pi-namespace-patch 1.0.2-namespace.2 → 1.0.4-namespace.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +50 -0
- package/README.md +8 -8
- package/dist/bundle/chunks/{anthropic-messages-MVG2FL56.js → anthropic-messages-Y22YDKSW.js} +1 -1
- package/dist/bundle/chunks/azure-openai-responses-YJDJIIDQ.js +2 -0
- package/dist/bundle/chunks/chunk-22CYIUS4.js +2 -0
- package/dist/bundle/chunks/{chunk-WCQZGZ6I.js → chunk-2QSWSXFK.js} +4 -4
- package/dist/bundle/chunks/{chunk-6FX7UEPL.js → chunk-64GOPQSC.js} +6 -4
- package/dist/bundle/chunks/{chunk-OSKPX3Z5.js → chunk-C47CLQZK.js} +1 -1
- package/dist/bundle/chunks/{chunk-OLBCNJCL.js → chunk-ERIW6MDO.js} +51 -47
- package/dist/bundle/chunks/chunk-F4TCZWQO.js +20 -0
- package/dist/bundle/chunks/{chunk-2KAZSACP.js → chunk-FKGBRPJC.js} +1 -1
- package/dist/bundle/chunks/{chunk-IKZJX7ZT.js → chunk-HQHD6PZI.js} +1 -1
- package/dist/bundle/chunks/chunk-KJUDFE6Y.js +11 -0
- package/dist/bundle/chunks/{chunk-G7EDXK4D.js → chunk-TAOL3JFA.js} +1 -1
- package/dist/bundle/chunks/chunk-VLMAON6X.js +15 -0
- package/dist/bundle/chunks/{chunk-BYB6ZAAQ.js → chunk-WE4MXUQS.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZSI3BL5Q.js → chunk-XXKX4I4Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-SYF2TF6W.js → chunk-YKYP4C4A.js} +9 -6
- package/dist/bundle/chunks/{chunk-DN3QEIXS.js → chunk-YTMEKMOC.js} +1 -1
- package/dist/bundle/chunks/chunk-ZBURYEWF.js +2 -0
- package/dist/bundle/chunks/{cli-KILDDGW3.js → cli-FRW732V6.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-X5PVWWYJ.js → cloudflare-workers-ai-system-one-NM3JRRWQ.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +99 -4
- package/dist/bundle/chunks/{easter-egg-3d-T5FFWIBR.js → easter-egg-3d-GBYHZI2E.js} +1 -1
- package/dist/bundle/chunks/execute-MNHU53Y5.js +484 -0
- package/dist/bundle/chunks/{google-generative-ai-ZOK6CV7D.js → google-generative-ai-XMFHGQC5.js} +1 -1
- package/dist/bundle/chunks/{google-vertex-VKWZQ3AY.js → google-vertex-4XRRNP74.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-7DAUEE4N.js → mistral-conversations-Q22M3IBG.js} +1 -1
- package/dist/bundle/chunks/{openai-codex-responses-TC3OK7B4.js → openai-codex-responses-4MYQSO5E.js} +1 -1
- package/dist/bundle/chunks/{openai-completions-GWHGMQ3T.js → openai-completions-OSRCWAAA.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-EZ7FJ2KL.js → openai-responses-UHF3DHNG.js} +1 -1
- package/dist/bundle/chunks/{runtime-D5I2NTIF.js → runtime-FW2HXAJ6.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-A4CZTQWZ.js → typesafe-system-one-PRR5K6CI.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-3HQKVCRO.js +2 -0
- package/dist/bundle/cli-runtime.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/cli/args.d.ts +1 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +11 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +18 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +44 -6
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +26 -4
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +47 -14
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -7
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/extensions/types.d.ts +2 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/keybindings.d.ts +4 -4
- package/dist/core/mcp-servers.d.ts +8 -0
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +30 -7
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/resource-loader.d.ts +3 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +4 -3
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts +9 -4
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/skills.d.ts +4 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt.d.ts +6 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +9 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +4 -10
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/read.d.ts +13 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +18 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/extensions/codemode/execute.d.ts.map +1 -1
- package/dist/extensions/codemode/execute.js +51 -9
- package/dist/extensions/codemode/execute.js.map +1 -1
- package/dist/extensions/codemode/index.d.ts.map +1 -1
- package/dist/extensions/codemode/index.js +1 -0
- package/dist/extensions/codemode/index.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +9 -2
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +13 -5
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/mcp/resources.d.ts +3 -4
- package/dist/extensions/mcp/resources.d.ts.map +1 -1
- package/dist/extensions/mcp/resources.js +3 -4
- package/dist/extensions/mcp/resources.js.map +1 -1
- package/dist/extensions/mcp/runtime.d.ts +4 -1
- package/dist/extensions/mcp/runtime.d.ts.map +1 -1
- package/dist/extensions/mcp/runtime.js +22 -5
- package/dist/extensions/mcp/runtime.js.map +1 -1
- package/dist/extensions/mcp/tools.d.ts +2 -1
- package/dist/extensions/mcp/tools.d.ts.map +1 -1
- package/dist/extensions/mcp/tools.js +6 -10
- package/dist/extensions/mcp/tools.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +7 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +42 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +1 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/utils/output-files.d.ts +15 -0
- package/dist/utils/output-files.d.ts.map +1 -0
- package/dist/utils/output-files.js +30 -0
- package/dist/utils/output-files.js.map +1 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +6 -1
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/docs/cli.md +15 -3
- package/docs/codemode.md +6 -5
- package/docs/extensions.md +1 -1
- package/docs/keybindings.md +4 -4
- package/docs/mcp.md +3 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +10 -10
- package/dist/bundle/chunks/azure-openai-responses-7AMFUIWJ.js +0 -2
- package/dist/bundle/chunks/chunk-7JGR3GZN.js +0 -11
- package/dist/bundle/chunks/chunk-OYBSLV7Y.js +0 -16
- package/dist/bundle/chunks/chunk-PDFMCAOZ.js +0 -19
- package/dist/bundle/chunks/chunk-VIV3CWXG.js +0 -2
- package/dist/bundle/chunks/execute-RYVK27GT.js +0 -388
- package/dist/bundle/chunks/virtual-modules-J2M3WAR2.js +0 -2
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{VisualLinePreview,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs}from"./chunk-OYBSLV7Y.js";import{Container,Spacer,Text,getAgentDir,getFileRevision,keyHint,normalizePath,require_cross_spawn,stripBom}from"./chunk-6FX7UEPL.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
|
-
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=writeFile2;function writeFile2(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&¤tTime-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";if(value.clientRegistration!==void 0&&value.clientRegistration!=="dcr"){if(value.clientRegistration!=="cimd")return'oauth.clientRegistration must be "dcr" or "cimd"';if(value.clientId!==void 0||value.clientName!==void 0)return'oauth.clientRegistration "cimd" cannot be combined with oauth.clientId or oauth.clientName';let callback=typeof value.callbackUrl=="string"?new URL(value.callbackUrl):void 0;if(callback&&(callback.hostname==="[::1]"||callback.pathname!=="/callback"))return'oauth.clientRegistration "cimd" requires oauth.callbackUrl on localhost or 127.0.0.1 with path /callback'}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 DEFAULT_MAX_LINES=2e3,DEFAULT_MAX_BYTES=51200;function splitLinesForCounting(content){if(content.length===0)return[];let lines=content.split(`
|
|
4
|
-
`);return content.endsWith(`
|
|
5
|
-
`)&&lines.pop(),lines}function formatSize(bytes){return bytes<1024?`${bytes}B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)}KB`:`${(bytes/(1024*1024)).toFixed(1)}MB`}function truncateHead(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};if(Buffer.byteLength(lines[0],"utf-8")>maxBytes)return{content:"",truncated:!0,truncatedBy:"bytes",totalLines,totalBytes,outputLines:0,outputBytes:0,lastLinePartial:!1,firstLineExceedsLimit:!0,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines";for(let i=0;i<lines.length&&i<maxLines;i++){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(i>0?1:0);if(outputBytesCount+lineBytes>maxBytes){truncatedBy="bytes";break}outputLinesArr.push(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
6
|
-
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateTail(content,options={}){let maxLines=options.maxLines??2e3,maxBytes=options.maxBytes??51200,totalBytes=Buffer.byteLength(content,"utf-8"),lines=splitLinesForCounting(content),totalLines=lines.length;if(totalLines<=maxLines&&totalBytes<=maxBytes)return{content,truncated:!1,truncatedBy:null,totalLines,totalBytes,outputLines:totalLines,outputBytes:totalBytes,lastLinePartial:!1,firstLineExceedsLimit:!1,maxLines,maxBytes};let outputLinesArr=[],outputBytesCount=0,truncatedBy="lines",lastLinePartial=!1;for(let i=lines.length-1;i>=0&&outputLinesArr.length<maxLines;i--){let line=lines[i],lineBytes=Buffer.byteLength(line,"utf-8")+(outputLinesArr.length>0?1:0);if(outputBytesCount+lineBytes>maxBytes){if(truncatedBy="bytes",outputLinesArr.length===0){let truncatedLine=truncateStringToBytesFromEnd(line,maxBytes);outputLinesArr.unshift(truncatedLine),outputBytesCount=Buffer.byteLength(truncatedLine,"utf-8"),lastLinePartial=!0}break}outputLinesArr.unshift(line),outputBytesCount+=lineBytes}outputLinesArr.length>=maxLines&&outputBytesCount<=maxBytes&&(truncatedBy="lines");let outputContent=outputLinesArr.join(`
|
|
7
|
-
`),finalOutputBytes=Buffer.byteLength(outputContent,"utf-8");return{content:outputContent,truncated:!0,truncatedBy,totalLines,totalBytes,outputLines:outputLinesArr.length,outputBytes:finalOutputBytes,lastLinePartial,firstLineExceedsLimit:!1,maxLines,maxBytes}}function truncateStringToBytesFromEnd(str,maxBytes){let buf=Buffer.from(str,"utf-8");if(buf.length<=maxBytes)return str;let start=buf.length-maxBytes;for(;start<buf.length&&(buf[start]&192)===128;)start++;return buf.slice(start).toString("utf-8")}function truncateLine(line,maxChars=500){return line.length<=maxChars?{text:line,wasTruncated:!1}:{text:`${line.slice(0,maxChars)}... [truncated]`,wasTruncated:!0}}function truncateMiddle(content,maxBytes){let buf=Buffer.from(content,"utf-8"),totalLines=splitLinesForCounting(content).length;if(buf.length<=maxBytes)return{content,truncated:!1,removedChars:0,totalBytes:buf.length,totalLines};let isBoundary=index=>index>=buf.length||(buf[index]&192)!==128,headEnd=Math.floor(maxBytes/2);for(;headEnd>0&&!isBoundary(headEnd);)headEnd--;let tailStart=buf.length-(maxBytes-Math.floor(maxBytes/2));for(;tailStart<buf.length&&!isBoundary(tailStart);)tailStart++;let head=buf.subarray(0,headEnd).toString("utf-8"),tail=buf.subarray(tailStart).toString("utf-8"),removedChars=Array.from(buf.subarray(headEnd,tailStart).toString("utf-8")).length;return{content:`${head}\u2026${removedChars} chars truncated\u2026${tail}`,truncated:!0,removedChars,totalBytes:buf.length,totalLines}}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)}
|
|
8
|
-
`;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(`
|
|
9
|
-
`);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(`
|
|
10
|
-
`);for(;newline>=0;)processLine(buffered.slice(0,newline)),buffered=buffered.slice(newline+1),newline=buffered.indexOf(`
|
|
11
|
-
`);if(Buffer.byteLength(buffered)>maxEventBytes)throw new Error(`MCP SSE event exceeds ${maxEventBytes} bytes`)}buffered+=decoder.decode(),buffered&&processLine(buffered),dispatch()}finally{reader.releaseLock()}}var McpHttpError=class extends Error{status;body;constructor(status,message,body=""){super(message),this.name="McpHttpError",this.status=status,this.body=body}},McpAuthRequiredError=class extends McpHttpError{wwwAuthenticate;constructor(response,body=""){super(401,"MCP server requires authentication",body),this.name="McpAuthRequiredError",this.wwwAuthenticate=response.headers.get("www-authenticate")}},McpSessionExpiredError=class extends McpHttpError{constructor(body=""){super(404,"MCP session expired",body),this.name="McpSessionExpiredError"}};function contentType(response){return response.headers.get("content-type")?.split(";",1)[0]?.trim().toLowerCase()}function needsAuthorization(response){return response.status===401?!0:response.status!==403?!1:/(?:^|[\s,])error="?insufficient_scope"?/i.test(response.headers.get("www-authenticate")??"")}function isTransientStatus(status){return status===408||status===429||status>=500}function discard(response){return response.body?.cancel().catch(()=>{})??Promise.resolve()}function describeHttpFailure(status,body){let text=body.trim(),snippet=text.length>ERROR_MESSAGE_BODY_CHARS?`${text.slice(0,ERROR_MESSAGE_BODY_CHARS-3)}...`:text;return`MCP HTTP request failed with status ${status}${snippet?`: ${snippet}`:""}`}var StreamableHttpTransport=class extends TransportEvents{url;options;fetch;controller=new AbortController;started=!1;closed=!1;sessionIdValue;protocolVersion;getStreamStarted=!1;constructor(options){super(),this.options=Object.freeze({...options,headers:options.headers?{...options.headers}:void 0}),this.url=new URL(options.url);let fetch=options.fetch??globalThis.fetch;this.fetch=(input,init)=>fetch(input,init)}get sessionId(){return this.sessionIdValue}async start(){if(this.started)throw new Error("MCP Streamable HTTP transport already started");if(this.closed)throw new McpConnectionClosedError;this.started=!0}setProtocolVersion(version){this.protocolVersion=version}async send(message){if(!this.started||this.closed)throw new McpConnectionClosedError;let response=await this.authorizedFetch("POST",{headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(message)});if(await this.checkResponse(response),this.captureSession(response),!isJsonRpcRequest(message)){await discard(response),"method"in message&&message.method==="notifications/initialized"&&this.startGetStream();return}if(response.status===202||response.status===204)throw new McpHttpError(response.status,`MCP server accepted request ${message.method} without a response`);let type=contentType(response);if(type==="application/json"){let body=await response.json();for(let item of Array.isArray(body)?body:[body])this.emitMessage(parseJsonRpcMessage(item));return}if(type==="text/event-stream"&&response.body){this.consumeResponseStream(response.body,message.id);return}throw await discard(response),new McpHttpError(response.status,`Unsupported MCP response content type: ${type??"missing"}`)}async close(){if(!this.closed){if(this.closed=!0,this.controller.abort(),this.started&&this.sessionIdValue){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),1e3);try{let{headers}=await this.headers();await this.fetch(this.url,{method:"DELETE",headers,signal:controller.signal}).then(discard).catch(()=>{})}catch{}finally{clearTimeout(timeout)}}this.emitClose()}}async authorizedFetch(method,init){let onUnauthorized=this.options.authProvider?.onUnauthorized?.bind(this.options.authProvider);for(let attempt=0;;attempt++){let{headers,token}=await this.headers(init.headers),response=await this.fetch(this.url,{method,headers,body:init.body,signal:this.controller.signal});if(attempt>0||!onUnauthorized||!needsAuthorization(response))return response;try{await onUnauthorized({response,serverUrl:this.url,fetch:this.fetch,token})}finally{await discard(response)}}}async headers(extra={}){let headers=new Headers(this.options.headers);for(let[name,value]of Object.entries(extra))headers.set(name,value);this.sessionIdValue&&headers.set("Mcp-Session-Id",this.sessionIdValue),this.protocolVersion&&headers.set("MCP-Protocol-Version",this.protocolVersion);let token=await this.options.authProvider?.token();return token&&headers.set("Authorization",`Bearer ${token}`),{headers,...token?{token}:{}}}captureSession(response){let sessionId=response.headers.get("mcp-session-id");sessionId&&(this.sessionIdValue=sessionId)}async checkResponse(response){if(response.ok)return;let body=(await response.text().catch(()=>"")).slice(0,MAX_ERROR_BODY_BYTES);throw response.status===401?new McpAuthRequiredError(response,body):response.status===404&&this.sessionIdValue?new McpSessionExpiredError(body):new McpHttpError(response.status,describeHttpFailure(response.status,body),body)}async consumeSse(stream,cursor,onMessage){await consumeSseStream(stream,{maxEventBytes:this.options.maxMessageBytes??DEFAULT_MAX_MESSAGE_BYTES,onId:id=>{cursor.lastEventId=id},onRetry:delayMs=>{cursor.retryMs=delayMs},onEvent:event=>{if(cursor.received=!0,!event.data.trim()||event.event!==void 0&&event.event!=="message")return;let message;try{message=parseJsonRpcMessage(JSON.parse(event.data))}catch(error){this.emitError(error);return}onMessage?.(message),this.emitMessage(message)}})}async consumeResponseStream(body,requestId){let cursor={lastEventId:void 0,retryMs:void 0,received:!1},answered=!1,onMessage=message=>{isJsonRpcResponse(message)&&message.id===requestId&&(answered=!0)},stream=body,failure;for(let attempt=0;;){if(stream)try{await this.consumeSse(stream,cursor,onMessage),failure=void 0}catch(error){failure=error}if(answered||this.closed)return;if(failure!==void 0&&!this.isRetryable(failure)||cursor.lastEventId===void 0||attempt>=this.maxRetries())break;if(cursor.received&&(attempt=0),cursor.received=!1,!await this.sleep(this.reconnectDelay(attempt++,cursor.retryMs)))return;try{stream=await this.openSseStream(cursor.lastEventId)}catch(error){if(failure=error,!this.isRetryable(error))break;stream=void 0}}if(this.closed)return;let reason=failure===void 0?"stream ended without a response":toError(failure).message;this.emitMessage({jsonrpc:"2.0",id:requestId,error:{code:JSON_RPC_ERROR_CODES.internalError,message:`MCP response stream failed: ${reason}`}})}startGetStream(){this.options.openGetStream===!1||this.getStreamStarted||this.closed||(this.getStreamStarted=!0,this.runGetStream())}async runGetStream(){let cursor={lastEventId:void 0,retryMs:void 0,received:!1};for(let attempt=0;!this.closed;){try{let stream=await this.openSseStream(cursor.lastEventId);if(!stream)return;let openedAt=Date.now();await this.consumeSse(stream,cursor),(cursor.received||Date.now()-openedAt>this.maxDelay())&&(attempt=0)}catch(error){if(this.closed)return;if(!this.isRetryable(error)){this.emitError(error);return}}if(cursor.received=!1,attempt>=this.maxRetries()){this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));return}if(!await this.sleep(this.reconnectDelay(attempt++,cursor.retryMs)))return}}async openSseStream(lastEventId){let response=await this.authorizedFetch("GET",{headers:{accept:"text/event-stream",...lastEventId===void 0?{}:{"last-event-id":lastEventId}}});if(response.status===405){await discard(response);return}await this.checkResponse(response),this.captureSession(response);let type=contentType(response);if(type!=="text/event-stream"||!response.body)throw await discard(response),new McpHttpError(response.status,`Unsupported MCP GET response content type: ${type??"missing"}`);return response.body}isRetryable(error){if(error instanceof McpHttpError)return isTransientStatus(error.status);if(error instanceof TypeError)return!0;let code=error?.code;return typeof code=="string"&&(code.startsWith("E")||code.startsWith("UND_ERR"))}reconnectDelay(attempt,serverDelayMs){if(serverDelayMs!==void 0)return serverDelayMs;let initial=this.options.reconnect?.initialDelayMs??DEFAULT_RECONNECT_INITIAL_DELAY_MS;return Math.min(initial*2**attempt,this.maxDelay())}maxDelay(){return this.options.reconnect?.maxDelayMs??DEFAULT_RECONNECT_MAX_DELAY_MS}maxRetries(){return this.options.reconnect?.maxRetries??DEFAULT_RECONNECT_MAX_RETRIES}sleep(ms){let signal=this.controller.signal;return signal.aborted?Promise.resolve(!1):new Promise(resolve=>{let onAbort=()=>{clearTimeout(timer),resolve(!1)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve(!0)},ms);timer.unref?.(),signal.addEventListener("abort",onAbort,{once:!0})})}};function blockToLlmContent(block){switch(block.type){case"text":return{type:"text",text:block.text};case"image":return{type:"image",data:block.data,mimeType:block.mimeType};case"audio":return{type:"text",text:`[audio ${block.mimeType} omitted]`};case"resource_link":return{type:"text",text:`${block.name}: ${block.uri}`};case"resource":{let resource=block.resource;return"text"in resource?{type:"text",text:resource.text}:resource.mimeType?.startsWith("image/")?{type:"image",data:resource.blob,mimeType:resource.mimeType}:{type:"text",text:`[binary resource ${resource.uri} (${resource.mimeType??"unknown type"}) omitted]`}}default:return{type:"text",text:`[unsupported MCP content ${block.type}]`}}}function toLlmContent(result){let content=(result.content??[]).map(blockToLlmContent);return content.length===0&&result.structuredContent!==void 0&&content.push({type:"text",text:JSON.stringify(result.structuredContent,null,2)}),content}import{createHash,randomBytes}from"node:crypto";import{writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join2}from"node:path";function toToolExposure(exposure){return exposure==="codemode"?"deferred":exposure}var MAX_TOOL_NAME_LENGTH=64,MCP_OUTPUT_MAX_BYTES=20*1024,OUTPUT_PREVIEW_LINES=5,READ_MCP_RESOURCE_TOOL="read_mcp_resource";async function saveToTempFile(data,extension){let path=join2(tmpdir(),`pi-mcp-${randomBytes(8).toString("hex")}${extension}`);return await writeFile(path,data,{mode:384}),path}function createMcpToolName(server,tool,isTaken=()=>!1){let name=`mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g,"_");if(name.length<=MAX_TOOL_NAME_LENGTH&&!isTaken(name))return name;let hash=createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0,8);return`${name.slice(0,MAX_TOOL_NAME_LENGTH-hash.length-1)}_${hash}`}function textOf(content){return content.filter(block=>block.type==="text").map(block=>block.text).join(`
|
|
12
|
-
`)}function createMcpResultSchema(structuredContentSchema){return{type:"object",properties:{content:{type:"array",items:{type:"object"}},...structuredContentSchema?{structuredContent:structuredContentSchema}:{},isError:{type:"boolean"},_meta:{type:"object"}},required:["content"]}}async function limitMcpContent(content,saveOutput=saveToTempFile){let combined=textOf(content),truncation=truncateMiddle(combined,MCP_OUTPUT_MAX_BYTES);if(!truncation.truncated)return{content};let fullOutputPath,where;try{fullOutputPath=await saveOutput(combined,".txt"),where=`[Full output: ${fullOutputPath} (read it with offset/limit)]`}catch(error){where=`[Could not save the full output: ${error instanceof Error?error.message:String(error)}]`}return{content:[{type:"text",text:`Warning: truncated output (original token count: ${Math.ceil(truncation.totalBytes/4)})
|
|
13
|
-
Total output lines: ${truncation.totalLines}
|
|
14
|
-
|
|
15
|
-
${truncation.content}
|
|
16
|
-
|
|
17
|
-
${where}`},...content.filter(block=>block.type==="image")],...fullOutputPath?{fullOutputPath}:{}}}function extensionOf(uri){let path=URL.canParse(uri)?new URL(uri).pathname:uri;return/\.[A-Za-z0-9]{1,8}$/.exec(path)?.[0]??".bin"}function isTextMimeType(mimeType){if(!mimeType)return!1;let type=mimeType.split(";",1)[0].trim().toLowerCase();return type.startsWith("text/")||type==="application/json"||type.endsWith("+json")||type.endsWith("+xml")}async function blockToContent(server,block,options){if(block.type==="resource_link"){let details=[block.mimeType,block.size===void 0?void 0:formatSize(block.size)].filter(Boolean),read=options.readableResources?`. Read it with ${READ_MCP_RESOURCE_TOOL} (server "${server}")`:"",description=block.description?`: ${block.description}`:"";return[{type:"text",text:`[Resource ${block.uri} "${block.title??block.name}"${details.length>0?` (${details.join(", ")})`:""}${description}${read}]`}]}if(block.type==="resource"&&"blob"in block.resource&&!block.resource.mimeType?.startsWith("image/")){let{uri,mimeType,blob}=block.resource,data=Buffer.from(blob,"base64");if(isTextMimeType(mimeType))return[{type:"text",text:data.toString("utf8")}];let kind=`${mimeType??"unknown type"}, ${formatSize(data.length)}`;try{let path=await(options.saveOutput??saveToTempFile)(data,extensionOf(uri));return[{type:"text",text:`[Binary resource ${uri} (${kind}) saved to ${path}]`}]}catch(error){let reason=error instanceof Error?error.message:String(error);return[{type:"text",text:`[Binary resource ${uri} (${kind}) could not be saved: ${reason}]`}]}}return toLlmContent({content:[block]})}async function toModelContent(server,blocks,options={}){return(await Promise.all(blocks.map(block=>blockToContent(server,block,options)))).flat()}async function convertMcpResult(server,tool,result,options={}){let converted=result.content.length>0?await toModelContent(server,result.content,options):toLlmContent(result);result.isError&&textOf(converted)===""&&converted.push({type:"text",text:`MCP tool ${server}/${tool} returned an error`});let{content,fullOutputPath}=await limitMcpContent(converted,options.saveOutput),{_meta:_ignored,...scriptResult}=result;return{content,details:{server,tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:scriptResult,...result.isError?{isError:!0}:{}}}function toParameters(schema){return{...schema,type:schema.type??"object",...schema.properties===void 0?{properties:{}}:{}}}var ANNOTATION_HINTS=["readOnlyHint","destructiveHint","idempotentHint","openWorldHint"];function toToolAnnotations(tool){let annotations={};for(let hint of ANNOTATION_HINTS){let value=tool.annotations?.[hint];typeof value=="boolean"&&(annotations[hint]=value)}return Object.keys(annotations).length>0?annotations:void 0}function createMcpToolDefinition(options){let{server,tool}=options,title=tool.title??tool.annotations?.title,annotations=toToolAnnotations(tool),label=`${server}/${tool.name}`;return{name:options.name,label,description:tool.description?.trim()||title||`MCP tool ${tool.name} from server ${server}`,parameters:toParameters(tool.inputSchema),outputSchema:createMcpResultSchema(tool.outputSchema),exposure:toToolExposure(options.exposure),namespace:options.namespace,...annotations?{annotations}:{},...createMcpToolRenderers(label),async execute(_toolCallId,params,signal,onUpdate){let result=await(await options.getClient()).callTool(tool.name,params??{},{signal,timeoutMs:options.timeoutMs,onProgress:progress=>{let total=progress.total===void 0?"":`/${progress.total}`,text=progress.message??`Progress ${progress.progress}${total}`;onUpdate?.({content:[{type:"text",text}],details:{server,tool:tool.name}})}});return convertMcpResult(server,tool.name,result,{readableResources:options.readableResources?.()})}}}function createMcpToolRenderers(label){return{renderCall(args,theme,context){let component=context.lastComponent??new Text("",0,0);return component.setText(formatToolCallWithArgs(label,args,theme,context.expanded)),component},renderResult(result,options,theme,context){let component=context.lastComponent??new Container;component.clear();let output=getTextOutput(result,context.showImages).trim();if(!output)return component;let color=context.isError?"error":"toolOutput",styled=replaceTabs(output).split(`
|
|
18
|
-
`).map(line=>theme.fg(color,line)).join(`
|
|
19
|
-
`);if(component.addChild(new Spacer(1)),options.expanded)component.addChild(new Text(styled,0,0));else{component.addChild(new VisualLinePreview({text:styled,maxVisualLines:OUTPUT_PREVIEW_LINES,keep:"start",formatHint:hidden=>`${theme.fg("muted",`... (${hidden} more lines,`)} ${keyHint("app.tools.expand","to expand")}${theme.fg("muted",")")}`}));let fullOutputPath=result.details?.fullOutputPath;fullOutputPath&&component.addChild(new Text(theme.fg("muted",`Full output: ${fullOutputPath}`),0,0))}return component}}}var LIST_MCP_RESOURCES_TOOL="list_mcp_resources",LIST_MCP_RESOURCE_TEMPLATES_TOOL="list_mcp_resource_templates";function isMcpAppResource(item){return(item.uri??item.uriTemplate??"").startsWith("ui://")||/;\s*profile\s*=\s*"?mcp-app"?/i.test(item.mimeType??"")}function listed(server,item){let{_meta,icons:_icons,...rest}=item;return{server,...rest}}var stringProperty=description=>({type:"string",description}),SERVER_FILTER=stringProperty("MCP server name. Omit to list every server with resources."),CURSOR=stringProperty("Opaque cursor from a previous call with the same server; omit for the first page."),LIST_PARAMETERS={type:"object",properties:{server:SERVER_FILTER,cursor:CURSOR},additionalProperties:!1},READ_PARAMETERS={type:"object",properties:{server:stringProperty("MCP server name exactly as configured. Must match the 'server' field returned by list_mcp_resources."),uri:stringProperty("Resource URI to read. Must be one of the URIs returned by list_mcp_resources.")},required:["server","uri"],additionalProperties:!1},optionalString={type:"string"},LISTING_ERRORS={type:"array",description:"Servers that could not be listed",items:{type:"object",properties:{server:{type:"string"},error:{type:"string"}},required:["server","error"]}},LIST_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resources:{type:"array",items:{type:"object",properties:{server:{type:"string"},uri:{type:"string"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString,size:{type:"number"}},required:["server","uri","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resources"]},LIST_TEMPLATES_OUTPUT_SCHEMA={type:"object",properties:{server:optionalString,resourceTemplates:{type:"array",items:{type:"object",properties:{server:{type:"string"},uriTemplate:{type:"string",description:"RFC 6570 URI template"},name:{type:"string"},title:optionalString,description:optionalString,mimeType:optionalString},required:["server","uriTemplate","name"]}},nextCursor:optionalString,errors:LISTING_ERRORS},required:["resourceTemplates"]},READ_OUTPUT_SCHEMA={type:"object",properties:{server:{type:"string"},uri:{type:"string"},contents:{type:"array",items:{anyOf:[{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,text:{type:"string"}},required:["uri","text"]},{type:"object",properties:{uri:{type:"string"},mimeType:optionalString,blob:{type:"string",description:"base64"}},required:["uri","blob"]}]}}},required:["server","uri","contents"]};function stringArgument(params,key){let value=params?.[key];if(value!=null){if(typeof value!="string")throw new Error(`${key} must be a string`);return value.trim()||void 0}}function errorMessage(error){return error instanceof Error?error.message:String(error)}async function jsonResult(tool,server,payload){let{content,fullOutputPath}=await limitMcpContent([{type:"text",text:JSON.stringify(payload)}]);return{content,details:{server:server??"",tool,...fullOutputPath?{fullOutputPath}:{}},structuredContent:payload}}function createMcpResourceToolDefinitions(options){let readOnly={readOnlyHint:!0},findServer=name=>{let servers=options.servers(),server=servers.find(candidate=>candidate.name===name);if(server)return server;let available=servers.map(candidate=>candidate.name).join(", ");throw new Error(`MCP server "${name}" has no resources${available?`. Servers with resources: ${available}`:""}`)},list=async(params,signal,key,page,all)=>{let serverName=stringArgument(params,"server"),cursor=stringArgument(params,"cursor"),visible=item=>!isMcpAppResource(item);if(serverName){let server=findServer(serverName),result=await page(server,cursor,{signal,timeoutMs:server.timeoutMs});return{server:server.name,[key]:result.items.filter(visible).map(item=>listed(server.name,item)),...result.nextCursor===void 0?{}:{nextCursor:result.nextCursor}}}if(cursor)throw new Error("cursor can only be used when a server is specified");let servers=[...options.servers()].sort((a,b)=>a.name.localeCompare(b.name)),results=await Promise.allSettled(servers.map(server=>all(server,{signal,timeoutMs:server.timeoutMs}))),items=[],errors=[];return results.forEach((result,index)=>{let server=servers[index].name;result.status==="fulfilled"?items.push(...result.value.filter(visible).map(item=>listed(server,item))):errors.push({server,error:errorMessage(result.reason)})}),{[key]:items,...errors.length>0?{errors}:{}}},listResources={name:LIST_MCP_RESOURCES_TOOL,label:LIST_MCP_RESOURCES_TOOL,description:"Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resources",async(server,cursor,requestOptions)=>{let result=await server.resourcesPage(cursor,requestOptions);return{items:result.resources,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResources(requestOptions));return jsonResult(LIST_MCP_RESOURCES_TOOL,stringArgument(params,"server"),payload)}},listTemplates={name:LIST_MCP_RESOURCE_TEMPLATES_TOOL,label:LIST_MCP_RESOURCE_TEMPLATES_TOOL,description:"Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.",parameters:LIST_PARAMETERS,outputSchema:LIST_TEMPLATES_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let payload=await list(params,signal,"resourceTemplates",async(server,cursor,requestOptions)=>{let result=await server.resourceTemplatesPage(cursor,requestOptions);return{items:result.resourceTemplates,nextCursor:result.nextCursor}},(server,requestOptions)=>server.allResourceTemplates(requestOptions));return jsonResult(LIST_MCP_RESOURCE_TEMPLATES_TOOL,stringArgument(params,"server"),payload)}},readResource={name:READ_MCP_RESOURCE_TOOL,label:READ_MCP_RESOURCE_TOOL,description:"Read a specific resource from an MCP server given the server name and resource URI.",parameters:READ_PARAMETERS,outputSchema:READ_OUTPUT_SCHEMA,exposure:toToolExposure(options.exposure),annotations:readOnly,async execute(_toolCallId,params,signal){let serverName=stringArgument(params,"server"),uri=stringArgument(params,"uri");if(!serverName)throw new Error("server must be provided");if(!uri)throw new Error("uri must be provided");let server=findServer(serverName),result=await server.readResource(uri,{signal,timeoutMs:server.timeoutMs}),blocks=result.contents.flatMap(contents2=>[...result.contents.length>1?[{type:"text",text:`${contents2.uri}:`}]:[],{type:"resource",resource:contents2}]),converted=await toModelContent(server.name,blocks),{content,fullOutputPath}=await limitMcpContent(converted.length>0?converted:[{type:"text",text:`Resource ${uri} is empty.`}]),contents=result.contents.map(({_meta:_ignored,...rest})=>rest);return{content,details:{server:server.name,tool:READ_MCP_RESOURCE_TOOL,...fullOutputPath?{fullOutputPath}:{}},structuredContent:{server:server.name,uri,contents}}}};return[listResources,listTemplates,readResource]}export{operationSignal,raceWithAbortSignal,require_proper_lockfile,getConfigValueEnvVarNames,isCommandConfigValue,isConfigValueConfigured,resolveConfigValueOrThrow,resolveHeadersOrThrow,FileAuthStorageBackend,ReadOnlyAuthStorage,AuthStorage,readStoredCredential,mcpNamespace,getMcpToolExposure,validateMcpServerConfig,McpServerRegistry,DEFAULT_MAX_LINES,DEFAULT_MAX_BYTES,formatSize,truncateHead,truncateTail,truncateLine,JSON_RPC_ERROR_CODES,McpError,isObject,LATEST_PROTOCOL_VERSION,McpClient,StdioTransport,McpHttpError,McpAuthRequiredError,McpSessionExpiredError,StreamableHttpTransport,READ_MCP_RESOURCE_TOOL,createMcpToolName,createMcpToolDefinition,createMcpToolRenderers,LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,isMcpAppResource,createMcpResourceToolDefinitions};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{getProviderEnvValue}from"./chunk-DRQDKNXA.js";var __rewriteRelativeImportExtension=function(path,preserveJsx){return typeof path=="string"&&/^\.\.?\//.test(path)?path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(m,tsx,d,ext,cm){return tsx?preserveJsx?".jsx":".js":d&&(!ext||!cm)?m:d+ext+"."+cm.toLowerCase()+"js"}):path},_existsSync=null,_homedir=null,_join=null,dynamicImport=specifier=>import(__rewriteRelativeImportExtension(specifier)),NODE_FS_SPECIFIER="node:fs",NODE_OS_SPECIFIER="node:os",NODE_PATH_SPECIFIER="node:path";typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(dynamicImport(NODE_FS_SPECIFIER).then(m=>{_existsSync=m.existsSync}),dynamicImport(NODE_OS_SPECIFIER).then(m=>{_homedir=m.homedir}),dynamicImport(NODE_PATH_SPECIFIER).then(m=>{_join=m.join}));var ANTHROPIC_AUTH_TOKEN_ENV="ANTHROPIC_AUTH_TOKEN",ANTHROPIC_OAUTH_TOKEN_ENV="ANTHROPIC_OAUTH_TOKEN",ANTHROPIC_API_KEY_ENV="ANTHROPIC_API_KEY",ANTHROPIC_FEDERATION_RULE_ID_ENV="ANTHROPIC_FEDERATION_RULE_ID",ANTHROPIC_ORGANIZATION_ID_ENV="ANTHROPIC_ORGANIZATION_ID",ANTHROPIC_SERVICE_ACCOUNT_ID_ENV="ANTHROPIC_SERVICE_ACCOUNT_ID",ANTHROPIC_IDENTITY_TOKEN_FILE_ENV="ANTHROPIC_IDENTITY_TOKEN_FILE",ANTHROPIC_WORKSPACE_ID_ENV="ANTHROPIC_WORKSPACE_ID",cachedVertexAdcCredentialsExists=null;function hasVertexAdcCredentials(env){let explicitCredentialsPath=env?.GOOGLE_APPLICATION_CREDENTIALS;if(explicitCredentialsPath)return _existsSync?_existsSync(explicitCredentialsPath):!1;if(cachedVertexAdcCredentialsExists===null){if(!_existsSync||!_homedir||!_join)return typeof process<"u"&&(process.versions?.node||process.versions?.bun)||(cachedVertexAdcCredentialsExists=!1),!1;let gacPath=getProviderEnvValue("GOOGLE_APPLICATION_CREDENTIALS",env);gacPath?cachedVertexAdcCredentialsExists=_existsSync(gacPath):cachedVertexAdcCredentialsExists=_existsSync(_join(_homedir(),".config","gcloud","application_default_credentials.json"))}return cachedVertexAdcCredentialsExists}function getApiKeyEnvVars(provider){if(provider==="github-copilot")return["COPILOT_GITHUB_TOKEN"];if(provider==="anthropic")return[ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV];let envVar={"ant-ling":"ANT_LING_API_KEY","qwen-token-plan":"QWEN_TOKEN_PLAN_API_KEY","qwen-token-plan-cn":"QWEN_TOKEN_PLAN_CN_API_KEY","qwen-token-plan-individual":"QWEN_TOKEN_PLAN_API_KEY",openai:"OPENAI_API_KEY","azure-openai-responses":"AZURE_OPENAI_API_KEY",nvidia:"NVIDIA_API_KEY",deepseek:"DEEPSEEK_API_KEY",google:"GEMINI_API_KEY","google-vertex":"GOOGLE_CLOUD_API_KEY",groq:"GROQ_API_KEY",cerebras:"CEREBRAS_API_KEY",xai:"XAI_API_KEY",typesafe:"TYPESAFE_API_KEY",radius:"RADIUS_API_KEY",openrouter:"OPENROUTER_API_KEY","vercel-ai-gateway":"AI_GATEWAY_API_KEY",zai:"ZAI_API_KEY","zai-coding-cn":"ZAI_CODING_CN_API_KEY",mistral:"MISTRAL_API_KEY",minimax:"MINIMAX_API_KEY","minimax-cn":"MINIMAX_CN_API_KEY",moonshotai:"MOONSHOT_API_KEY","moonshotai-cn":"MOONSHOT_API_KEY",huggingface:"HF_TOKEN",fireworks:"FIREWORKS_API_KEY",together:"TOGETHER_API_KEY",baseten:"BASETEN_API_KEY",opencode:"OPENCODE_API_KEY","opencode-go":"OPENCODE_API_KEY","kimi-coding":"KIMI_API_KEY",meta:"META_API_KEY","cloudflare-workers-ai":"CLOUDFLARE_API_KEY","cloudflare-ai-gateway":"CLOUDFLARE_API_KEY",xiaomi:"XIAOMI_API_KEY","xiaomi-token-plan-cn":"XIAOMI_TOKEN_PLAN_CN_API_KEY","xiaomi-token-plan-ams":"XIAOMI_TOKEN_PLAN_AMS_API_KEY","xiaomi-token-plan-sgp":"XIAOMI_TOKEN_PLAN_SGP_API_KEY"}[provider];return envVar?[envVar]:void 0}function findEnvKeys(provider,env){let envVars=getApiKeyEnvVars(provider);if(!envVars)return;let found=envVars.filter(envVar=>!!getProviderEnvValue(envVar,env));return found.length>0?found:void 0}function getEnvApiKey(provider,env){let envKeys=findEnvKeys(provider,env);if(envKeys?.[0]){let apiKeyEnv=provider==="anthropic"?envKeys.find(key=>key!==ANTHROPIC_AUTH_TOKEN_ENV):envKeys[0];if(apiKeyEnv)return getProviderEnvValue(apiKeyEnv,env)}if(provider==="google-vertex"){let hasCredentials=hasVertexAdcCredentials(env),hasProject=!!(getProviderEnvValue("GOOGLE_CLOUD_PROJECT",env)||getProviderEnvValue("GCLOUD_PROJECT",env)),hasLocation=!!getProviderEnvValue("GOOGLE_CLOUD_LOCATION",env);if(hasCredentials&&hasProject&&hasLocation)return"<authenticated>"}if(provider==="amazon-bedrock"&&(getProviderEnvValue("AWS_PROFILE",env)||getProviderEnvValue("AWS_ACCESS_KEY_ID",env)&&getProviderEnvValue("AWS_SECRET_ACCESS_KEY",env)||getProviderEnvValue("AWS_BEARER_TOKEN_BEDROCK",env)||getProviderEnvValue("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",env)||getProviderEnvValue("AWS_CONTAINER_CREDENTIALS_FULL_URI",env)||getProviderEnvValue("AWS_WEB_IDENTITY_TOKEN_FILE",env)))return"<authenticated>"}export{ANTHROPIC_AUTH_TOKEN_ENV,ANTHROPIC_OAUTH_TOKEN_ENV,ANTHROPIC_API_KEY_ENV,ANTHROPIC_FEDERATION_RULE_ID_ENV,ANTHROPIC_ORGANIZATION_ID_ENV,ANTHROPIC_SERVICE_ACCOUNT_ID_ENV,ANTHROPIC_IDENTITY_TOKEN_FILE_ENV,ANTHROPIC_WORKSPACE_ID_ENV,findEnvKeys,getEnvApiKey};
|