@relay-harness/coding-agent 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +27 -6
  2. package/LICENSE +22 -0
  3. package/README.md +14 -16
  4. package/dist/bundle/chunks/{chunk-H6S6DQTM.js → chunk-6AEKWHDP.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-3QND5D7W.js → chunk-7ZBTLURV.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-WMTXXI7H.js → chunk-FUPU6X73.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-XDAWU2J5.js → chunk-IDUCLYG3.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-XSLAMYCK.js → chunk-LVFZRSZQ.js} +556 -62
  9. package/dist/bundle/chunks/{chunk-ISNO4JTR.js → chunk-PJWDW5WR.js} +2 -2
  10. package/dist/bundle/chunks/{chunk-3XNI2SB6.js → chunk-TZ2ZVU7E.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-MP5FU7MG.js → chunk-UVFWV6YH.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-PTRF7IZB.js → chunk-WU7MEKPF.js} +1 -1
  13. package/dist/bundle/chunks/{cli-K4CNHWOI.js → cli-2LN4J4IN.js} +1 -1
  14. package/dist/bundle/chunks/{easter-egg-3d-TGRCIHA4.js → easter-egg-3d-URCOHV3B.js} +1 -1
  15. package/dist/bundle/chunks/{execute-6E5DA2QI.js → execute-JAHDBPR2.js} +1 -1
  16. package/dist/bundle/chunks/{runtime-O5HLCH3V.js → runtime-TTSK6Y5T.js} +1 -1
  17. package/dist/bundle/chunks/{virtual-modules-FNVEVB65.js → virtual-modules-2G2P7CK2.js} +1 -1
  18. package/dist/bundle/cli-runtime.js +1 -1
  19. package/dist/bundle/index.js +1 -1
  20. package/dist/bundle/rpc-entry.js +1 -1
  21. package/dist/core/settings-manager.d.ts +5 -3
  22. package/dist/core/settings-manager.d.ts.map +1 -1
  23. package/dist/core/settings-manager.js.map +1 -1
  24. package/dist/extensions/laya/assessment.d.ts +7 -1
  25. package/dist/extensions/laya/assessment.d.ts.map +1 -1
  26. package/dist/extensions/laya/assessment.js +21 -1
  27. package/dist/extensions/laya/assessment.js.map +1 -1
  28. package/dist/extensions/laya/docker.d.ts +19 -0
  29. package/dist/extensions/laya/docker.d.ts.map +1 -0
  30. package/dist/extensions/laya/docker.js +44 -0
  31. package/dist/extensions/laya/docker.js.map +1 -0
  32. package/dist/extensions/laya/index.d.ts +12 -3
  33. package/dist/extensions/laya/index.d.ts.map +1 -1
  34. package/dist/extensions/laya/index.js +331 -67
  35. package/dist/extensions/laya/index.js.map +1 -1
  36. package/dist/extensions/laya/learn.d.ts +67 -0
  37. package/dist/extensions/laya/learn.d.ts.map +1 -0
  38. package/dist/extensions/laya/learn.js +263 -0
  39. package/dist/extensions/laya/learn.js.map +1 -0
  40. package/dist/extensions/laya/memory.d.ts +48 -0
  41. package/dist/extensions/laya/memory.d.ts.map +1 -0
  42. package/dist/extensions/laya/memory.js +107 -0
  43. package/dist/extensions/laya/memory.js.map +1 -0
  44. package/dist/extensions/laya/model-manifest.d.ts +1 -1
  45. package/dist/extensions/laya/model-manifest.js +1 -1
  46. package/dist/extensions/laya/model-manifest.js.map +1 -1
  47. package/dist/extensions/laya/routers.d.ts +8 -0
  48. package/dist/extensions/laya/routers.d.ts.map +1 -1
  49. package/dist/extensions/laya/routers.js +2 -0
  50. package/dist/extensions/laya/routers.js.map +1 -1
  51. package/dist/extensions/laya/runtime.d.ts +39 -49
  52. package/dist/extensions/laya/runtime.d.ts.map +1 -1
  53. package/dist/extensions/laya/runtime.js +93 -145
  54. package/dist/extensions/laya/runtime.js.map +1 -1
  55. package/dist/extensions/laya/server.d.ts +39 -15
  56. package/dist/extensions/laya/server.d.ts.map +1 -1
  57. package/dist/extensions/laya/server.js +219 -78
  58. package/dist/extensions/laya/server.js.map +1 -1
  59. package/dist/extensions/laya/train-script.d.ts +8 -0
  60. package/dist/extensions/laya/train-script.d.ts.map +1 -0
  61. package/dist/extensions/laya/train-script.js +422 -0
  62. package/dist/extensions/laya/train-script.js.map +1 -0
  63. package/dist/extensions/laya/training.d.ts +176 -0
  64. package/dist/extensions/laya/training.d.ts.map +1 -0
  65. package/dist/extensions/laya/training.js +337 -0
  66. package/dist/extensions/laya/training.js.map +1 -0
  67. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  68. package/dist/modes/interactive/components/config-selector.js +3 -2
  69. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  70. package/dist/modes/interactive/components/custom-message.js +1 -1
  71. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  72. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  73. package/dist/modes/interactive/interactive-mode.js +4 -4
  74. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  75. package/dist/modes/interactive/theme/dark.json +9 -9
  76. package/dist/modes/interactive/theme/light.json +9 -9
  77. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -1
  78. package/dist/modes/interactive/theme/system-theme.js +11 -10
  79. package/dist/modes/interactive/theme/system-theme.js.map +1 -1
  80. package/dist/utils/version-check.d.ts.map +1 -1
  81. package/dist/utils/version-check.js +10 -6
  82. package/dist/utils/version-check.js.map +1 -1
  83. package/docs/laya.md +59 -19
  84. package/docs/quickstart.md +19 -6
  85. package/docs/settings.md +4 -3
  86. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  87. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  88. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  89. package/examples/extensions/sandbox/package-lock.json +2 -2
  90. package/examples/extensions/sandbox/package.json +1 -1
  91. package/examples/extensions/with-deps/package-lock.json +2 -2
  92. package/examples/extensions/with-deps/package.json +1 -1
  93. package/package.json +15 -11
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{VisualLinePreview,formatSize,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs,truncateMiddle,writeOutputFile}from"./chunk-MP5FU7MG.js";import{Container,Spacer,Text,getAgentDir,getFileRevision,keyHint,normalizePath,require_cross_spawn,stripBom}from"./chunk-XDAWU2J5.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_polyfills=__commonJS({"node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
2
+ import{VisualLinePreview,formatSize,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs,truncateMiddle,writeOutputFile}from"./chunk-UVFWV6YH.js";import{Container,Spacer,Text,getAgentDir,getFileRevision,keyHint,normalizePath,require_cross_spawn,stripBom}from"./chunk-IDUCLYG3.js";import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.js";var require_polyfills=__commonJS({"node_modules/graceful-fs/polyfills.js"(exports,module){var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return cwd||(cwd=origCwd.call(process)),cwd};try{process.cwd()}catch{}typeof process.chdir=="function"&&(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,chdir));var chdir;module.exports=patch;function patch(fs){constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&patchLchmod(fs),fs.lutimes||patchLutimes(fs),fs.chown=chownFix(fs.chown),fs.fchown=chownFix(fs.fchown),fs.lchown=chownFix(fs.lchown),fs.chmod=chmodFix(fs.chmod),fs.fchmod=chmodFix(fs.fchmod),fs.lchmod=chmodFix(fs.lchmod),fs.chownSync=chownFixSync(fs.chownSync),fs.fchownSync=chownFixSync(fs.fchownSync),fs.lchownSync=chownFixSync(fs.lchownSync),fs.chmodSync=chmodFixSync(fs.chmodSync),fs.fchmodSync=chmodFixSync(fs.fchmodSync),fs.lchmodSync=chmodFixSync(fs.lchmodSync),fs.stat=statFix(fs.stat),fs.fstat=statFix(fs.fstat),fs.lstat=statFix(fs.lstat),fs.statSync=statFixSync(fs.statSync),fs.fstatSync=statFixSync(fs.fstatSync),fs.lstatSync=statFixSync(fs.lstatSync),fs.chmod&&!fs.lchmod&&(fs.lchmod=function(path,mode,cb){cb&&process.nextTick(cb)},fs.lchmodSync=function(){}),fs.chown&&!fs.lchown&&(fs.lchown=function(path,uid,gid,cb){cb&&process.nextTick(cb)},fs.lchownSync=function(){}),platform==="win32"&&(fs.rename=typeof fs.rename!="function"?fs.rename:(function(fs$rename){function rename(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<6e4){setTimeout(function(){fs.stat(to,function(stater,st){stater&&stater.code==="ENOENT"?fs$rename(from,to,CB):cb(er)})},backoff),backoff<100&&(backoff+=10);return}cb&&cb(er)})}return Object.setPrototypeOf&&Object.setPrototypeOf(rename,fs$rename),rename})(fs.rename)),fs.read=typeof fs.read!="function"?fs.read:(function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_=="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs,fd,buffer,offset,length,position,callback)}return Object.setPrototypeOf&&Object.setPrototypeOf(read,fs$read),read})(fs.read),fs.readSync=typeof fs.readSync!="function"?fs.readSync:(function(fs$readSync){return function(fd,buffer,offset,length,position){for(var eagCounter=0;;)try{return fs$readSync.call(fs,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}})(fs.readSync);function patchLchmod(fs2){fs2.lchmod=function(path,mode,callback){fs2.open(path,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){callback&&callback(err);return}fs2.fchmod(fd,mode,function(err2){fs2.close(fd,function(err22){callback&&callback(err2||err22)})})})},fs2.lchmodSync=function(path,mode){var fd=fs2.openSync(path,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs2.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}}function patchLutimes(fs2){constants.hasOwnProperty("O_SYMLINK")&&fs2.futimes?(fs2.lutimes=function(path,at,mt,cb){fs2.open(path,constants.O_SYMLINK,function(er,fd){if(er){cb&&cb(er);return}fs2.futimes(fd,at,mt,function(er2){fs2.close(fd,function(er22){cb&&cb(er2||er22)})})})},fs2.lutimesSync=function(path,at,mt){var fd=fs2.openSync(path,constants.O_SYMLINK),ret,threw=!0;try{ret=fs2.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs2.closeSync(fd)}catch{}else fs2.closeSync(fd)}return ret}):fs2.futimes&&(fs2.lutimes=function(_a,_b,_c,cb){cb&&process.nextTick(cb)},fs2.lutimesSync=function(){})}function chmodFix(orig){return orig&&function(target,mode,cb){return orig.call(fs,target,mode,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chmodFixSync(orig){return orig&&function(target,mode){try{return orig.call(fs,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){return orig&&function(target,uid,gid,cb){return orig.call(fs,target,uid,gid,function(er){chownErOk(er)&&(er=null),cb&&cb.apply(this,arguments)})}}function chownFixSync(orig){return orig&&function(target,uid,gid){try{return orig.call(fs,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){return orig&&function(target,options,cb){typeof options=="function"&&(cb=options,options=null);function callback(er,stats){stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),cb&&cb.apply(this,arguments)}return options?orig.call(fs,target,options,callback):orig.call(fs,target,callback)}}function statFixSync(orig){return orig&&function(target,options){var stats=options?orig.call(fs,target,options):orig.call(fs,target);return stats&&(stats.uid<0&&(stats.uid+=4294967296),stats.gid<0&&(stats.gid+=4294967296)),stats}}function chownErOk(er){if(!er||er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;return!!(nonroot&&(er.code==="EINVAL"||er.code==="EPERM"))}}}});var require_legacy_streams=__commonJS({"node_modules/graceful-fs/legacy-streams.js"(exports,module){var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs){return{ReadStream,WriteStream};function ReadStream(path,options){if(!(this instanceof ReadStream))return new ReadStream(path,options);Stream.call(this);var self=this;this.path=path,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path,options){if(!(this instanceof WriteStream))return new WriteStream(path,options);Stream.call(this),this.path=path,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};for(var keys=Object.keys(options),index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=fs.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}}});var require_clone=__commonJS({"node_modules/graceful-fs/clone.js"(exports,module){"use strict";module.exports=clone;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone(obj){if(obj===null||typeof obj!="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}}});var require_graceful_fs=__commonJS({"node_modules/graceful-fs/graceful-fs.js"(exports,module){var fs=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;typeof Symbol=="function"&&typeof Symbol.for=="function"?(gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous")):(gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous");function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;util.debuglog?debug=util.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
3
3
  GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],publishQueue(fs,queue),fs.close=(function(fs$close){function close(fd,cb){return fs$close.call(fs,fd,function(err){err||resetQueue(),typeof cb=="function"&&cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close})(fs.close),fs.closeSync=(function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync})(fs.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){debug(fs[gracefulQueue]),__require("assert").equal(fs[gracefulQueue].length,0)}));var queue;global[gracefulQueue]||publishQueue(global,fs[gracefulQueue]);module.exports=patch(clone(fs));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs.__patched&&(module.exports=patch(fs),fs.__patched=!0);function patch(fs2){polyfills(fs2),fs2.gracefulify=patch,fs2.createReadStream=createReadStream,fs2.createWriteStream=createWriteStream;var fs$readFile=fs2.readFile;fs2.readFile=readFile;function readFile(path,options,cb){return typeof options=="function"&&(cb=options,options=null),go$readFile(path,options,cb);function go$readFile(path2,options2,cb2,startTime){return fs$readFile(path2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readFile,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$writeFile=fs2.writeFile;fs2.writeFile=writeFile;function writeFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$writeFile(path,data,options,cb);function go$writeFile(path2,data2,options2,cb2,startTime){return fs$writeFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$writeFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$appendFile=fs2.appendFile;fs$appendFile&&(fs2.appendFile=appendFile);function appendFile(path,data,options,cb){return typeof options=="function"&&(cb=options,options=null),go$appendFile(path,data,options,cb);function go$appendFile(path2,data2,options2,cb2,startTime){return fs$appendFile(path2,data2,options2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$appendFile,[path2,data2,options2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$copyFile=fs2.copyFile;fs$copyFile&&(fs2.copyFile=copyFile);function copyFile(src,dest,flags,cb){return typeof flags=="function"&&(cb=flags,flags=0),go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}var fs$readdir=fs2.readdir;fs2.readdir=readdir;var noReaddirOptionVersions=/^v[0-5]\./;function readdir(path,options,cb){typeof options=="function"&&(cb=options,options=null);var go$readdir=noReaddirOptionVersions.test(process.version)?function(path2,options2,cb2,startTime){return fs$readdir(path2,fs$readdirCallback(path2,options2,cb2,startTime))}:function(path2,options2,cb2,startTime){return fs$readdir(path2,options2,fs$readdirCallback(path2,options2,cb2,startTime))};return go$readdir(path,options,cb);function fs$readdirCallback(path2,options2,cb2,startTime){return function(err,files){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$readdir,[path2,options2,cb2],err,startTime||Date.now(),Date.now()]):(files&&files.sort&&files.sort(),typeof cb2=="function"&&cb2.call(this,err,files))}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs2);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs2.ReadStream;fs$ReadStream&&(ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open);var fs$WriteStream=fs2.WriteStream;fs$WriteStream&&(WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open),Object.defineProperty(fs2,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs2,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs2,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs2,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path,options){return this instanceof ReadStream?(fs$ReadStream.apply(this,arguments),this):ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.autoClose&&that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd),that.read())})}function WriteStream(path,options){return this instanceof WriteStream?(fs$WriteStream.apply(this,arguments),this):WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){err?(that.destroy(),that.emit("error",err)):(that.fd=fd,that.emit("open",fd))})}function createReadStream(path,options){return new fs2.ReadStream(path,options)}function createWriteStream(path,options){return new fs2.WriteStream(path,options)}var fs$open=fs2.open;fs2.open=open;function open(path,flags,mode,cb){return typeof mode=="function"&&(cb=mode,mode=null),go$open(path,flags,mode,cb);function go$open(path2,flags2,mode2,cb2,startTime){return fs$open(path2,flags2,mode2,function(err,fd){err&&(err.code==="EMFILE"||err.code==="ENFILE")?enqueue([go$open,[path2,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]):typeof cb2=="function"&&cb2.apply(this,arguments)})}}return fs2}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){for(var now=Date.now(),i=0;i<fs[gracefulQueue].length;++i)fs[gracefulQueue][i].length>2&&(fs[gracefulQueue][i][3]=now,fs[gracefulQueue][i][4]=now);retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs[gracefulQueue].length!==0){var elem=fs[gracefulQueue].shift(),fn=elem[0],args=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn.name,args),fn.apply(null,args);else if(Date.now()-startTime>=6e4){debug("TIMEOUT",fn.name,args);var cb=args.pop();typeof cb=="function"&&cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);sinceAttempt>=desiredDelay?(debug("RETRY",fn.name,args),fn.apply(null,args.concat([startTime]))):fs[gracefulQueue].push(elem)}retryTimer===void 0&&(retryTimer=setTimeout(retry,0))}}}});var require_retry_operation=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports,module){function RetryOperation(timeouts,options){typeof options=="boolean"&&(options={forever:options}),this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout&&clearTimeout(this._timeout),!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){self._attempts++,self._operationTimeoutCb&&(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref&&self._timeout.unref()),self._fn(self._attempts)},timeout);return this._options.unref&&timer.unref(),!0};RetryOperation.prototype.attempt=function(fn,timeoutOps){this._fn=fn,timeoutOps&&(timeoutOps.timeout&&(this._operationTimeout=timeoutOps.timeout),timeoutOps.cb&&(this._operationTimeoutCb=timeoutOps.cb));var self=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=function(fn){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;for(var counts={},mainError=null,mainErrorCount=0,i=0;i<this._errors.length;i++){var error=this._errors[i],message=error.message,count=(counts[message]||0)+1;counts[message]=count,count>=mainErrorCount&&(mainError=error,mainErrorCount=count)}return mainError}}});var require_retry=__commonJS({"node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports){var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var timeouts=[],i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));return options&&options.forever&&!timeouts.length&&timeouts.push(this.createTimeout(i,opts)),timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array&&(methods=options,options=null),!methods){methods=[];for(var key in obj)typeof obj[key]=="function"&&methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args=Array.prototype.slice.call(arguments,1),callback=args.pop();args.push(function(err){op.retry(err)||(err&&(arguments[0]=op.mainError()),callback.apply(this,arguments))}),op.attempt(function(){original2.apply(obj,args)})}.bind(obj,original),obj[method].options=options}}}});var require_retry2=__commonJS({"node_modules/proper-lockfile/node_modules/retry/index.js"(exports,module){module.exports=require_retry()}});var require_signals=__commonJS({"node_modules/signal-exit/signals.js"(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")}});var require_signal_exit=__commonJS({"node_modules/signal-exit/index.js"(exports,module){var process3=global.process,processOk=function(process4){return process4&&typeof process4=="object"&&typeof process4.removeListener=="function"&&typeof process4.emit=="function"&&typeof process4.reallyExit=="function"&&typeof process4.listeners=="function"&&typeof process4.kill=="function"&&typeof process4.pid=="number"&&typeof process4.on=="function"};processOk(process3)?(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!="function"&&(EE=EE.EventEmitter),process3.__signal_exit_emitter__?emitter=process3.__signal_exit_emitter__:(emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={}),emitter.infinite||(emitter.setMaxListeners(1/0),emitter.infinite=!0),module.exports=function(cb,opts){if(!processOk(global.process))return function(){};assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1&&load();var ev="exit";opts&&opts.alwaysLast&&(ev="afterexit");var remove=function(){emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0&&unload()};return emitter.on(ev,cb),remove},unload=function(){!loaded||!processOk(global.process)||(loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch{}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1)},module.exports.unload=unload,emit=function(event,code,signal){emitter.emitted[event]||(emitter.emitted[event]=!0,emitter.emit(event,code,signal))},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(processOk(global.process)){var listeners=process3.listeners(sig);listeners.length===emitter.count&&(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP"&&(sig="SIGINT"),process3.kill(process3.pid,sig))}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){loaded||!processOk(global.process)||(loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch{return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit)},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){processOk(global.process)&&(process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode))},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){arg!==void 0&&(process3.exitCode=arg);var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}):module.exports=function(){return function(){}};var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit}});var require_mtime_precision=__commonJS({"node_modules/proper-lockfile/lib/mtime-precision.js"(exports,module){"use strict";var cacheSymbol=Symbol();function probe(file,fs,callback){let cachedPrecision=fs[cacheSymbol];if(cachedPrecision)return fs.stat(file,(err,stat)=>{if(err)return callback(err);callback(null,stat.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1e3)*1e3+5);fs.utimes(file,mtime,mtime,err=>{if(err)return callback(err);fs.stat(file,(err2,stat)=>{if(err2)return callback(err2);let precision=stat.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(fs,cacheSymbol,{value:precision}),callback(null,stat.mtime,precision)})})}function getMtime(precision){let now=Date.now();return precision==="s"&&(now=Math.ceil(now/1e3)*1e3),new Date(now)}module.exports.probe=probe;module.exports.getMtime=getMtime}});var require_lockfile=__commonJS({"node_modules/proper-lockfile/lib/lockfile.js"(exports,module){"use strict";var path=__require("path"),fs=require_graceful_fs(),retry=require_retry2(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file,options){return options.lockfilePath||`${file}.lock`}function resolveCanonicalPath(file,options,callback){if(!options.realpath)return callback(null,path.resolve(file));options.fs.realpath(file,callback)}function acquireLock(file,options,callback){let lockfilePath=getLockFile(file,options);options.fs.mkdir(lockfilePath,err=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));options.fs.stat(lockfilePath,(err2,stat)=>{if(err2)return err2.code==="ENOENT"?acquireLock(file,{...options,stale:0},callback):callback(err2);if(!isLockStale(stat,options))return callback(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file}));removeLock(file,options,err3=>{if(err3)return callback(err3);acquireLock(file,{...options,stale:0},callback)})})})}function isLockStale(stat,options){return stat.mtime.getTime()<Date.now()-options.stale}function removeLock(file,options,callback){options.fs.rmdir(getLockFile(file,options),err=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file,options){let lock2=locks[file];lock2.updateTimeout||(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err)return err.code==="ENOENT"||isOverThreshold?setLockAsCompromised(file,lock2,Object.assign(err,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));if(!(lock2.mtime.getTime()===stat.mtime.getTime()))return setLockAsCompromised(file,lock2,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,err2=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(!lock2.released){if(err2)return err2.code==="ENOENT"||isOverThreshold2?setLockAsCompromised(file,lock2,Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(file,options));lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file,options)}})})},lock2.updateDelay),lock2.updateTimeout.unref&&lock2.updateTimeout.unref())}function setLockAsCompromised(file,lock2,err){lock2.released=!0,lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),locks[file]===lock2&&delete locks[file],lock2.options.onCompromised(err)}function lock(file,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs,onCompromised:err=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries=="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2e3),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file2,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file2]={lockfilePath:getLockFile(file2,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file2,options),callback(null,releasedCallback=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));unlock(file2,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file,options,callback){options={fs,realpath:!0,...options},resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);let lock2=locks[file2];if(!lock2)return callback(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file2],removeLock(file2,options,callback)})}function check(file,options,callback){options={stale:1e4,realpath:!0,fs,...options},options.stale=Math.max(options.stale||0,2e3),resolveCanonicalPath(file,options,(err,file2)=>{if(err)return callback(err);options.fs.stat(getLockFile(file2,options),(err2,stat)=>err2?err2.code==="ENOENT"?callback(null,!1):callback(err2):callback(null,!isLockStale(stat,options)))})}function getLocks(){return locks}onExit(()=>{for(let file in locks){let options=locks[file].options;try{options.fs.rmdirSync(getLockFile(file,options))}catch{}}});module.exports.lock=lock;module.exports.unlock=unlock;module.exports.check=check;module.exports.getLocks=getLocks}});var require_adapter=__commonJS({"node_modules/proper-lockfile/lib/adapter.js"(exports,module){"use strict";var fs=require_graceful_fs();function createSyncFs(fs2){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs2};return methods.forEach(method=>{newFs[method]=(...args)=>{let callback=args.pop(),ret;try{ret=fs2[`${method}Sync`](...args)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args)=>new Promise((resolve,reject)=>{args.push((err,result)=>{err?reject(err):resolve(result)}),method(...args)})}function toSync(method){return(...args)=>{let err,result;if(args.push((_err,_result)=>{err=_err,result=_result}),method(...args),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs),typeof options.retries=="number"&&options.retries>0||options.retries&&typeof options.retries.retries=="number"&&options.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}}});var require_proper_lockfile=__commonJS({"node_modules/proper-lockfile/index.js"(exports,module){"use strict";var lockfile2=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file,options){let release=await toPromise(lockfile2.lock)(file,options);return toPromise(release)}function lockSync(file,options){let release=toSync(lockfile2.lock)(file,toSyncOptions(options));return toSync(release)}function unlock(file,options){return toPromise(lockfile2.unlock)(file,options)}function unlockSync(file,options){return toSync(lockfile2.unlock)(file,toSyncOptions(options))}function check(file,options){return toPromise(lockfile2.check)(file,options)}function checkSync(file,options){return toSync(lockfile2.check)(file,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check;module.exports.checkSync=checkSync}});import{execSync,spawnSync}from"child_process";var commandResultCache=new Map,ENV_VAR_NAME_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,ENV_VAR_NAME_PREFIX_RE=/^[A-Za-z_][A-Za-z0-9_]*/;function appendLiteral(parts,value){if(!value)return;let previousPart=parts[parts.length-1];if(previousPart?.type==="literal"){previousPart.value+=value;return}parts.push({type:"literal",value})}function parseConfigValueTemplate(config){let parts=[],index=0;for(;index<config.length;){let dollarIndex=config.indexOf("$",index);if(dollarIndex<0){appendLiteral(parts,config.slice(index));break}appendLiteral(parts,config.slice(index,dollarIndex));let nextChar=config[dollarIndex+1];if(nextChar==="$"||nextChar==="!"){appendLiteral(parts,nextChar),index=dollarIndex+2;continue}if(nextChar==="{"){let endIndex=config.indexOf("}",dollarIndex+2);if(endIndex<0){appendLiteral(parts,"$"),index=dollarIndex+1;continue}let name=config.slice(dollarIndex+2,endIndex);ENV_VAR_NAME_RE.test(name)?parts.push({type:"env",name}):appendLiteral(parts,config.slice(dollarIndex,endIndex+1)),index=endIndex+1;continue}let match=config.slice(dollarIndex+1).match(ENV_VAR_NAME_PREFIX_RE);if(match){parts.push({type:"env",name:match[0]}),index=dollarIndex+1+match[0].length;continue}appendLiteral(parts,"$"),index=dollarIndex+1}return parts}function parseConfigValueReference(config){return config.startsWith("!")?{type:"command",config}:{type:"template",parts:parseConfigValueTemplate(config)}}function resolveEnvConfigValue(name,env){return env?.[name]||process.env[name]||void 0}function getTemplateEnvVarNames(parts){let names=[];for(let part of parts)part.type!=="env"||names.includes(part.name)||names.push(part.name);return names}function resolveTemplate(parts,env){let resolved="";for(let part of parts){if(part.type==="literal"){resolved+=part.value;continue}let envValue=resolveEnvConfigValue(part.name,env);if(envValue===void 0)return;resolved+=envValue}return resolved}function getConfigValueEnvVarNames(config){let reference=parseConfigValueReference(config);return reference.type==="template"?getTemplateEnvVarNames(reference.parts):[]}function getMissingConfigValueEnvVarNames(config,env){return getConfigValueEnvVarNames(config).filter(name=>resolveEnvConfigValue(name,env)===void 0)}function isCommandConfigValue(config){return parseConfigValueReference(config).type==="command"}function isConfigValueConfigured(config,env){return getMissingConfigValueEnvVarNames(config,env).length===0}function resolveConfigValue(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommand(reference.config):resolveTemplate(reference.parts,env)}function executeWithConfiguredShell(command){try{let{shell,args,commandTransport}=getShellConfig(),commandFromStdin=commandTransport==="stdin",result=spawnSync(shell,commandFromStdin?args:[...args,command],{encoding:"utf-8",input:commandFromStdin?command:void 0,timeout:1e4,stdio:[commandFromStdin?"pipe":"ignore","pipe","ignore"],shell:!1,windowsHide:!0});return result.error?result.error.code==="ENOENT"?{executed:!1,value:void 0}:{executed:!0,value:void 0}:result.status!==0?{executed:!0,value:void 0}:{executed:!0,value:(result.stdout??"").trim()||void 0}}catch{return{executed:!1,value:void 0}}}function executeWithDefaultShell(command){try{return execSync(command,{encoding:"utf-8",timeout:1e4,stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function executeCommandUncached(commandConfig){let command=commandConfig.slice(1);return process.platform==="win32"?(()=>{let configuredResult=executeWithConfiguredShell(command);return configuredResult.executed?configuredResult.value:executeWithDefaultShell(command)})():executeWithDefaultShell(command)}function executeCommand(commandConfig){if(commandResultCache.has(commandConfig))return commandResultCache.get(commandConfig);let result=executeCommandUncached(commandConfig);return commandResultCache.set(commandConfig,result),result}function resolveConfigValueUncached(config,env){let reference=parseConfigValueReference(config);return reference.type==="command"?executeCommandUncached(reference.config):resolveTemplate(reference.parts,env)}function resolveConfigValueOrThrow(config,description,env){let resolvedValue=resolveConfigValueUncached(config,env);if(resolvedValue!==void 0)return resolvedValue;let reference=parseConfigValueReference(config);if(reference.type==="command")throw new Error(`Failed to resolve ${description} from shell command: ${reference.config.slice(1)}`);if(reference.type==="template"){let missingEnvVars=getMissingConfigValueEnvVarNames(config,env);if(missingEnvVars.length===1)throw new Error(`Failed to resolve ${description} from environment variable: ${missingEnvVars[0]}`);if(missingEnvVars.length>1)throw new Error(`Failed to resolve ${description} from environment variables: ${missingEnvVars.join(", ")}`)}throw new Error(`Failed to resolve ${description}`)}function resolveHeadersOrThrow(headers,description,env){if(!headers)return;let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolveConfigValueOrThrow(value,`${description} header "${key}"`,env);return Object.keys(resolved).length>0?resolved:void 0}var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import{existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";import{setTimeout as sleep}from"timers/promises";function abortReason(signal){if(signal.reason!==void 0)return signal.reason;let error=new Error("The operation was aborted");return error.name="AbortError",error}function operationSignal(signal){return signal??new AbortController().signal}function raceWithAbortSignal(operation,signal){return signal?signal.aborted?(operation.catch(()=>{}),Promise.reject(abortReason(signal))):new Promise((resolve,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()}):operation}var AUTH_FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384},sharedAuthFileReadState,FileAuthStorageBackend=class{authPath;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}ensureParentDir(){let dir=dirname(this.authPath);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}ensureFileExists(){existsSync(this.authPath)||writeFileSync(this.authPath,"{}",AUTH_FILE_WRITE_OPTIONS)}acquireLockSyncWithRetry(path){let lastError;for(let attempt=1;attempt<=10;attempt++)try{return import_proper_lockfile.default.lockSync(path,{realpath:!1})}catch(error){if((typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0)!=="ELOCKED"||attempt===10)throw error;lastError=error;let start=Date.now();for(;Date.now()-start<20;);}throw lastError??new Error("Failed to acquire auth storage lock")}withLock(fn){this.ensureParentDir(),this.ensureFileExists();let release;try{release=this.acquireLockSyncWithRetry(this.authPath);let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=fn(current);return next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),result}finally{release&&release()}}async acquireLockAsync(signal,onCompromised){let deadline=Date.now()+3e4,retry=0;for(;;){signal?.throwIfAborted();let release;try{release=await import_proper_lockfile.default.lock(this.authPath,{realpath:!1,retries:0,stale:3e4,onCompromised})}catch(error){signal?.throwIfAborted();let code=typeof error=="object"&&error!==null&&"code"in error?String(error.code):void 0,remainingMs=deadline-Date.now();if(code!=="ELOCKED"||remainingMs<=0)throw error;let baseDelayMs=Math.min(10*2**retry,2e3/2);retry++;let delayMs=Math.min(Math.round(baseDelayMs*(1+Math.random())),remainingMs);signal?await sleep(delayMs,void 0,{signal}):await sleep(delayMs);continue}return signal?.aborted&&(await release(),signal.throwIfAborted()),release}}async withLockAsync(fn,options){options?.signal?.throwIfAborted(),this.ensureParentDir(),this.ensureFileExists();let release,lockCompromised=!1,lockCompromisedError,throwIfCompromised=()=>{if(lockCompromised)throw lockCompromisedError??new Error("Auth storage lock was compromised")};try{release=await this.acquireLockAsync(options?.signal,error=>{lockCompromised=!0,lockCompromisedError=error}),throwIfCompromised(),options?.signal?.throwIfAborted();let current=existsSync(this.authPath)?readFileSync(this.authPath,"utf-8"):void 0,{result,next}=await fn(current);return throwIfCompromised(),options?.signal?.throwIfAborted(),next!==void 0&&writeFileSync(this.authPath,next,AUTH_FILE_WRITE_OPTIONS),throwIfCompromised(),result}finally{if(release)try{await release()}catch{}}}},ReadOnlyAuthStorage=class{authPath;data;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}load(){if(this.data)return this.data;let parsed;try{parsed=JSON.parse(stripBom(readFileSync(this.authPath,"utf-8")))}catch(error){if(error.code==="ENOENT")return this.data={},this.data;throw new Error(`Failed to read auth.json: ${error instanceof Error?error.message:String(error)}`)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new Error("Invalid auth.json: expected an object");for(let[providerId,credential]of Object.entries(parsed)){if(typeof credential!="object"||credential===null||Array.isArray(credential))throw new Error(`Invalid auth.json credential for provider "${providerId}"`);let value=credential;if(value.type==="api_key"){let validKey=value.key===void 0||typeof value.key=="string",validEnv=value.env===void 0||typeof value.env=="object"&&value.env!==null&&!Array.isArray(value.env)&&Object.values(value.env).every(entry=>typeof entry=="string");if(validKey&&validEnv)continue}else if(value.type==="oauth"&&typeof value.access=="string"&&typeof value.refresh=="string"&&typeof value.expires=="number"&&Number.isFinite(value.expires))continue;throw new Error(`Invalid auth.json credential for provider "${providerId}"`)}return this.data=parsed,this.data}async read(providerId,options){options?.signal?.throwIfAborted();let credential=this.load()[providerId];if(options?.signal?.throwIfAborted(),!!credential)return credential.type!=="api_key"||!credential.key||isCommandConfigValue(credential.key)?structuredClone(credential):{...credential,key:resolveConfigValue(credential.key,credential.env)}}async list(options){options?.signal?.throwIfAborted();let credentials=Object.entries(this.load()).map(([providerId,credential])=>({providerId,type:credential.type}));return options?.signal?.throwIfAborted(),credentials}async modify(_providerId,_fn,_options){throw new Error("Read-only credential storage cannot modify auth.json")}async delete(_providerId,_options){throw new Error("Read-only credential storage cannot modify auth.json")}},InMemoryAuthStorageBackend=class{value;asyncChain=Promise.resolve();withLock(fn){let{result,next}=fn(this.value);return next!==void 0&&(this.value=next),result}withLockAsync(fn,options){let previous=this.asyncChain,operation=(async()=>{await previous.catch(()=>{}),options?.signal?.throwIfAborted();let{result,next}=await fn(this.value);return options?.signal?.throwIfAborted(),next!==void 0&&(this.value=next),result})();return this.asyncChain=operation.catch(()=>{}),raceWithAbortSignal(operation,options?.signal)}},AuthStorage=class _AuthStorage{storage;authPath;readState;constructor(storage,authPath){if(this.storage=storage,this.authPath=authPath,this.readState=authPath&&sharedAuthFileReadState?.authPath===authPath?sharedAuthFileReadState.readState:{data:{}},authPath&&!sharedAuthFileReadState&&(sharedAuthFileReadState={authPath,readState:this.readState}),authPath){let revision=getFileRevision(authPath);if(revision!==void 0&&revision===this.readState.revision)return}this.reload()}static create(authPath=join(getAgentDir(),"auth.json")){let normalizedAuthPath=normalizePath(authPath);return new _AuthStorage(new FileAuthStorageBackend(normalizedAuthPath),normalizedAuthPath)}static fromStorage(storage){return new _AuthStorage(storage)}static inMemory(data={}){let storage=new InMemoryAuthStorageBackend;return storage.withLock(()=>({result:void 0,next:JSON.stringify(data,null,2)})),_AuthStorage.fromStorage(storage)}parseStorageData(content){return content?JSON.parse(stripBom(content)):{}}updateReadState(data,revision){this.readState.data=data,this.readState.revision=revision}reload(){let content,revision;try{this.storage.withLock(current=>(content=current,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:void 0})),this.updateReadState(this.parseStorageData(content),revision)}catch{}}async reloadFromStorageAsync(options){return this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),revision=this.authPath?getFileRevision(this.authPath):void 0;return this.updateReadState(currentData,revision),{result:currentData}},options)}async readLatestData(options){if(options?.signal?.throwIfAborted(),!this.authPath){let reload2=this.reloadFromStorageAsync(options);return options?.signal?reload2:reload2.catch(()=>this.readState.data)}let revision=getFileRevision(this.authPath);if(revision!==void 0&&revision===this.readState.revision)return this.readState.data;if(!this.readState.reload){let controller=new AbortController,reload2={controller,promise:this.reloadFromStorageAsync({signal:controller.signal}),readers:0};this.readState.reload=reload2,reload2.promise.then(()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)},()=>{this.readState.reload===reload2&&(this.readState.reload=void 0)})}let reload=this.readState.reload;reload.readers++;try{let result=raceWithAbortSignal(reload.promise,options?.signal);return options?.signal?await result:await result.catch(()=>this.readState.data)}finally{reload.readers--,reload.readers===0&&this.readState.reload===reload&&(this.readState.reload=void 0,reload.controller.abort())}}async read(provider,options){let credential=(await this.readLatestData(options))[provider];return options?.signal?.throwIfAborted(),credential?.type!=="api_key"||credential.key===void 0?credential:{...credential,key:resolveConfigValue(credential.key,credential.env)}}async modify(provider,fn,options){let latestData=this.readState.data,revision,result=await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content),next=await fn(currentData[provider]);if(next===void 0)return latestData=currentData,revision=this.authPath?getFileRevision(this.authPath):void 0,{result:currentData[provider]};let merged={...currentData,[provider]:next};return latestData=merged,{result:next,next:JSON.stringify(merged,null,2)}},options);return this.updateReadState(latestData,revision),result}async delete(provider,options){let latestData=this.readState.data;await this.storage.withLockAsync(async content=>{let currentData=this.parseStorageData(content);return delete currentData[provider],latestData=currentData,{result:void 0,next:JSON.stringify(currentData,null,2)}},options),this.updateReadState(latestData)}async list(options){let entries=Object.entries(await this.readLatestData(options));return options?.signal?.throwIfAborted(),entries.map(([providerId,credential])=>({providerId,type:credential.type}))}};function readStoredCredential(providerId,authPath=join(getAgentDir(),"auth.json")){try{return JSON.parse(stripBom(readFileSync(normalizePath(authPath),"utf-8")))[providerId]}catch{return}}var MCP_EXPOSURES=["codemode","deferred","direct","hidden"],MCP_EXPOSURE_ALIASES={"codemode-deferred":"codemode"},LOOPBACK_HOSTS=["localhost","127.0.0.1","[::1]"];function isLoopbackRedirectUri(value){if(!URL.canParse(value))return!1;let url=new URL(value);return url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)&&url.search===""&&url.hash===""}var SERVER_NAME=/^[A-Za-z0-9_-]+$/;function mcpNamespace(server){return`mcp__${server.replace(/-/g,"_")}`}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStringRecord(value){return isRecord(value)&&Object.values(value).every(entry=>typeof entry=="string")}function validateOAuth(value){if(value===void 0)return;if(!isRecord(value))return"oauth must be an object";if(value.clientId!==void 0&&typeof value.clientId!="string")return"oauth.clientId must be a string";if(value.clientSecret!==void 0&&typeof value.clientSecret!="string")return"oauth.clientSecret must be a string";let port=value.callbackPort;if(port!==void 0&&(typeof port!="number"||!Number.isInteger(port)||port<1||port>65535))return"oauth.callbackPort must be a port number";if(value.callbackUrl!==void 0){if(typeof value.callbackUrl!="string"||!isLoopbackRedirectUri(value.callbackUrl))return"oauth.callbackUrl must be an http URI on localhost, 127.0.0.1, or [::1] without query or fragment";let urlPort=new URL(value.callbackUrl).port;if(urlPort&&port!==void 0&&Number(urlPort)!==port)return"oauth.callbackUrl and oauth.callbackPort name different ports"}if(value.scope!==void 0&&typeof value.scope!="string")return"oauth.scope must be a string";if(value.clientName!==void 0&&(typeof value.clientName!="string"||!value.clientName.trim()))return"oauth.clientName must be a non-empty string";let metadataUrl=value.authServerMetadataUrl;if(metadataUrl!==void 0){let url=typeof metadataUrl=="string"&&URL.canParse(metadataUrl)?new URL(metadataUrl):void 0;if(!url||!(url.protocol==="https:"||url.protocol==="http:"&&LOOPBACK_HOSTS.includes(url.hostname)))return"oauth.authServerMetadataUrl must be an https URL, or http on localhost, 127.0.0.1, or [::1]"}}function isExposure(value){return typeof value=="string"&&MCP_EXPOSURES.includes(value)}function resolveExposureAlias(value){return typeof value=="string"?MCP_EXPOSURE_ALIASES[value]??value:value}function resolveExposureAliases(value){let{exposure,toolExposure}=value,resolved={...value};return exposure!==void 0&&(resolved.exposure=resolveExposureAlias(exposure)),isRecord(toolExposure)&&(resolved.toolExposure=Object.fromEntries(Object.entries(toolExposure).map(([tool,entry])=>[tool,resolveExposureAlias(entry)]))),resolved}function toolPatternRegExp(pattern){let source=pattern.split("*").map(part=>part.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${source}$`)}function getMcpToolExposure(config,toolName){let overrides=config.toolExposure??{},exact=overrides[toolName];if(exact!==void 0)return exact;for(let[pattern,exposure]of Object.entries(overrides))if(pattern.includes("*")&&toolPatternRegExp(pattern).test(toolName))return exposure;return config.exposure??"codemode"}function validateMcpServerConfig(name,raw){if(!SERVER_NAME.test(name))return`invalid server name "${name}" (use letters, digits, "_" and "-")`;if(!isRecord(raw))return`server "${name}" must be an object`;let value=resolveExposureAliases(raw),{type,exposure,enabled,timeout,toolExposure,description}=value,exposures=MCP_EXPOSURES.map(value2=>`"${value2}"`).join(", ");if(exposure!==void 0&&!isExposure(exposure))return`server "${name}": exposure must be one of ${exposures}`;if(toolExposure!==void 0){if(!isRecord(toolExposure))return`server "${name}": toolExposure must map tool names to exposures`;for(let[tool,value2]of Object.entries(toolExposure))if(!isExposure(value2))return`server "${name}": toolExposure "${tool}" must be one of ${exposures}`}if(enabled!==void 0&&typeof enabled!="boolean")return`server "${name}": enabled must be a boolean`;if(description!==void 0&&typeof description!="string")return`server "${name}": description must be a string`;if(timeout!==void 0&&(typeof timeout!="number"||!(timeout>0)))return`server "${name}": timeout must be a positive number of seconds`;if(type==="sse")return`server "${name}": legacy SSE transport is not supported; use the streamable HTTP URL`;if(typeof value.url=="string"&&(type===void 0||type==="http"||type==="streamable-http")){if(!URL.canParse(value.url)||!/^https?:$/.test(new URL(value.url).protocol))return`server "${name}": url must be an http or https URL`;if(value.headers!==void 0&&!isStringRecord(value.headers))return`server "${name}": headers must map names to strings`;let oauthError=validateOAuth(value.oauth);if(oauthError)return`server "${name}": ${oauthError}`;if(value.auth!==void 0){if(!isRecord(value.auth)||typeof value.auth.provider!="string"||!value.auth.provider)return`server "${name}": auth.provider must be a provider name`;let url=new URL(value.url);if(url.protocol!=="https:"&&!LOOPBACK_HOSTS.includes(url.hostname))return`server "${name}": auth requires an https URL, or http on localhost, 127.0.0.1, or [::1]`}return value}return typeof value.command=="string"&&(type===void 0||type==="stdio")?value.args!==void 0&&!(Array.isArray(value.args)&&value.args.every(arg=>typeof arg=="string"))?`server "${name}": args must be an array of strings`:value.env!==void 0&&!isStringRecord(value.env)?`server "${name}": env must map names to strings`:value.cwd!==void 0&&typeof value.cwd!="string"?`server "${name}": cwd must be a string`:value:`server "${name}" needs either "command" (stdio) or "url" (streamable HTTP)`}var McpServerRegistry=class{servers=new Map;changeListener;register(server){this.servers.set(server.name,server),this.changeListener?.()}unregister(name,extensionPath){this.servers.get(name)?.extensionPath===extensionPath&&(this.servers.delete(name),this.changeListener?.())}get(name){return this.servers.get(name)}list(){return[...this.servers.values()].map(server=>({...server,config:structuredClone(server.config)}))}setChangeListener(listener){this.changeListener=listener}};var JSON_RPC_ERROR_CODES={parseError:-32700,invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internalError:-32603},McpError=class extends Error{code;data;constructor(code,message,data){super(message),this.name="McpError",this.code=code,this.data=data}},McpConnectionClosedError=class extends Error{constructor(message="MCP connection closed"){super(message),this.name="McpConnectionClosedError"}},McpTimeoutError=class extends Error{timeoutMs;constructor(timeoutMs){super(`MCP request timed out after ${timeoutMs}ms`),this.name="McpTimeoutError",this.timeoutMs=timeoutMs}},McpAbortError=class extends Error{constructor(message="MCP request aborted"){super(message),this.name="AbortError"}};function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function toError(value){return value instanceof Error?value:new Error(String(value))}function isJsonRpcId(value){return typeof value=="string"||typeof value=="number"&&Number.isFinite(value)}function isJsonRpcRequest(message){return isObject(message)&&message.jsonrpc==="2.0"&&isJsonRpcId(message.id)&&typeof message.method=="string"}function isJsonRpcNotification(message){return isObject(message)&&message.jsonrpc==="2.0"&&!("id"in message)&&typeof message.method=="string"}function isJsonRpcResponse(message){return!isObject(message)||message.jsonrpc!=="2.0"||!isJsonRpcId(message.id)?!1:"result"in message?!("error"in message):!("error"in message)||!isObject(message.error)?!1:typeof message.error.code=="number"&&typeof message.error.message=="string"}function parseJsonRpcMessage(value){if(isJsonRpcRequest(value)||isJsonRpcNotification(value)||isJsonRpcResponse(value))return value;throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid JSON-RPC message")}var LATEST_PROTOCOL_VERSION="2025-11-25",SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05"];var DEFAULT_REQUEST_TIMEOUT_MS=3e4,MAX_LIST_PAGES=1e3;function validateInitializeResult(value){if(!isObject(value)||typeof value.protocolVersion!="string"||!isObject(value.capabilities)||!isObject(value.serverInfo)||typeof value.serverInfo.name!="string"||typeof value.serverInfo.version!="string"||value.instructions!==void 0&&typeof value.instructions!="string")throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP initialize result");return value}function invalid(message){return new McpError(JSON_RPC_ERROR_CODES.invalidRequest,message)}function validateListPage(method,key,value,isItem){let items=isObject(value)?value[key]:void 0;if(!isObject(value)||!Array.isArray(items))throw invalid(`Invalid MCP ${method} result`);for(let item of items)if(!isObject(item)||!isItem(item))throw invalid(`Invalid entry in MCP ${method} result`);let nextCursor=value.nextCursor===null||value.nextCursor===""?void 0:value.nextCursor;if(nextCursor!==void 0&&typeof nextCursor!="string")throw invalid(`Invalid MCP ${method} cursor`);return{items,...nextCursor===void 0?{}:{nextCursor}}}var isTool=tool=>typeof tool.name=="string"&&isObject(tool.inputSchema),isResource=resource=>typeof resource.uri=="string"&&(resource.name===void 0||typeof resource.name=="string"),isResourceTemplate=template=>typeof template.uriTemplate=="string"&&(template.name===void 0||typeof template.name=="string");function toResource(item){return{...item,name:item.name??item.uri}}function toResourceTemplate(item){return{...item,name:item.name??item.uriTemplate}}function pageCursor(page){return page.nextCursor===void 0?{}:{nextCursor:page.nextCursor}}function validateReadResourceResult(value){if(!isObject(value)||!Array.isArray(value.contents))throw invalid("Invalid MCP resources/read result");for(let contents of value.contents)if(!isObject(contents)||typeof contents.uri!="string"||typeof contents.text!="string"&&typeof contents.blob!="string")throw invalid("Invalid contents in MCP resources/read result");return value}function validateCallToolResult(value){if(!isObject(value)||value.content!==void 0&&!Array.isArray(value.content))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call result");if(value.structuredContent!==void 0&&!isObject(value.structuredContent))throw new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Invalid MCP tools/call structured content");return value.content===void 0?{...value,content:[]}:value}var McpClient=class{options;state="idle";transport;nextRequestId=1;serverInfoValue;serverCapabilitiesValue;instructionsValue;protocolVersionValue;pending=new Map;progressRequests=new Map;incoming=new Map;requestHandlers=new Map;notificationListeners=new Map;errorListeners=new Set;closeListeners=new Set;disposers=[];constructor(options){this.options=Object.freeze({...options}),this.requestHandlers.set("ping",()=>({}));let roots=options.roots;roots&&this.requestHandlers.set("roots/list",async()=>({roots:[...typeof roots=="function"?await roots():roots]}))}get connectionState(){return this.state}get serverInfo(){return this.serverInfoValue}get serverCapabilities(){return this.serverCapabilitiesValue}get instructions(){return this.instructionsValue}get protocolVersion(){return this.protocolVersionValue}async connect(transport){if(this.state!=="idle")throw new Error(`Cannot connect MCP client in ${this.state} state`);this.state="connecting",this.transport=transport,this.disposers=[transport.onMessage(message=>this.handleMessage(message)),transport.onError(error=>this.emitError(error)),transport.onClose(()=>this.handleTransportClose())];try{await transport.start();let capabilities={...this.options.capabilities};this.options.roots&&capabilities.roots===void 0&&(capabilities.roots={});let result=validateInitializeResult(await this.requestInternal("initialize",{protocolVersion:this.options.protocolVersion??LATEST_PROTOCOL_VERSION,capabilities,clientInfo:{name:this.options.name,version:this.options.version,...this.options.title===void 0?{}:{title:this.options.title}}},{},!0));if(!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion))throw new Error(`MCP server selected unsupported protocol version ${result.protocolVersion}`);return this.protocolVersionValue=result.protocolVersion,this.serverInfoValue=result.serverInfo,this.serverCapabilitiesValue=result.capabilities,this.instructionsValue=result.instructions,transport.setProtocolVersion?.(result.protocolVersion),await this.notifyInternal("notifications/initialized",void 0,!0),this.state="connected",result}catch(error){throw await this.close().catch(()=>{}),error}}request(method,params,options={}){return this.requestInternal(method,params,options,!1)}notify(method,params){return this.notifyInternal(method,params,!1)}setRequestHandler(method,handler){return this.requestHandlers.set(method,handler),()=>{this.requestHandlers.get(method)===handler&&this.requestHandlers.delete(method)}}onNotification(method,listener){let listeners=this.notificationListeners.get(method)??new Set;return this.notificationListeners.set(method,listeners),listeners.add(listener),()=>{listeners.delete(listener),listeners.size===0&&this.notificationListeners.delete(method)}}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}async ping(options={}){await this.request("ping",void 0,options)}async listTools(options={}){return await this.listAll("tools/list","tools",isTool,options)}async listResources(options={}){return(await this.listAll("resources/list","resources",isResource,options)).map(toResource)}async listResourcesPage(cursor,options={}){let page=await this.listPage("resources/list","resources",isResource,cursor,options);return{resources:page.items.map(toResource),...pageCursor(page)}}async listResourceTemplates(options={}){return(await this.listAll("resources/templates/list","resourceTemplates",isResourceTemplate,options)).map(toResourceTemplate)}async listResourceTemplatesPage(cursor,options={}){let page=await this.listPage("resources/templates/list","resourceTemplates",isResourceTemplate,cursor,options);return{resourceTemplates:page.items.map(toResourceTemplate),...pageCursor(page)}}async readResource(uri,options={}){return validateReadResourceResult(await this.request("resources/read",{uri},options))}async listPage(method,key,isItem,cursor,options){return validateListPage(method,key,await this.request(method,cursor===void 0?void 0:{cursor},options),isItem)}async listAll(method,key,isItem,options){let items=[],cursors=new Set,cursor;for(let pageNumber=0;pageNumber<MAX_LIST_PAGES;pageNumber++){let page=await this.listPage(method,key,isItem,cursor,options);if(items.push(...page.items),page.nextCursor===void 0)return items;if(cursors.has(page.nextCursor))throw new Error(`MCP ${method} returned duplicate cursor: ${page.nextCursor}`);cursors.add(page.nextCursor),cursor=page.nextCursor}throw new Error(`MCP ${method} exceeded ${MAX_LIST_PAGES} pages`)}async callTool(name,args,options={}){return validateCallToolResult(await this.request("tools/call",{name,...args===void 0?{}:{arguments:args}},options))}async close(){let transport=this.transport;this.transport=void 0,this.disposeTransportListeners(),this.markClosed(new McpConnectionClosedError),await transport?.close()}async requestInternal(method,params,options,allowConnecting){let transport=this.requireTransport(allowConnecting);if(options.signal?.aborted)throw new McpAbortError;let id=this.nextRequestId++,progressToken=options.onProgress?id:void 0,requestParams=progressToken===void 0?params:{...params,_meta:{...isObject(params?._meta)?params._meta:{},progressToken}},message={jsonrpc:"2.0",id,method,...requestParams===void 0?{}:{params:requestParams}};return new Promise((resolve,reject)=>{let entry={resolve,reject,timeoutMs:options.timeoutMs??this.options.requestTimeoutMs??DEFAULT_REQUEST_TIMEOUT_MS,timer:void 0,signal:options.signal,onAbort:()=>this.cancelPending(id,new McpAbortError,method!=="initialize",String(options.signal?.reason??"Aborted")),cancellable:method!=="initialize",onProgress:options.onProgress,progressToken};this.pending.set(id,entry),progressToken!==void 0&&this.progressRequests.set(progressToken,id),options.signal?.addEventListener("abort",entry.onAbort,{once:!0}),this.armTimeout(id,entry),transport.send(message).catch(error=>this.cancelPending(id,error,!1))})}async notifyInternal(method,params,allowConnecting){await this.requireTransport(allowConnecting).send({jsonrpc:"2.0",method,...params===void 0?{}:{params}})}requireTransport(allowConnecting){if(this.transport&&(this.state==="connected"||allowConnecting&&this.state==="connecting"))return this.transport;throw new McpConnectionClosedError(`MCP client is ${this.state}`)}handleMessage(message){if(isJsonRpcResponse(message)){this.handleResponse(message);return}if(isJsonRpcRequest(message)){this.handleRequest(message);return}if(isJsonRpcNotification(message)){this.handleNotification(message.method,message.params);return}this.emitError(new McpError(JSON_RPC_ERROR_CODES.invalidRequest,"Received invalid JSON-RPC message"))}handleResponse(message){let entry=this.pending.get(message.id);if(!entry){this.emitError(new Error(`Received response for unknown MCP request ${String(message.id)}`));return}this.removePending(message.id,entry),"error"in message?entry.reject(new McpError(message.error.code,message.error.message,message.error.data)):entry.resolve(message.result)}async handleRequest(message){let transport=this.transport;if(!transport)return;let handler=this.requestHandlers.get(message.method);if(!handler){await transport.send({jsonrpc:"2.0",id:message.id,error:{code:JSON_RPC_ERROR_CODES.methodNotFound,message:`Method not found: ${message.method}`}}).catch(error=>this.emitError(error));return}let controller=new AbortController;this.incoming.set(message.id,controller);try{let result=await handler(message.params,{signal:controller.signal});await transport.send({jsonrpc:"2.0",id:message.id,result:result??{}})}catch(error){let responseError=error instanceof McpError?{code:error.code,message:error.message,data:error.data}:{code:JSON_RPC_ERROR_CODES.internalError,message:toError(error).message};await transport.send({jsonrpc:"2.0",id:message.id,error:responseError}).catch(sendError=>this.emitError(sendError))}finally{this.incoming.delete(message.id)}}handleNotification(method,params){method==="notifications/progress"?this.handleProgress(params):method==="notifications/cancelled"&&this.handleCancelled(params);for(let listener of this.notificationListeners.get(method)??[])try{listener(params)}catch(error){this.emitError(error)}}handleProgress(params){if(!isObject(params)||!isJsonRpcId(params.progressToken)||typeof params.progress!="number")return;let requestId=this.progressRequests.get(params.progressToken),entry=requestId===void 0?void 0:this.pending.get(requestId);if(!(requestId===void 0||!entry)){this.armTimeout(requestId,entry);try{entry.onProgress?.(params)}catch(error){this.emitError(error)}}}handleCancelled(params){isObject(params)&&isJsonRpcId(params.requestId)&&this.incoming.get(params.requestId)?.abort(params.reason)}armTimeout(id,entry){entry.timer&&clearTimeout(entry.timer),!(!Number.isFinite(entry.timeoutMs)||entry.timeoutMs<=0)&&(entry.timer=setTimeout(()=>{this.cancelPending(id,new McpTimeoutError(entry.timeoutMs),entry.cancellable,"Request timed out")},entry.timeoutMs))}cancelPending(id,error,notifyServer,reason){let entry=this.pending.get(id);entry&&(this.removePending(id,entry),entry.reject(error),notifyServer&&this.transport&&this.transport.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:id,...reason?{reason}:{}}}).catch(sendError=>this.emitError(sendError)))}removePending(id,entry){this.pending.delete(id),entry.timer&&clearTimeout(entry.timer),entry.progressToken!==void 0&&this.progressRequests.delete(entry.progressToken),entry.signal?.removeEventListener("abort",entry.onAbort)}rejectPending(error){for(let[id,entry]of this.pending)this.removePending(id,entry),entry.reject(error)}handleTransportClose(){this.markClosed(new McpConnectionClosedError)}markClosed(error){let wasClosed=this.state==="closed";this.state="closed",this.rejectPending(error);for(let controller of this.incoming.values())controller.abort(error);if(this.incoming.clear(),!wasClosed)for(let listener of[...this.closeListeners])try{listener()}catch(listenerError){this.emitError(listenerError)}}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}disposeTransportListeners(){for(let dispose of this.disposers.splice(0))dispose()}};var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn}from"node:child_process";import process2 from"node:process";var DEFAULT_MAX_MESSAGE_BYTES=16*1024*1024,TransportEvents=class{messageListeners=new Set;errorListeners=new Set;closeListeners=new Set;closeEmitted=!1;onMessage(listener){return this.messageListeners.add(listener),()=>this.messageListeners.delete(listener)}onError(listener){return this.errorListeners.add(listener),()=>this.errorListeners.delete(listener)}onClose(listener){return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener)}emitMessage(message){for(let listener of this.messageListeners)listener(message)}emitError(error){let normalized=toError(error);for(let listener of this.errorListeners)listener(normalized)}emitClose(){if(!this.closeEmitted){this.closeEmitted=!0;for(let listener of this.closeListeners)listener()}}};var DEFAULT_MAX_STDERR_BYTES=64*1024,DEFAULT_CLOSE_TIMEOUT_MS=2e3,STDIN_CLOSE_GRACE_MS=500,USE_PROCESS_GROUPS=process2.platform!=="win32",liveProcessGroups=new Set,exitHookInstalled=!1;function killProcessTree(child,signal){let pid=child.pid;if(process2.platform==="win32"&&pid!==void 0){if(child.exitCode!==null)return;spawn("taskkill",["/pid",String(pid),"/T","/F"],{stdio:"ignore",windowsHide:!0}).on("error",()=>{});return}if(USE_PROCESS_GROUPS&&pid!==void 0)try{process2.kill(-pid,signal);return}catch{}try{child.kill(signal)}catch{}}function installExitHook(){exitHookInstalled||(exitHookInstalled=!0,process2.once("exit",()=>{for(let pid of liveProcessGroups)try{process2.kill(-pid,"SIGTERM")}catch{}}))}var StdioTransport=class extends TransportEvents{options;child;stdoutBuffer=Buffer.alloc(0);stderrBuffer=Buffer.alloc(0);started=!1;closed=!1;constructor(options){super(),this.options=Object.freeze({...options,args:options.args?[...options.args]:void 0})}get pid(){return this.child?.pid}get stderr(){return this.stderrBuffer.toString("utf8")}async start(){if(this.started)throw new Error("MCP stdio transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0;let env=this.options.inheritEnv===!1?{...this.options.env}:{...process2.env,...this.options.env},child=(0,import_cross_spawn.default)(this.options.command,this.options.args??[],{cwd:this.options.cwd,env,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:USE_PROCESS_GROUPS});this.child=child;let pid=child.pid;USE_PROCESS_GROUPS&&pid!==void 0&&(installExitHook(),liveProcessGroups.add(pid),child.once("exit",()=>liveProcessGroups.delete(pid))),child.stdout?.on("data",chunk=>this.handleStdout(chunk)),child.stdout?.on("error",error=>this.emitError(error)),child.stdin?.on("error",error=>{this.closed||this.emitError(error)}),child.stderr?.on("data",chunk=>this.handleStderr(chunk)),child.stderr?.on("error",error=>this.emitError(error)),child.on("close",()=>{this.child=void 0,this.stdoutBuffer.toString("utf8").trim()&&this.emitError(new Error("MCP stdio server closed with an incomplete JSON-RPC message")),this.stdoutBuffer=Buffer.alloc(0),this.emitClose()}),await new Promise((resolve,reject)=>{let onSpawn=()=>{child.off("error",onError),resolve()},onError=error=>{child.off("spawn",onSpawn),reject(error)};child.once("spawn",onSpawn),child.once("error",onError)}),child.on("error",error=>{this.closed||this.emitError(error)})}async send(message){let stdin=this.child?.stdin;if(!this.started||this.closed||!stdin?.writable)throw new McpConnectionClosedError;let payload=`${JSON.stringify(message)}
4
4
  `;await new Promise((resolve,reject)=>{stdin.write(payload,error=>error?reject(error):resolve())})}async close(){if(this.closed)return;this.closed=!0;let child=this.child;if(!child){this.emitClose();return}if(child.exitCode!==null||child.signalCode!==null){child.stdin?.end();return}let closeTimeoutMs=this.options.closeTimeoutMs??DEFAULT_CLOSE_TIMEOUT_MS;await new Promise(resolve=>{let timers=[];child.once("close",()=>{for(let timer of timers)clearTimeout(timer);killProcessTree(child,"SIGTERM"),resolve()});let grace=Math.min(STDIN_CLOSE_GRACE_MS,closeTimeoutMs);timers.push(setTimeout(()=>killProcessTree(child,"SIGTERM"),grace)),timers.push(setTimeout(()=>killProcessTree(child,"SIGKILL"),grace+closeTimeoutMs)),child.stdin?.end()})}handleStdout(chunk){this.stdoutBuffer=Buffer.concat([this.stdoutBuffer,Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk)]);let maxMessageBytes=this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES;for(;;){let newline=this.stdoutBuffer.indexOf(10);if(newline<0){this.stdoutBuffer.length>maxMessageBytes&&(this.stdoutBuffer=Buffer.alloc(0),this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`)));return}let line=this.stdoutBuffer.subarray(0,newline);if(this.stdoutBuffer=this.stdoutBuffer.subarray(newline+1),line.length>maxMessageBytes){this.emitError(new Error(`MCP stdio message exceeds ${maxMessageBytes} bytes`));continue}let text=line.toString("utf8").replace(/\r$/,"");if(text.trim())try{this.emitMessage(parseJsonRpcMessage(JSON.parse(text)))}catch(error){this.emitError(error)}}}handleStderr(chunk){let buffer=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk),maxStderrBytes=this.options.maxStderrBytes??DEFAULT_MAX_STDERR_BYTES;this.stderrBuffer=Buffer.concat([this.stderrBuffer,buffer]),this.stderrBuffer.length>maxStderrBytes&&(this.stderrBuffer=this.stderrBuffer.subarray(-maxStderrBytes)),this.options.onStderr?.(buffer.toString("utf8"))}};var MAX_ERROR_BODY_BYTES=8*1024,ERROR_MESSAGE_BODY_CHARS=500,DEFAULT_RECONNECT_INITIAL_DELAY_MS=1e3,DEFAULT_RECONNECT_MAX_DELAY_MS=3e4,DEFAULT_RECONNECT_MAX_RETRIES=5;async function consumeSseStream(stream,options){let reader=stream.getReader(),decoder=new TextDecoder,buffered="",eventName,eventId,dataLines=[],dataBytes=0,maxEventBytes=options.maxEventBytes??DEFAULT_MAX_MESSAGE_BYTES,dispatch=()=>{if(dataLines.length===0){eventName=void 0,eventId=void 0;return}let data=dataLines.join(`
5
5
  `);options.onEvent({...eventName?{event:eventName}:{},data,...eventId?{id:eventId}:{}}),eventName=void 0,eventId=void 0,dataLines=[],dataBytes=0},processLine=rawLine=>{let line=rawLine.endsWith("\r")?rawLine.slice(0,-1):rawLine;if(line===""){dispatch();return}if(line.startsWith(":"))return;let colon=line.indexOf(":"),field=colon<0?line:line.slice(0,colon),value=colon<0?"":line.slice(colon+1);if(value.startsWith(" ")&&(value=value.slice(1)),field==="data"){if(dataBytes+=Buffer.byteLength(value)+(dataLines.length>0?1:0),dataBytes>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`);dataLines.push(value)}else field==="event"?eventName=value:field==="id"&&!value.includes("\0")?(eventId=value,options.onId?.(value)):field==="retry"&&/^\d+$/.test(value)&&options.onRetry?.(Number(value))};try{for(;;){let{done,value}=await reader.read();if(done)break;buffered+=decoder.decode(value,{stream:!0});let newline=buffered.indexOf(`
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{Text,getBinDir,getCapabilities,getImageDimensions,hyperlink,imageFallback,resolvePath,truncateToWidth}from"./chunk-XDAWU2J5.js";import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&existsSync(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
2
+ import{Text,getBinDir,getCapabilities,getImageDimensions,hyperlink,imageFallback,resolvePath,truncateToWidth}from"./chunk-IDUCLYG3.js";import{existsSync}from"node:fs";import{delimiter,join}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=path.replace(/\//g,"\\").toLowerCase();return/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&existsSync(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(existsSync(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(existsSync(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
3
3
  1. Install Git for Windows: https://git-scm.com/download/win
4
4
  2. Add your bash to PATH (Cygwin, MSYS2, etc.)
5
5
  3. Set shellPath in settings.json
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{backgroundAnsi,foregroundAnsi,isAppleTerminalSession,rgbColor,theme}from"./chunk-XDAWU2J5.js";var ARMIN_WIDTH=31,ARMIN_HEIGHT=36,WIDTH=ARMIN_WIDTH,HEIGHT=ARMIN_HEIGHT,BITS=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],BYTES_PER_ROW=Math.ceil(WIDTH/8),DISPLAY_HEIGHT=Math.ceil(HEIGHT/2),EFFECTS=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function isArminPixel(x,y){if(y>=HEIGHT)return!1;let byteIndex=y*BYTES_PER_ROW+Math.floor(x/8),bitIndex=x%8;return(BITS[byteIndex]>>bitIndex&1)===0}function getChar(x,row){let upper=isArminPixel(x,row*2),lower=isArminPixel(x,row*2+1);return upper&&lower?"\u2588":upper?"\u2580":lower?"\u2584":" "}function buildFinalGrid(){let grid=[];for(let row=0;row<DISPLAY_HEIGHT;row++){let line=[];for(let x=0;x<WIDTH;x++)line.push(getChar(x,row));grid.push(line)}return grid}var ArminComponent=class{ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(ui){this.ui=ui,this.effect=EFFECTS[Math.floor(Math.random()*EFFECTS.length)],this.finalGrid=buildFinalGrid(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(width){if(width===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let padding=1,availableWidth=width-padding;this.cachedLines=this.currentGrid.map(row=>{let clipped=row.slice(0,availableWidth).join(""),padRight=Math.max(0,width-padding-clipped.length);return` ${theme.fg("accent",clipped)}${" ".repeat(padRight)}`});let message="ARMIN SAYS HI",msgPadRight=Math.max(0,width-padding-message.length);return this.cachedLines.push(` ${theme.fg("accent",message)}${" ".repeat(msgPadRight)}`),this.cachedWidth=width,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:DISPLAY_HEIGHT},()=>Array(WIDTH).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:WIDTH},()=>({y:-Math.floor(Math.random()*DISPLAY_HEIGHT*2),settled:0}))};break;case"fade":{let positions=[];for(let row=0;row<DISPLAY_HEIGHT;row++)for(let x=0;x<WIDTH;x++)positions.push([row,x]);for(let i=positions.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[positions[i],positions[j]]=[positions[j],positions[i]]}this.effectState={positions,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:DISPLAY_HEIGHT},()=>Array.from({length:WIDTH},()=>{let chars=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return chars[Math.floor(Math.random()*chars.length)]}));let dissolvePositions=[];for(let row=0;row<DISPLAY_HEIGHT;row++)for(let x=0;x<WIDTH;x++)dissolvePositions.push([row,x]);for(let i=dissolvePositions.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[dissolvePositions[i],dissolvePositions[j]]=[dissolvePositions[j],dissolvePositions[i]]}this.effectState={positions:dissolvePositions,idx:0};break}}}startAnimation(){let fps=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let done=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),done&&this.stopAnimation()},1e3/fps)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let state=this.effectState,pixelsPerFrame=3;for(let i=0;i<pixelsPerFrame;i++){let row=Math.floor(state.pos/WIDTH),x=state.pos%WIDTH;if(row>=DISPLAY_HEIGHT)return!0;this.currentGrid[row][x]=this.finalGrid[row][x],state.pos++}return!1}tickScanline(){let state=this.effectState;if(state.row>=DISPLAY_HEIGHT)return!0;for(let x=0;x<WIDTH;x++)this.currentGrid[state.row][x]=this.finalGrid[state.row][x];return state.row++,!1}tickRain(){let state=this.effectState,allSettled=!0;this.currentGrid=this.createEmptyGrid();for(let x=0;x<WIDTH;x++){let drop=state.drops[x];for(let row=DISPLAY_HEIGHT-1;row>=DISPLAY_HEIGHT-drop.settled;row--)row>=0&&(this.currentGrid[row][x]=this.finalGrid[row][x]);if(drop.settled>=DISPLAY_HEIGHT)continue;allSettled=!1;let targetRow=-1;for(let row=DISPLAY_HEIGHT-1-drop.settled;row>=0;row--)if(this.finalGrid[row][x]!==" "){targetRow=row;break}drop.y++,drop.y>=0&&drop.y<DISPLAY_HEIGHT&&(targetRow>=0&&drop.y>=targetRow?(drop.settled=DISPLAY_HEIGHT-targetRow,drop.y=-Math.floor(Math.random()*5)-1):this.currentGrid[drop.y][x]="\u2593")}return allSettled}tickFade(){let state=this.effectState,pixelsPerFrame=15;for(let i=0;i<pixelsPerFrame;i++){if(state.idx>=state.positions.length)return!0;let[row,x]=state.positions[state.idx];this.currentGrid[row][x]=this.finalGrid[row][x],state.idx++}return!1}tickCrt(){let state=this.effectState,midRow=Math.floor(DISPLAY_HEIGHT/2);this.currentGrid=this.createEmptyGrid();let top=midRow-state.expansion,bottom=midRow+state.expansion;for(let row=Math.max(0,top);row<=Math.min(DISPLAY_HEIGHT-1,bottom);row++)for(let x=0;x<WIDTH;x++)this.currentGrid[row][x]=this.finalGrid[row][x];return state.expansion++,state.expansion>DISPLAY_HEIGHT}tickGlitch(){let state=this.effectState;return state.phase<state.glitchFrames?(this.currentGrid=this.finalGrid.map(row=>{let offset=Math.floor(Math.random()*7)-3,glitchRow=[...row];if(Math.random()<.3)return glitchRow.slice(offset).concat(glitchRow.slice(0,offset)).slice(0,WIDTH);if(Math.random()<.2){let swapRow=Math.floor(Math.random()*DISPLAY_HEIGHT);return[...this.finalGrid[swapRow]]}return glitchRow}),state.phase++,!1):(this.currentGrid=this.finalGrid.map(row=>[...row]),!0)}tickDissolve(){let state=this.effectState,pixelsPerFrame=20;for(let i=0;i<pixelsPerFrame;i++){if(state.idx>=state.positions.length)return!0;let[row,x]=state.positions[state.idx];this.currentGrid[row][x]=this.finalGrid[row][x],state.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};var ARM_TOP=rgbColor(65,229,218),ARM_LOW=rgbColor(25,173,177),SLASH=rgbColor(125,249,239),WORDMARK_ACCENT=rgbColor(60,241,230),RESET="\x1B[0m",RELAY_LOGO_PIXELS=[".t..s.t.","t...s..t","l..s...l",".l.s..l."],RELAY_LOGO_COLORS={t:ARM_TOP,l:ARM_LOW,s:SLASH},RELAY_LOGO_WIDTH=RELAY_LOGO_PIXELS[0].length;function relayLogoLines(){let mode=theme.getColorMode(),line=row=>{let text="";for(let column=0;column<RELAY_LOGO_WIDTH;column++){let top=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row][column]],bottom=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row+1][column]];top&&bottom?text+=top===bottom?`${foregroundAnsi(top,mode)}\u2588${RESET}`:`${foregroundAnsi(top,mode)}${backgroundAnsi(bottom,mode)}\u2580${RESET}`:top?text+=`${foregroundAnsi(top,mode)}\u2580${RESET}`:bottom?text+=`${foregroundAnsi(bottom,mode)}\u2584${RESET}`:text+=" "}return text};return[line(0),line(2)]}function supportsRelayLogo(){return!isAppleTerminalSession()}function relayWordmark(){let mode=theme.getColorMode();return`${theme.bold("re")}${foregroundAnsi(WORDMARK_ACCENT,mode)}\x1B[1mlay${RESET}`}export{ARMIN_WIDTH,ARMIN_HEIGHT,isArminPixel,ArminComponent,RELAY_LOGO_PIXELS,RELAY_LOGO_COLORS,RELAY_LOGO_WIDTH,relayLogoLines,supportsRelayLogo,relayWordmark};
2
+ import{backgroundAnsi,foregroundAnsi,isAppleTerminalSession,rgbColor,theme}from"./chunk-IDUCLYG3.js";var ARMIN_WIDTH=31,ARMIN_HEIGHT=36,WIDTH=ARMIN_WIDTH,HEIGHT=ARMIN_HEIGHT,BITS=[255,255,255,127,255,240,255,127,255,237,255,127,255,219,255,127,255,183,255,127,255,119,254,127,63,248,254,127,223,255,254,127,223,63,252,127,159,195,251,127,111,252,244,127,247,15,247,127,247,255,247,127,247,255,227,127,247,7,232,127,239,248,103,112,15,255,187,111,241,0,208,91,253,63,236,83,193,255,239,87,159,253,238,95,159,252,174,95,31,120,172,95,63,0,80,108,127,0,220,119,255,192,63,120,255,1,248,127,255,3,156,120,255,7,140,124,255,15,206,120,255,255,207,127,255,255,207,120,255,255,223,120,255,255,223,125,255,255,63,126,255,255,255,127],BYTES_PER_ROW=Math.ceil(WIDTH/8),DISPLAY_HEIGHT=Math.ceil(HEIGHT/2),EFFECTS=["typewriter","scanline","rain","fade","crt","glitch","dissolve"];function isArminPixel(x,y){if(y>=HEIGHT)return!1;let byteIndex=y*BYTES_PER_ROW+Math.floor(x/8),bitIndex=x%8;return(BITS[byteIndex]>>bitIndex&1)===0}function getChar(x,row){let upper=isArminPixel(x,row*2),lower=isArminPixel(x,row*2+1);return upper&&lower?"\u2588":upper?"\u2580":lower?"\u2584":" "}function buildFinalGrid(){let grid=[];for(let row=0;row<DISPLAY_HEIGHT;row++){let line=[];for(let x=0;x<WIDTH;x++)line.push(getChar(x,row));grid.push(line)}return grid}var ArminComponent=class{ui;interval=null;effect;finalGrid;currentGrid;effectState={};cachedLines=[];cachedWidth=0;gridVersion=0;cachedVersion=-1;constructor(ui){this.ui=ui,this.effect=EFFECTS[Math.floor(Math.random()*EFFECTS.length)],this.finalGrid=buildFinalGrid(),this.currentGrid=this.createEmptyGrid(),this.initEffect(),this.startAnimation()}invalidate(){this.cachedWidth=0}render(width){if(width===this.cachedWidth&&this.cachedVersion===this.gridVersion)return this.cachedLines;let padding=1,availableWidth=width-padding;this.cachedLines=this.currentGrid.map(row=>{let clipped=row.slice(0,availableWidth).join(""),padRight=Math.max(0,width-padding-clipped.length);return` ${theme.fg("accent",clipped)}${" ".repeat(padRight)}`});let message="ARMIN SAYS HI",msgPadRight=Math.max(0,width-padding-message.length);return this.cachedLines.push(` ${theme.fg("accent",message)}${" ".repeat(msgPadRight)}`),this.cachedWidth=width,this.cachedVersion=this.gridVersion,this.cachedLines}createEmptyGrid(){return Array.from({length:DISPLAY_HEIGHT},()=>Array(WIDTH).fill(" "))}initEffect(){switch(this.effect){case"typewriter":this.effectState={pos:0};break;case"scanline":this.effectState={row:0};break;case"rain":this.effectState={drops:Array.from({length:WIDTH},()=>({y:-Math.floor(Math.random()*DISPLAY_HEIGHT*2),settled:0}))};break;case"fade":{let positions=[];for(let row=0;row<DISPLAY_HEIGHT;row++)for(let x=0;x<WIDTH;x++)positions.push([row,x]);for(let i=positions.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[positions[i],positions[j]]=[positions[j],positions[i]]}this.effectState={positions,idx:0};break}case"crt":this.effectState={expansion:0};break;case"glitch":this.effectState={phase:0,glitchFrames:8};break;case"dissolve":{this.currentGrid=Array.from({length:DISPLAY_HEIGHT},()=>Array.from({length:WIDTH},()=>{let chars=[" ","\u2591","\u2592","\u2593","\u2588","\u2580","\u2584"];return chars[Math.floor(Math.random()*chars.length)]}));let dissolvePositions=[];for(let row=0;row<DISPLAY_HEIGHT;row++)for(let x=0;x<WIDTH;x++)dissolvePositions.push([row,x]);for(let i=dissolvePositions.length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[dissolvePositions[i],dissolvePositions[j]]=[dissolvePositions[j],dissolvePositions[i]]}this.effectState={positions:dissolvePositions,idx:0};break}}}startAnimation(){let fps=this.effect==="glitch"?60:30;this.interval=setInterval(()=>{let done=this.tickEffect();this.updateDisplay(),this.ui.requestRender(),done&&this.stopAnimation()},1e3/fps)}stopAnimation(){this.interval&&(clearInterval(this.interval),this.interval=null)}tickEffect(){switch(this.effect){case"typewriter":return this.tickTypewriter();case"scanline":return this.tickScanline();case"rain":return this.tickRain();case"fade":return this.tickFade();case"crt":return this.tickCrt();case"glitch":return this.tickGlitch();case"dissolve":return this.tickDissolve();default:return!0}}tickTypewriter(){let state=this.effectState,pixelsPerFrame=3;for(let i=0;i<pixelsPerFrame;i++){let row=Math.floor(state.pos/WIDTH),x=state.pos%WIDTH;if(row>=DISPLAY_HEIGHT)return!0;this.currentGrid[row][x]=this.finalGrid[row][x],state.pos++}return!1}tickScanline(){let state=this.effectState;if(state.row>=DISPLAY_HEIGHT)return!0;for(let x=0;x<WIDTH;x++)this.currentGrid[state.row][x]=this.finalGrid[state.row][x];return state.row++,!1}tickRain(){let state=this.effectState,allSettled=!0;this.currentGrid=this.createEmptyGrid();for(let x=0;x<WIDTH;x++){let drop=state.drops[x];for(let row=DISPLAY_HEIGHT-1;row>=DISPLAY_HEIGHT-drop.settled;row--)row>=0&&(this.currentGrid[row][x]=this.finalGrid[row][x]);if(drop.settled>=DISPLAY_HEIGHT)continue;allSettled=!1;let targetRow=-1;for(let row=DISPLAY_HEIGHT-1-drop.settled;row>=0;row--)if(this.finalGrid[row][x]!==" "){targetRow=row;break}drop.y++,drop.y>=0&&drop.y<DISPLAY_HEIGHT&&(targetRow>=0&&drop.y>=targetRow?(drop.settled=DISPLAY_HEIGHT-targetRow,drop.y=-Math.floor(Math.random()*5)-1):this.currentGrid[drop.y][x]="\u2593")}return allSettled}tickFade(){let state=this.effectState,pixelsPerFrame=15;for(let i=0;i<pixelsPerFrame;i++){if(state.idx>=state.positions.length)return!0;let[row,x]=state.positions[state.idx];this.currentGrid[row][x]=this.finalGrid[row][x],state.idx++}return!1}tickCrt(){let state=this.effectState,midRow=Math.floor(DISPLAY_HEIGHT/2);this.currentGrid=this.createEmptyGrid();let top=midRow-state.expansion,bottom=midRow+state.expansion;for(let row=Math.max(0,top);row<=Math.min(DISPLAY_HEIGHT-1,bottom);row++)for(let x=0;x<WIDTH;x++)this.currentGrid[row][x]=this.finalGrid[row][x];return state.expansion++,state.expansion>DISPLAY_HEIGHT}tickGlitch(){let state=this.effectState;return state.phase<state.glitchFrames?(this.currentGrid=this.finalGrid.map(row=>{let offset=Math.floor(Math.random()*7)-3,glitchRow=[...row];if(Math.random()<.3)return glitchRow.slice(offset).concat(glitchRow.slice(0,offset)).slice(0,WIDTH);if(Math.random()<.2){let swapRow=Math.floor(Math.random()*DISPLAY_HEIGHT);return[...this.finalGrid[swapRow]]}return glitchRow}),state.phase++,!1):(this.currentGrid=this.finalGrid.map(row=>[...row]),!0)}tickDissolve(){let state=this.effectState,pixelsPerFrame=20;for(let i=0;i<pixelsPerFrame;i++){if(state.idx>=state.positions.length)return!0;let[row,x]=state.positions[state.idx];this.currentGrid[row][x]=this.finalGrid[row][x],state.idx++}return!1}updateDisplay(){this.gridVersion++}dispose(){this.stopAnimation()}};var ARM_TOP=rgbColor(65,229,218),ARM_LOW=rgbColor(25,173,177),SLASH=rgbColor(125,249,239),WORDMARK_ACCENT=rgbColor(60,241,230),RESET="\x1B[0m",RELAY_LOGO_PIXELS=[".t..s.t.","t...s..t","l..s...l",".l.s..l."],RELAY_LOGO_COLORS={t:ARM_TOP,l:ARM_LOW,s:SLASH},RELAY_LOGO_WIDTH=RELAY_LOGO_PIXELS[0].length;function relayLogoLines(){let mode=theme.getColorMode(),line=row=>{let text="";for(let column=0;column<RELAY_LOGO_WIDTH;column++){let top=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row][column]],bottom=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row+1][column]];top&&bottom?text+=top===bottom?`${foregroundAnsi(top,mode)}\u2588${RESET}`:`${foregroundAnsi(top,mode)}${backgroundAnsi(bottom,mode)}\u2580${RESET}`:top?text+=`${foregroundAnsi(top,mode)}\u2580${RESET}`:bottom?text+=`${foregroundAnsi(bottom,mode)}\u2584${RESET}`:text+=" "}return text};return[line(0),line(2)]}function supportsRelayLogo(){return!isAppleTerminalSession()}function relayWordmark(){let mode=theme.getColorMode();return`${theme.bold("re")}${foregroundAnsi(WORDMARK_ACCENT,mode)}\x1B[1mlay${RESET}`}export{ARMIN_WIDTH,ARMIN_HEIGHT,isArminPixel,ArminComponent,RELAY_LOGO_PIXELS,RELAY_LOGO_COLORS,RELAY_LOGO_WIDTH,relayLogoLines,supportsRelayLogo,relayWordmark};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-3QND5D7W.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-WMTXXI7H.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-3XNI2SB6.js";import"./chunk-MP5FU7MG.js";import{APP_NAME,CONFIG_DIR_NAME,source_default}from"./chunk-XDAWU2J5.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-7ZBTLURV.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-FUPU6X73.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-TZ2ZVU7E.js";import"./chunk-UVFWV6YH.js";import{APP_NAME,CONFIG_DIR_NAME,source_default}from"./chunk-IDUCLYG3.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
3
3
  ${APP_NAME} mcp add <server> [options] -- <command> [args...]
4
4
  ${APP_NAME} mcp add <server> [options] --url <url>
5
5
  ${APP_NAME} mcp remove <server> [-l]
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ARMIN_HEIGHT,ARMIN_WIDTH,RELAY_LOGO_COLORS,RELAY_LOGO_PIXELS,RELAY_LOGO_WIDTH,isArminPixel}from"./chunk-PTRF7IZB.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-XDAWU2J5.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}function relayLogoPixel(column,row){let color=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row][column]];return color&&[color.r,color.g,color.b]}function relayLogoModel(origin){return createModel(RELAY_LOGO_WIDTH,RELAY_LOGO_PIXELS.length,relayLogoPixel,{cameraDistance:16,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):relayLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
2
+ import{ARMIN_HEIGHT,ARMIN_WIDTH,RELAY_LOGO_COLORS,RELAY_LOGO_PIXELS,RELAY_LOGO_WIDTH,isArminPixel}from"./chunk-WU7MEKPF.js";import{backgroundAnsi,colorToRgb,foregroundAnsi,formatKeyText,getKeybindings,indexedColor,rgbColor,theme,visibleWidth}from"./chunk-IDUCLYG3.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";var DEPTH=.7,FLY_START=.1,FLY_DURATION=1.3,START_SCALE=.1;function createModel(columns,rows,pixel,options){let blocks=[];for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){let color=pixel(column,row);color&&blocks.push({home:[column,row,0],color})}return{columns,rows,blocks,cameraDistance:options.cameraDistance,radius:Math.hypot(columns/2,rows/2,1+DEPTH/2),widthShare:options.widthShare,puzzleMoves:random=>options.puzzleMoves(random,blocks.length),origin:options.origin}}function relayLogoPixel(column,row){let color=RELAY_LOGO_COLORS[RELAY_LOGO_PIXELS[row][column]];return color&&[color.r,color.g,color.b]}function relayLogoModel(origin){return createModel(RELAY_LOGO_WIDTH,RELAY_LOGO_PIXELS.length,relayLogoPixel,{cameraDistance:16,widthShare:.35,puzzleMoves:random=>random<.4?2:1,origin})}function arminModel(color){return createModel(ARMIN_WIDTH,ARMIN_HEIGHT,(column,row)=>isArminPixel(column,row)?color:void 0,{cameraDistance:80,widthShare:.45,puzzleMoves:(random,blockCount)=>Math.round(blockCount*(.03+random*.04)),origin:void 0})}var PUZZLE_START=FLY_START+FLY_DURATION+3,PUZZLE_STEP=.3,PUZZLE_STEPS=12,PUZZLE_RETURN=1,PUZZLE_HOLD=.6,PUZZLE_CYCLE=PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD,PUZZLE_MOVES=[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]];function shuffleSteps(model,cycle){let{columns,rows}=model,positions=model.blocks.map(block=>block.home),steps=[positions],lastMoved=new Set,random=cycle*7919+1,next=()=>hash(random++),key=([x,y,z])=>((z+1)*rows+y)*columns+x;for(let step=0;step<PUZZLE_STEPS;step++){let occupied=new Set(positions.map(key)),nextPositions=[...positions],moved=new Set,moveCount=model.puzzleMoves(next());for(let move=0;move<moveCount;move++){let candidates=[];for(let block=0;block<positions.length;block++){if(moved.has(block))continue;let[x,y,z]=positions[block];for(let[dx,dy,dz]of PUZZLE_MOVES){let target=[x+dx,y+dy,z+dz];target[0]<0||target[0]>=columns||target[1]<0||target[1]>=rows||target[2]<-1||target[2]>1||occupied.has(key(target))||candidates.push({block,target})}}let fresh=candidates.filter(candidate=>!lastMoved.has(candidate.block)),pool=fresh.length>0?fresh:candidates,choice=pool[Math.floor(next()*pool.length)];if(!choice)break;occupied.add(key(choice.target)),nextPositions[choice.block]=choice.target,moved.add(choice.block)}lastMoved.clear();for(let block of moved)lastMoved.add(block);positions=nextPositions,steps.push(positions)}return steps}var FRAME_MS=1e3/30,DUST_DURATION=.35,WAVE_SPREAD=.55,WAVE_JITTER=.12,DISSOLVE_END=FLY_START+WAVE_SPREAD+WAVE_JITTER+DUST_DURATION,BACKGROUND_FADE=.5,EXIT_DURATION=1.1,STARS_START=2.5,STARS_FADE=2,STAR_DENSITY=.018,STAR_TINTS=[[255,255,255],[170,195,255],[255,225,170],[255,190,205]],LOGO_COLOR_STEP=5,LIGHT_HALO_STRENGTH=.3,HALO_RADIUS_X=6,HALO_RADIUS_Y=3,HALO_LEVELS=32,STAR_ALPHA_LEVELS=8,STAR_FLICKER_LEVELS=3,HINT_FADE=.5,DOT_BITS=[1,8,2,16,4,32,64,128],BRAILLE=Array.from({length:256},(_,bits)=>String.fromCharCode(10240+bits)),LIGHT=normalize([-.45,-.6,.75]),HALF_VECTOR=normalize([LIGHT[0],LIGHT[1],LIGHT[2]+1]);function normalize(v){let length=Math.hypot(v[0],v[1],v[2]);return[v[0]/length,v[1]/length,v[2]/length]}function clamp01(value){return value<0?0:value>1?1:value}function smooth(value){let t=clamp01(value);return t*t*t*(t*(t*6-15)+10)}function easeOut(value){let t=1-clamp01(value);return 1-t*t*t}function mix(a,b,amount){return[a[0]+(b[0]-a[0])*amount,a[1]+(b[1]-a[1])*amount,a[2]+(b[2]-a[2])*amount]}function hash(value){let x=Math.imul(value^2654435769,2246822507);return x^=x>>>13,x=Math.imul(x,3266489909),x^=x>>>16,(x>>>0)/4294967296}function isLight([r,g,b]){return .2126*r+.7152*g+.0722*b>128}function toRgb(color){let{r,g,b}=colorToRgb(color);return[r,g,b]}function glyphInk(text,seed){return text.trim()===""?0:/^[.,:;'`\-_·]$/.test(text)?2:/^[\u2500-\u257f]$/.test(text)?3:4+Math.floor(seed*3)}var segmenter=new Intl.Segmenter;function parseScreen(lines,width,foreground,background){let palette=index=>toRgb(indexedColor(index));return lines.map(line=>{let cells=[],fg,bg,dim=!1,inverse=!1,applySgr=params=>{let codes=params===""?["0"]:params.split(";");for(let i2=0;i2<codes.length;i2++){let parts=codes[i2].split(":").map(part=>Number.parseInt(part,10)),code=parts[0]??0;if(code===38||code===48){let args;if(parts.length>1)args=parts.slice(1).filter(part=>!Number.isNaN(part));else{let kind=Number.parseInt(codes[i2+1]??"",10),count=kind===5?2:kind===2?4:1;args=codes.slice(i2+1,i2+1+count).map(part=>Number.parseInt(part,10)),i2+=count}let color;args[0]===5&&args[1]!==void 0?color=palette(args[1]):args[0]===2&&args.length>=4&&(color=[args[1],args[2],args[3]]),color&&(code===38?fg=color:bg=color)}else code===0?(fg=void 0,bg=void 0,dim=!1,inverse=!1):code===2?dim=!0:code===22?dim=!1:code===7?inverse=!0:code===27?inverse=!1:code>=30&&code<=37?fg=palette(code-30):code>=90&&code<=97?fg=palette(code-90+8):code===39?fg=void 0:code>=40&&code<=47?bg=palette(code-40):code>=100&&code<=107?bg=palette(code-100+8):code===49&&(bg=void 0)}},pushText=text=>{for(let{segment}of segmenter.segment(text)){let glyphWidth=visibleWidth(segment);if(glyphWidth===0||cells.length+glyphWidth>width)continue;let cellFg=fg??foreground,cellBg=bg;inverse&&(cellFg=bg??background,cellBg=fg??foreground),dim&&(cellFg=mix(cellFg,cellBg??background,.4));let cell={text:segment,width:glyphWidth,fg:cellFg,bg:cellBg,delay:0,ink:0,seed:0};cells.push(cell),glyphWidth===2&&cells.push({...cell,text:"",width:0})}},i=0;for(;i<line.length;){let sequenceStart=line.indexOf("\x1B",i);if(sequenceStart===-1){pushText(line.slice(i));break}sequenceStart>i&&pushText(line.slice(i,sequenceStart));let kind=line[sequenceStart+1];if(kind==="["){let end=sequenceStart+2;for(;end<line.length&&(line.charCodeAt(end)<64||line.charCodeAt(end)>126);)end++;line[end]==="m"&&applySgr(line.slice(sequenceStart+2,end)),i=end+1}else if(kind==="]"||kind==="_"||kind==="P"||kind==="^"){let bell=line.indexOf("\x07",sequenceStart+2),st=line.indexOf("\x1B\\",sequenceStart+2);if(bell===-1&&st===-1)break;i=bell!==-1&&(st===-1||bell<st)?bell+1:st+2}else i=sequenceStart+2}return cells})}function rotation(yaw,pitch,roll){let[sy,cy,sx,cx,sz,cz]=[Math.sin(yaw),Math.cos(yaw),Math.sin(pitch),Math.cos(pitch),Math.sin(roll),Math.cos(roll)],ry=[cy,0,sy,0,1,0,-sy,0,cy],rx=[1,0,0,0,cx,-sx,0,sx,cx],rz=[cz,-sz,0,sz,cz,0,0,0,1];return multiply(rz,multiply(rx,ry))}function multiply(a,b){let result=new Array(9);for(let row=0;row<3;row++)for(let column=0;column<3;column++)result[row*3+column]=a[row*3]*b[column]+a[row*3+1]*b[3+column]+a[row*3+2]*b[6+column];return result}var SPIN_RAMP=1.4,SPIN_SPEED=Math.PI*2/PUZZLE_CYCLE,SPIN_LINGER=.6,FIRST_FRONT_VIEW=PUZZLE_START+PUZZLE_STEP*PUZZLE_STEPS+PUZZLE_RETURN+PUZZLE_HOLD/2;function baseSpinPhase(time){let elapsed=time-FLY_START;if(elapsed<=0)return 0;let u=elapsed/SPIN_RAMP;return u<1?SPIN_SPEED*SPIN_RAMP*(u**6-3*u**5+2.5*u**4):SPIN_SPEED*(SPIN_RAMP*.5+elapsed-SPIN_RAMP)}var SPIN_ALIGNMENT=Math.PI*2-baseSpinPhase(FIRST_FRONT_VIEW)%(Math.PI*2);function spinPhase(time){return baseSpinPhase(time)+SPIN_ALIGNMENT*smooth((time-FLY_START)/FLY_DURATION)}function spinAngle(time){let phase=spinPhase(time);return phase-SPIN_LINGER*Math.sin(phase)}var BlockRaster=class{bits=new Uint8Array(0);counts=new Uint8Array(0);rgb=new Float32Array(0);haloAmount=new Float32Array(0);haloRgb=new Float32Array(0);width=0;height=0;depth=new Float32Array(0);faceIds=new Uint16Array(0);dirty;haloDirty;cameraDistance;constructor(cameraDistance){this.cameraDistance=cameraDistance}render(width,height,pose,boxes,background,haloStrength){let dotWidth=width*2,dotHeight=height*4;if(width!==this.width||height!==this.height)this.width=width,this.height=height,this.bits=new Uint8Array(width*height),this.counts=new Uint8Array(width*height),this.rgb=new Float32Array(width*height*3),this.haloAmount=new Float32Array(width*height),this.haloRgb=new Float32Array(width*height*3),this.haloDirty=void 0,this.depth=new Float32Array(dotWidth*dotHeight).fill(1/0),this.faceIds=new Uint16Array(dotWidth*dotHeight),this.dirty=void 0;else if(this.dirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.dirty;for(let row=minY2;row<=maxY2;row++)this.bits.fill(0,row*width+minX2,row*width+maxX2+1),this.counts.fill(0,row*width+minX2,row*width+maxX2+1),this.rgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.dirty=void 0}if(this.haloDirty){let{minX:minX2,minY:minY2,maxX:maxX2,maxY:maxY2}=this.haloDirty;for(let row=minY2;row<=maxY2;row++)this.haloAmount.fill(0,row*width+minX2,row*width+maxX2+1),this.haloRgb.fill(0,(row*width+minX2)*3,(row*width+maxX2+1)*3);this.haloDirty=void 0}let m=rotation(pose.yaw,pose.pitch,pose.roll),{centerX,centerY,scale}=pose,cameraDistance=this.cameraDistance,origin=[m[6]*cameraDistance,m[7]*cameraDistance,m[8]*cameraDistance],light=isLight(background),faces=this.visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,light);if(faces.length===0)return;let minX=dotWidth,minY=dotHeight,maxX=-1,maxY=-1;for(let face of faces)minX=Math.min(minX,face.minX),minY=Math.min(minY,face.minY),maxX=Math.max(maxX,face.maxX),maxY=Math.max(maxY,face.maxY);if(maxX<minX||maxY<minY)return;let depth=this.depth,faceIds=this.faceIds;for(let faceIndex=0;faceIndex<faces.length;faceIndex++){let face=faces[faceIndex],a=face.axis,u=(a+1)%3,v=(a+2)%3,originA=origin[a],originU=origin[u],originV=origin[v],stepA=m[a]/scale,stepU=m[u]/scale,stepV=m[v]/scale,sx=(face.minX+.5-centerX)/scale;for(let dotY=face.minY;dotY<=face.maxY;dotY++){let sy=(dotY+.5-centerY)/scale,directionA=m[a]*sx+m[3+a]*sy-m[6+a]*cameraDistance,directionU=m[u]*sx+m[3+u]*sy-m[6+u]*cameraDistance,directionV=m[v]*sx+m[3+v]*sy-m[6+v]*cameraDistance,index=dotY*dotWidth+face.minX;for(let dotX=face.minX;dotX<=face.maxX;dotX++,index++){let t=(face.plane-originA)/directionA;if(t>0&&t<depth[index]){let hitU=originU+t*directionU,hitV=originV+t*directionV;hitU>=face.uMin&&hitU<=face.uMax&&hitV>=face.vMin&&hitV<=face.vMax&&(depth[index]=t,faceIds[index]=faceIndex+1)}directionA+=stepA,directionU+=stepU,directionV+=stepV}}}let bits=this.bits,counts=this.counts,rgb=this.rgb,cellMinX=width,cellMinY=height,cellMaxX=-1,cellMaxY=-1;for(let dotY=minY;dotY<=maxY;dotY++){let index=dotY*dotWidth+minX;for(let dotX=minX;dotX<=maxX;dotX++,index++){let id=faceIds[index];if(id===0)continue;let face=faces[id-1],fog=clamp01(.15-cameraDistance*(1-depth[index])*.12)*(light?.5:1);faceIds[index]=0,depth[index]=1/0;let cellX=dotX>>1,cellY=dotY>>2,cell=cellY*width+cellX;bits[cell]|=DOT_BITS[(dotY&3)*2+(dotX&1)],counts[cell]++,rgb[cell*3]+=face.red+(background[0]-face.red)*fog,rgb[cell*3+1]+=face.green+(background[1]-face.green)*fog,rgb[cell*3+2]+=face.blue+(background[2]-face.blue)*fog,cellX<cellMinX&&(cellMinX=cellX),cellX>cellMaxX&&(cellMaxX=cellX),cellY<cellMinY&&(cellMinY=cellY),cellY>cellMaxY&&(cellMaxY=cellY)}}cellMaxX>=0&&(this.dirty={minX:cellMinX,minY:cellMinY,maxX:cellMaxX,maxY:cellMaxY}),haloStrength>0&&this.renderHalo(haloStrength)}renderHalo(strength){let cells=this.dirty;if(!cells)return;let{width,height,counts,rgb}=this,minX=Math.max(0,cells.minX-HALO_RADIUS_X),maxX=Math.min(width-1,cells.maxX+HALO_RADIUS_X),minY=Math.max(0,cells.minY-HALO_RADIUS_Y),maxY=Math.min(height-1,cells.maxY+HALO_RADIUS_Y),regionWidth=maxX-minX+1,tent=radius=>{let weights=Array.from({length:radius*2+1},(_,i)=>radius+1-Math.abs(i-radius)),total=weights.reduce((sum,weight)=>sum+weight,0);return weights.map(weight=>weight/total)},weightsX=tent(HALO_RADIUS_X),weightsY=tent(HALO_RADIUS_Y),rows=cells.maxY-cells.minY+1,horizontal=new Float32Array(rows*regionWidth*4);for(let y=cells.minY;y<=cells.maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dx=-HALO_RADIUS_X;dx<=HALO_RADIUS_X;dx++){let sourceX=x+dx;if(sourceX<cells.minX||sourceX>cells.maxX)continue;let source=y*width+sourceX,count=counts[source];if(count===0)continue;let weight=weightsX[dx+HALO_RADIUS_X]/8;coverage+=count*weight,red+=rgb[source*3]*weight,green+=rgb[source*3+1]*weight,blue+=rgb[source*3+2]*weight}let target=((y-cells.minY)*regionWidth+(x-minX))*4;horizontal[target]=coverage,horizontal[target+1]=red,horizontal[target+2]=green,horizontal[target+3]=blue}for(let y=minY;y<=maxY;y++)for(let x=minX;x<=maxX;x++){let coverage=0,red=0,green=0,blue=0;for(let dy=-HALO_RADIUS_Y;dy<=HALO_RADIUS_Y;dy++){let sourceY=y+dy;if(sourceY<cells.minY||sourceY>cells.maxY)continue;let weight=weightsY[dy+HALO_RADIUS_Y],source=((sourceY-cells.minY)*regionWidth+(x-minX))*4;coverage+=horizontal[source]*weight,red+=horizontal[source+1]*weight,green+=horizontal[source+2]*weight,blue+=horizontal[source+3]*weight}let target=y*width+x,count=counts[target];if(count>0&&count/8>coverage&&(coverage=count/8,red=rgb[target*3]/count*coverage,green=rgb[target*3+1]/count*coverage,blue=rgb[target*3+2]/count*coverage),coverage<=0)continue;let amount=Math.round(strength*Math.min(1,coverage)**.7*HALO_LEVELS)/HALO_LEVELS;amount<=0||(this.haloAmount[target]=amount,this.haloRgb[target*3]=Math.round(red/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+1]=Math.round(green/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP,this.haloRgb[target*3+2]=Math.round(blue/coverage/LOGO_COLOR_STEP)*LOGO_COLOR_STEP)}this.haloDirty={minX,minY,maxX,maxY}}visibleFaces(m,origin,pose,boxes,dotWidth,dotHeight,lightBackground){let faces=[],cameraDistance=this.cameraDistance;for(let box of boxes)for(let a=0;a<3;a++){let u=(a+1)%3,v=(a+2)%3;for(let side of[-1,1]){let plane=side>0?box.max[a]:box.min[a];if((origin[a]-plane)*side<=0||boxes.some(other=>other!==box&&(side>0?other.min[a]:other.max[a])===plane&&other.min[u]<=box.min[u]&&other.max[u]>=box.max[u]&&other.min[v]<=box.min[v]&&other.max[v]>=box.max[v]))continue;let minX=1/0,minY=1/0,maxX=-1/0,maxY=-1/0,corner=[0,0,0];for(let cornerU of[box.min[u],box.max[u]])for(let cornerV of[box.min[v],box.max[v]]){corner[a]=plane,corner[u]=cornerU,corner[v]=cornerV;let x=m[0]*corner[0]+m[1]*corner[1]+m[2]*corner[2],y=m[3]*corner[0]+m[4]*corner[1]+m[5]*corner[2],z=m[6]*corner[0]+m[7]*corner[1]+m[8]*corner[2],perspective=pose.scale*cameraDistance/(cameraDistance-z),screenX=pose.centerX+x*perspective,screenY=pose.centerY+y*perspective;minX=Math.min(minX,screenX),minY=Math.min(minY,screenY),maxX=Math.max(maxX,screenX),maxY=Math.max(maxY,screenY)}let face={minX:Math.max(0,Math.floor(minX)),minY:Math.max(0,Math.floor(minY)),maxX:Math.min(dotWidth-1,Math.ceil(maxX)),maxY:Math.min(dotHeight-1,Math.ceil(maxY))};if(face.maxX<face.minX||face.maxY<face.minY)continue;let nx=m[a]*side,ny=m[3+a]*side,nz=m[6+a]*side,diffuse=Math.max(0,nx*LIGHT[0]+ny*LIGHT[1]+nz*LIGHT[2]),rim=Math.max(0,nx*.8-nz*.3),specular=lightBackground?0:Math.max(0,nx*HALF_VECTOR[0]+ny*HALF_VECTOR[1]+nz*HALF_VECTOR[2])**24*.6*255,light=lightBackground?Math.min(1,.55+diffuse*.45+rim*.1):.45+diffuse*.78+rim*.25;faces.push({axis:a,plane,uMin:box.min[u],uMax:box.max[u],vMin:box.min[v],vMax:box.max[v],...face,red:Math.min(255,box.color[0]*light+specular),green:Math.min(255,box.color[1]*light+specular),blue:Math.min(255,box.color[2]*light+specular)})}}return faces}},playing=!1;async function playEasterEgg3d(tui,screen,egg){if(playing)return;playing=!0;let reported=await tui.queryTerminalColors({timeoutMs:100}),dark=theme.appearance==="dark",toRgbTuple=(rgb,fallback)=>rgb?[rgb.r,rgb.g,rgb.b]:fallback,colors={foreground:toRgbTuple(reported.foreground,toRgb(theme.colors.text)),background:toRgbTuple(reported.background,dark?[0,0,0]:[255,255,255])};if(tui.hasOverlay()){playing=!1;return}let model=egg.kind==="armin"?arminModel(toRgb(theme.colors.accent)):relayLogoModel({column:egg.column,row:egg.row}),animation=new EasterEgg3dAnimation(tui,screen,model,colors,()=>{playing=!1,overlay.hide()}),overlay=tui.showOverlay(animation,{anchor:"top-left",width:"100%",maxHeight:"100%"})}var EasterEgg3dAnimation=class{tui;screen;model;foreground;background;onDone;startTime=performance.now();lastRender=performance.now();timer;exit;shuffle;screenWidth=-1;screenHeight=-1;stars=[];cells=[];ansiCache=new Map;raster;constructor(tui,screen,model,colors,onDone){this.tui=tui,this.screen=screen,this.model=model,this.raster=new BlockRaster(model.cameraDistance),this.foreground=colors.foreground,this.background=colors.background,this.onDone=onDone,this.timer=setInterval(()=>{this.exit&&this.exitProgress()>=1||performance.now()-this.lastRender>1e3?this.finish():this.tui.requestRender()},FRAME_MS),this.timer.unref?.()}close(){if(this.exit){this.finish();return}let time=this.elapsed(),yaw=spinAngle(time),turn=Math.PI*2;this.exit={start:performance.now(),time,yaw,targetYaw:Math.ceil(yaw/turn)*turn,offsets:this.blockOffsets(time)}}handleInput(data){let keybindings=getKeybindings();(keybindings.matches(data,"tui.select.cancel")||keybindings.matches(data,"app.clear"))&&this.close()}handleMouse(event){return event.type==="click"&&this.close(),{handled:!0,render:!1}}invalidate(){this.screenWidth=-1,this.screenHeight=-1,this.ansiCache.clear()}render(width){let height=Math.max(1,this.tui.terminal.rows),foreground=this.foreground,background=this.background;this.lastRender=performance.now(),(width!==this.screenWidth||height!==this.screenHeight)&&(this.screenWidth=width,this.screenHeight=height,this.cells=this.prepareCells(width,foreground),this.stars=this.prepareStars(width,height));let dissolveTime,pose,hintAlpha,starAlpha,offsets;if(this.exit){let progress=this.exitProgress(),landing=clamp01(progress/.8),settle=1-smooth(landing);dissolveTime=Math.min(this.exit.time,DISSOLVE_END)*(1-progress),pose=this.pose(width,height,this.flyProgress(this.exit.time)*settle,this.exit.time),pose.yaw=this.exit.yaw+(this.exit.targetYaw-this.exit.yaw)*easeOut(landing),pose.pitch*=settle,pose.roll*=settle,hintAlpha=this.hintAlpha(this.exit.time)*(1-smooth(progress/.2)),starAlpha=this.starAlpha(this.exit.time)*(1-smooth(progress/.3));let gather=1-smooth(progress/.5);offsets=this.exit.offsets.map(([x,y,z])=>[x*gather,y*gather,z*gather])}else{let time=this.elapsed();dissolveTime=time,pose=this.pose(width,height,this.flyProgress(time),time),hintAlpha=this.hintAlpha(time),starAlpha=this.starAlpha(time),offsets=this.blockOffsets(time)}let{columns,rows}=this.model,boxes=this.model.blocks.map((block,index)=>{let[dx,dy,dz]=offsets[index],x=block.home[0]-columns/2+dx,y=block.home[1]-rows/2+dy;return{min:[x,y,dz-DEPTH/2],max:[x+1,y+1,dz+DEPTH/2],color:block.color}}),raster=this.raster;raster.render(width,height,pose,boxes,background,isLight(background)?LIGHT_HALO_STRENGTH:0);let halo=(index,base)=>{let amount=raster.haloAmount[index];if(amount<=0)return base;let color=raster.haloRgb;return mix(base??background,[color[index*3],color[index*3+1],color[index*3+2]],amount)},backgroundFade=smooth(dissolveTime/BACKGROUND_FADE),textFade=smooth(dissolveTime/.6)*.3,textActive=dissolveTime<DISSOLVE_END||backgroundFade<1,hint=this.hint(width,height,hintAlpha,background),frame=Math.floor(dissolveTime*14),now=this.elapsed(),starLevel=Math.round(starAlpha*STAR_ALPHA_LEVELS)/STAR_ALPHA_LEVELS,starfield=index=>{if(starLevel<=0)return;let star=this.stars[index];if(!star)return;let flicker=Math.round((.5+.5*Math.sin(now*star.speed+star.phase))*STAR_FLICKER_LEVELS)/STAR_FLICKER_LEVELS;return{text:star.glyph,fg:mix(background,mix(foreground,star.tint,.5),star.strength*(.7+.3*flicker)*starLevel)}},lines=[];for(let row=0;row<height;row++){let cells=this.cells[row]??[],line="",currentFg=-1,currentBg=-1,emit=(text,fg,bg)=>{let fgKey=fg?this.pack(fg):-1,bgKey=bg?this.pack(bg):-1;fgKey!==currentFg&&text!==" "&&(line+=fg?this.ansi(fgKey,!1):"\x1B[39m",currentFg=fgKey),bgKey!==currentBg&&(line+=bg?this.ansi(bgKey,!0):"\x1B[49m",currentBg=bgKey),line+=text};for(let column=0;column<width;column++){let index=row*width+column,cell=textActive?cells[column]:void 0,cellBg=halo(index,cell?.bg&&backgroundFade<1?mix(cell.bg,background,backgroundFade):void 0);if(hint&&row===hint.row&&column>=hint.start&&column<hint.start+hint.text.length){let offset=column-hint.start;emit(hint.text[offset],offset<hint.keyLength?hint.keyColor:hint.color,cellBg);continue}let dots=raster.bits[index];if(dots){let step=LOGO_COLOR_STEP*raster.counts[index],rgb=raster.rgb,color=[Math.round(rgb[index*3]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+1]/step)*LOGO_COLOR_STEP,Math.round(rgb[index*3+2]/step)*LOGO_COLOR_STEP];emit(BRAILLE[dots],color,cellBg);continue}if(!cell){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let dust=(dissolveTime-cell.delay)/DUST_DURATION;if(dust<0&&cell.width===2&&!raster.bits[index+1]){emit(cell.text,mix(cell.fg,background,textFade),cellBg),column++;continue}if(dust<0&&cell.width===1){emit(cell.text,mix(cell.fg,background,textFade),cellBg);continue}let dotCount=dust<0?cell.ink:Math.round(cell.ink*(1-clamp01(dust)));if(dotCount<=0){let star=starfield(index);emit(star?.text??" ",star?.fg,cellBg);continue}let bits=0,placed=0;for(let attempt=0;placed<dotCount&&attempt<32;attempt++){let bit=DOT_BITS[Math.floor(hash(cell.seed*7919+frame*131+attempt)*8)];bits&bit||(bits|=bit,placed++)}let fade=textFade+(1-textFade)*clamp01(dust)**.8;emit(BRAILLE[bits],mix(cell.fg,background,fade),cellBg)}lines.push(`${line}\x1B[0m`)}return lines}elapsed(){return(performance.now()-this.startTime)/1e3}exitProgress(){return this.exit?clamp01((performance.now()-this.exit.start)/1e3/EXIT_DURATION):0}finish(){this.timer&&(clearInterval(this.timer),this.timer=void 0,this.onDone())}blockOffsets(time){let blocks=this.model.blocks,home=()=>blocks.map(()=>[0,0,0]);if(time<PUZZLE_START)return home();let cycle=Math.floor((time-PUZZLE_START)/PUZZLE_CYCLE),local=time-PUZZLE_START-cycle*PUZZLE_CYCLE;this.shuffle?.cycle!==cycle&&(this.shuffle={cycle,steps:shuffleSteps(this.model,cycle)});let steps=this.shuffle.steps,offset=(position,index)=>{let block=blocks[index].home;return[position[0]-block[0],position[1]-block[1],position[2]-block[2]]},shuffleEnd=PUZZLE_STEP*PUZZLE_STEPS;if(local<shuffleEnd){let step=Math.floor(local/PUZZLE_STEP),progress=smooth((local-step*PUZZLE_STEP)/PUZZLE_STEP);return steps[step].map((from,index)=>{let a=offset(from,index),b=offset(steps[step+1][index],index);return[a[0]+(b[0]-a[0])*progress,a[1]+(b[1]-a[1])*progress,a[2]+(b[2]-a[2])*progress]})}if(local<shuffleEnd+PUZZLE_RETURN){let u=(local-shuffleEnd)/PUZZLE_RETURN,remaining=1-smooth(u),arc=Math.sin(Math.PI*clamp01(u))*.8;return steps[PUZZLE_STEPS].map((position,index)=>{let[x,y,z]=offset(position,index);return[x*remaining,y*remaining,z*remaining+(index%2===0?arc:-arc)]})}return home()}flyProgress(time){return smooth((time-FLY_START)/FLY_DURATION)}starAlpha(time){return smooth((time-STARS_START)/STARS_FADE)}hintAlpha(time){return smooth((time-FLY_START-FLY_DURATION)/HINT_FADE)}pose(width,height,progress,time){let{columns,rows,cameraDistance,radius,widthShare,origin}=this.model,reach=radius*(cameraDistance/(cameraDistance-radius)),startScale=origin?2*(cameraDistance-DEPTH/2)/cameraDistance:START_SCALE,endScale=Math.max(startScale,Math.min(width*2*widthShare,(height*4-8)*.48)/reach),endX=width,endY=height*2-2,startX=origin?origin.column*2+columns:endX,startY=origin?origin.row*4+rows:endY;return{centerX:startX+(endX-startX)*progress,centerY:startY+(endY-startY)*progress,scale:startScale*(endScale/startScale)**progress,yaw:spinAngle(time),pitch:.3*Math.sin(spinPhase(time))*progress,roll:.06*Math.sin(2*spinPhase(time))*progress}}hint(width,height,alpha,background){if(alpha<=0)return;let key=formatKeyText(getKeybindings().getKeys("tui.select.cancel")[0]??"escape"),text=`${key} to return`;if(!(text.length>width))return{row:height-2,start:Math.floor((width-text.length)/2),text,keyLength:key.length,keyColor:mix(background,toRgb(theme.colors.muted),alpha),color:mix(background,toRgb(theme.colors.dim),alpha)}}prepareStars(width,height){let stars=new Array(width*height);for(let index=0;index<width*height;index++){if(hash(index*3+20973)>=STAR_DENSITY)continue;let random=salt=>hash(index*7+salt*40503);stars[index]={glyph:BRAILLE[DOT_BITS[Math.floor(random(1)*8)]],tint:STAR_TINTS[Math.floor(random(2)*STAR_TINTS.length)],strength:.1+random(3)*.12,phase:random(4)*Math.PI*2,speed:.4+random(5)*.8}}return stars}prepareCells(width,foreground){let cells=parseScreen(this.screen,width,foreground,this.background),height=Math.max(1,this.tui.terminal.rows),{columns,rows,origin}=this.model,centerX=origin?origin.column+columns/2:width/2,centerY=origin?origin.row+rows/4:height/2,farthest=Math.hypot(Math.max(centerX,width-centerX),Math.max(centerY,height-centerY)*2);for(let row=0;row<cells.length;row++){let line=cells[row];for(let column=0;column<line.length;column++){let cell=line[column],owner=cell.width===0?line[column-1]:cell,seed=hash(row*65537+column);if(cell.width!==0){let distance=Math.hypot(column-centerX,(row-centerY)*2)/farthest;cell.delay=FLY_START+distance*WAVE_SPREAD+seed*WAVE_JITTER}else cell.delay=owner.delay;cell.seed=row*65537+column,cell.ink=glyphInk(owner.text,seed)}}if(origin)for(let row=origin.row;row<origin.row+Math.ceil(rows/2);row++){let line=cells[row];if(line)for(let column=origin.column;column<origin.column+columns;column++){let cell=line[column];cell&&(cell.text=" ",cell.width=1,cell.ink=0,cell.bg=void 0)}}return cells}pack(color){return Math.round(color[0])<<16|Math.round(color[1])<<8|Math.round(color[2])}ansi(key,isBackground){let cacheKey=key*2+(isBackground?1:0),value=this.ansiCache.get(cacheKey);if(value===void 0){let color=rgbColor(key>>16&255,key>>8&255,key&255),mode=theme.getColorMode();value=isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode),this.ansiCache.set(cacheKey,value)}return value}};export{EasterEgg3dAnimation,playEasterEgg3d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-ISNO4JTR.js";import{formatSize,writeOutputFile}from"./chunk-MP5FU7MG.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-XDAWU2J5.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>this.handleMessage(message)),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!(this.finished||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item);break;case"call":this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}handleDone(message){if(!message.ok){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),message.writes)}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
2
+ import{Bm25Ranker,CODEMODE_DOCS_PATH,CODEMODE_STORE_ENTRY_TYPE,DEFAULT_TOOL_SEARCH_LIMIT,combineUsage,createToolSearchDocument,getCodemodeCallableTools,parseCodemodeSource,renderToolSample,toCodemodeDeclaration,toCodemodeIdentifier}from"./chunk-PJWDW5WR.js";import{formatSize,writeOutputFile}from"./chunk-UVFWV6YH.js";import{getCodemodeWorkerSpecifier,getQuickJSWasmPath}from"./chunk-IDUCLYG3.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";import{Worker}from"node:worker_threads";import{readFile}from"node:fs/promises";import{createRequire}from"node:module";var modules=new Map;function loadQuickJSWasm(path){let resolved=path??createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),module=modules.get(resolved);if(!module){let{WebAssembly}=globalThis;module=readFile(resolved).then(bytes=>WebAssembly.compile(bytes)).catch(error=>{throw modules.delete(resolved),error}),modules.set(resolved,module)}return module}function isWorkerToHostMessage(value){if(typeof value!="object"||value===null)return!1;let type=value.type;return type==="call"||type==="output"||type==="done"||type==="crash"}var DEFAULT_TIMEOUT_MS=3e5,IDENTIFIER=/^[A-Za-z_$][A-Za-z0-9_$]*$/,RESERVED_GLOBALS=new Set(["tools","ALL_TOOLS","console","text","image","exit","globalThis","store","load"]);function errorMessage(error){return error instanceof Error?error.message:String(error)}function serializeStore(store){let serialized={};for(let[key,value]of Object.entries(store??{})){let json=JSON.stringify(value);json!==void 0&&(serialized[key]=json)}return serialized}function parseStoreWrites(json){let writes={set:{},delete:[]};for(let[key,value]of JSON.parse(json))value===void 0?writes.delete.push(key):writes.set[key]=JSON.parse(value);return writes}function defaultWorkerUrl(){return new URL(import.meta.url.endsWith(".ts")?"./worker.ts":"./worker.js",import.meta.url)}var Execution=class{promise;resolveResult;worker;interrupt=new SharedArrayBuffer(4);tools;globals;signal;timer;output=[];calls=[];pending=new Map;finished=!1;constructor(options){this.promise=new Promise(resolve=>{this.resolveResult=resolve}),this.tools=options.tools,this.globals=options.globals,this.signal=options.signal,Number.isFinite(options.timeoutMs)&&(this.timer=setTimeout(()=>{this.finish({kind:"timeout",message:`Execution timed out after ${options.timeoutMs} ms`})},options.timeoutMs)),options.signal&&(options.signal.aborted?this.onAbort():options.signal.addEventListener("abort",this.onAbort,{once:!0})),options.wasm.then(wasm=>this.start(options,wasm),error=>{this.finish({kind:"sandbox",message:`Failed to load QuickJS: ${errorMessage(error)}`})})}abort(message){return this.finish({kind:"aborted",message}),this.promise}start(options,wasm){if(this.finished)return;let workerData={code:options.code,tools:[...options.tools.values()].map(tool=>({name:tool.name,jsName:toCodemodeIdentifier(tool.name),description:tool.description??""})),globals:[...options.globals.values()].map(global=>({name:global.name,spread:global.spread===!0})),wasm,memoryLimitBytes:options.memoryLimitBytes,store:options.store,interrupt:this.interrupt},worker;try{worker=new Worker(options.workerUrl,{workerData})}catch(error){this.finish({kind:"sandbox",message:`Failed to start worker: ${errorMessage(error)}`});return}this.worker=worker,worker.on("message",message=>this.handleMessage(message)),worker.on("error",error=>{this.finish({kind:"sandbox",name:error instanceof Error?error.name:void 0,message:errorMessage(error)})}),worker.on("exit",code=>{this.finish({kind:"sandbox",message:`Worker exited with code ${code} before the script settled`})})}onAbort=()=>{let reason=this.signal?.reason;this.finish({kind:"aborted",message:reason instanceof Error?reason.message:"Execution aborted"})};post(message){this.worker?.postMessage(message)}handleMessage(message){if(!(this.finished||!isWorkerToHostMessage(message)))switch(message.type){case"output":this.output.push(message.item);break;case"call":this.handleCall(message);break;case"done":this.handleDone(message);break;case"crash":this.finish({kind:"sandbox",message:message.message});break}}handleDone(message){if(!message.ok){let parsed=JSON.parse(message.error);this.finish({kind:"script",...parsed});return}this.finish(void 0,message.value===void 0?void 0:JSON.parse(message.value),message.writes)}async handleCall(message){let{id,name}=message,isTool=message.target==="tool",record=isTool?{name,status:"cancelled",durationMs:0}:void 0;record&&this.calls.push(record);let pending={record,startedAt:performance.now(),controller:new AbortController};this.pending.set(id,pending);let status,reply;try{let tool=(isTool?this.tools:this.globals).get(name);if(!tool)throw new Error(`Unknown ${isTool?"tool":"global"} "${name}"`);let args=message.args===void 0?void 0:JSON.parse(message.args),value=await tool.execute(args,{signal:pending.controller.signal});reply={type:"result",id,ok:!0,payload:value===void 0?void 0:JSON.stringify(value)},status="ok"}catch(error){reply={type:"result",id,ok:!1,payload:errorMessage(error)},status="error"}this.pending.delete(id)&&(record&&(record.status=status,record.durationMs=performance.now()-pending.startedAt),this.post(reply))}finish(error,value,writes){if(this.finished)return;this.finished=!0,clearTimeout(this.timer),this.signal?.removeEventListener("abort",this.onAbort);let now=performance.now();for(let pending of this.pending.values())pending.record&&(pending.record.durationMs=now-pending.startedAt),pending.controller.abort();this.pending.clear();let result=error?{ok:!1,error,output:this.output,calls:this.calls}:{ok:!0,value,output:this.output,calls:this.calls,storeWrites:writes===void 0?{set:{},delete:[]}:parseStoreWrites(writes)};if(!this.worker){this.resolveResult(result);return}Atomics.store(new Int32Array(this.interrupt),0,1),this.worker.terminate().catch(()=>{}).then(()=>this.resolveResult(result))}},CodemodeSandbox=class{toolsByName=new Map;globalsByName=new Map;timeoutMs;memoryLimitBytes;wasm;workerUrl;running=new Set;closed=!1;constructor(options={}){this.timeoutMs=options.timeoutMs??DEFAULT_TIMEOUT_MS,this.memoryLimitBytes=options.memoryLimitBytes,this.wasm=options.wasm,this.workerUrl=options.workerUrl??defaultWorkerUrl();for(let tool of options.tools??[])this.registerTool(tool);let namespaces=new Set;for(let global of options.globals??[]){let parts=global.name.split(".");if(parts.length>2||!parts.every(part=>IDENTIFIER.test(part))||RESERVED_GLOBALS.has(parts[0]))throw new Error(`Invalid global name "${global.name}"`);if(this.globalsByName.has(global.name))throw new Error(`Global "${global.name}" is already registered`);parts.length===2&&namespaces.add(parts[0]),this.globalsByName.set(global.name,global)}for(let name of namespaces)if(this.globalsByName.has(name))throw new Error(`Global "${name}" conflicts with the namespace "${name}"`)}registerTool(tool){if(this.toolsByName.has(tool.name))throw new Error(`Tool "${tool.name}" is already registered`);this.toolsByName.set(tool.name,tool)}unregisterTool(name){return this.toolsByName.delete(name)}get tools(){return[...this.toolsByName.values()]}get globals(){return[...this.globalsByName.values()]}execute(code,options={}){if(this.closed)return Promise.reject(new Error("Sandbox is closed"));let execution=new Execution({code,tools:new Map(this.toolsByName),globals:this.globalsByName,timeoutMs:options.timeoutMs??this.timeoutMs,signal:options.signal,memoryLimitBytes:this.memoryLimitBytes,store:serializeStore(options.store),wasm:this.wasm===void 0?loadQuickJSWasm():Promise.resolve(this.wasm),workerUrl:this.workerUrl});return this.running.add(execution),execution.promise.finally(()=>this.running.delete(execution))}async close(){this.closed=!0,await Promise.all([...this.running].map(execution=>execution.abort("Sandbox closed")))}};var IMAGE_HELPER_EXPECTS="image expects a non-empty image URL string, an object with image_url, or a raw MCP image block",PRELUDE_SOURCE=`(function (bridge, toolsJson, globalsJson, storeJson) {
3
3
  "use strict";
4
4
  const stringify = JSON.stringify;
5
5
  const parse = JSON.parse;
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-3QND5D7W.js";import"./chunk-3XNI2SB6.js";import"./chunk-MP5FU7MG.js";import"./chunk-XDAWU2J5.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-7ZBTLURV.js";import"./chunk-TZ2ZVU7E.js";import"./chunk-UVFWV6YH.js";import"./chunk-IDUCLYG3.js";import"./chunk-S3GGRYIO.js";import"./chunk-4L3WN2XY.js";export{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{dist_exports as dist_exports3}from"./chunk-H6S6DQTM.js";import{all_exports,compat_exports,compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-XSLAMYCK.js";import"./chunk-PTRF7IZB.js";import"./chunk-WMTXXI7H.js";import"./chunk-3XNI2SB6.js";import"./chunk-USJZMAIR.js";import{build_exports}from"./chunk-ISNO4JTR.js";import"./chunk-MP5FU7MG.js";import{dist_exports}from"./chunk-XDAWU2J5.js";import"./chunk-S3GGRYIO.js";import"./chunk-EQ2HXQGJ.js";import"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import"./chunk-KJUDFE6Y.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@relay-harness/agent-core":dist_exports2,"@relay-harness/tui":dist_exports,"@relay-harness/ai":compat_exports,"@relay-harness/ai/compat":compat_exports,"@relay-harness/ai/oauth":oauth_exports,"@relay-harness/ai/providers/all":all_exports,"@relay-harness/coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
2
+ import{dist_exports as dist_exports3}from"./chunk-6AEKWHDP.js";import{all_exports,compat_exports,compile_exports,dist_exports as dist_exports2,value_exports}from"./chunk-LVFZRSZQ.js";import"./chunk-WU7MEKPF.js";import"./chunk-FUPU6X73.js";import"./chunk-TZ2ZVU7E.js";import"./chunk-USJZMAIR.js";import{build_exports}from"./chunk-PJWDW5WR.js";import"./chunk-UVFWV6YH.js";import{dist_exports}from"./chunk-IDUCLYG3.js";import"./chunk-S3GGRYIO.js";import"./chunk-EQ2HXQGJ.js";import"./chunk-DRQDKNXA.js";import"./chunk-TRDNDS6A.js";import"./chunk-KJUDFE6Y.js";import"./chunk-A3JYRWB6.js";import"./chunk-4L3WN2XY.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@relay-harness/agent-core":dist_exports2,"@relay-harness/tui":dist_exports,"@relay-harness/ai":compat_exports,"@relay-harness/ai/compat":compat_exports,"@relay-harness/ai/oauth":oauth_exports,"@relay-harness/ai/providers/all":all_exports,"@relay-harness/coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-XSLAMYCK.js";import"./chunks/chunk-PTRF7IZB.js";import"./chunks/chunk-WMTXXI7H.js";import"./chunks/chunk-3XNI2SB6.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-ISNO4JTR.js";import"./chunks/chunk-MP5FU7MG.js";import{APP_NAME}from"./chunks/chunk-XDAWU2J5.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";function setupCli(){process.title=APP_NAME,process.env.RELAY_CODING_AGENT="true",process.env.AI_AGENT="relay",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-LVFZRSZQ.js";import"./chunks/chunk-WU7MEKPF.js";import"./chunks/chunk-FUPU6X73.js";import"./chunks/chunk-TZ2ZVU7E.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-PJWDW5WR.js";import"./chunks/chunk-UVFWV6YH.js";import{APP_NAME}from"./chunks/chunk-IDUCLYG3.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";function setupCli(){process.title=APP_NAME,process.env.RELAY_CODING_AGENT="true",process.env.AI_AGENT="relay",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();main(process.argv.slice(2));
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-H6S6DQTM.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-XSLAMYCK.js";import{ArminComponent}from"./chunks/chunk-PTRF7IZB.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-WMTXXI7H.js";import{readStoredCredential}from"./chunks/chunk-3XNI2SB6.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-ISNO4JTR.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-MP5FU7MG.js";import{CONFIG_DIR_NAME,Theme,VERSION,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getMarkdownTheme,getPackageDir,getReadmePath,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-XDAWU2J5.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-6AEKWHDP.js";import{AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getLastAssistantUsage,getLatestCompactionEntry,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-LVFZRSZQ.js";import{ArminComponent}from"./chunks/chunk-WU7MEKPF.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-FUPU6X73.js";import{readStoredCredential}from"./chunks/chunk-TZ2ZVU7E.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-PJWDW5WR.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-UVFWV6YH.js";import{CONFIG_DIR_NAME,Theme,VERSION,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getMarkdownTheme,getPackageDir,getReadmePath,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-IDUCLYG3.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";export{AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAndLoadExtensions,estimateTokens,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseSessionEntries,parseSkillBlock,prepareBranchEntries,rawKeyHint,readStoredCredential,renderDiff,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-XSLAMYCK.js";import"./chunks/chunk-PTRF7IZB.js";import"./chunks/chunk-WMTXXI7H.js";import"./chunks/chunk-3XNI2SB6.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-ISNO4JTR.js";import"./chunks/chunk-MP5FU7MG.js";import{APP_NAME}from"./chunks/chunk-XDAWU2J5.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.RELAY_CODING_AGENT="true";process.env.AI_AGENT="relay";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-LVFZRSZQ.js";import"./chunks/chunk-WU7MEKPF.js";import"./chunks/chunk-FUPU6X73.js";import"./chunks/chunk-TZ2ZVU7E.js";import"./chunks/chunk-USJZMAIR.js";import"./chunks/chunk-PJWDW5WR.js";import"./chunks/chunk-UVFWV6YH.js";import{APP_NAME}from"./chunks/chunk-IDUCLYG3.js";import"./chunks/chunk-S3GGRYIO.js";import"./chunks/chunk-EQ2HXQGJ.js";import"./chunks/chunk-DRQDKNXA.js";import"./chunks/chunk-TRDNDS6A.js";import"./chunks/chunk-KJUDFE6Y.js";import"./chunks/chunk-A3JYRWB6.js";import"./chunks/chunk-4L3WN2XY.js";process.title=`${APP_NAME}-rpc`;process.env.RELAY_CODING_AGENT="true";process.env.AI_AGENT="relay";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -103,12 +103,14 @@ export interface LayaSettings {
103
103
  escalateAfterFailures?: number;
104
104
  /** `advise` names unneeded tools in the plan; `enforce` also deactivates them. Default: `advise`. */
105
105
  toolRouting?: "advise" | "enforce";
106
- /** Start the local Laya server when laya/auto needs it and offer to install it on first use. Default: true. */
106
+ /** Install Laya in Docker when Relay starts and keep its container running. Default: true. */
107
107
  autostart?: boolean;
108
- /** Python 3.10 to 3.13 used to create the Laya environment. Default: the first of python3, python, py found. */
109
- python?: string;
108
+ /** Docker image of Laya. Default: the image built from this Relay version on ghcr.io. */
109
+ image?: string;
110
110
  /** Write routing telemetry to the agent directory. Default: true. */
111
111
  telemetry?: boolean;
112
+ /** Route requests similar to tasks learned with `/laya learn` by their labels, and show their lessons. Default: true. */
113
+ memory?: boolean;
112
114
  /** Classifier request timeout in milliseconds before falling back to keyword rules. Default: 5000. */
113
115
  timeoutMs?: number;
114
116
  }