@humain/humain-code 0.4.6 → 0.4.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/bun/sandbox-env-setup.js +8 -0
- package/dist/bun/sandbox-env-setup.js.map +1 -1
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
- package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
- package/dist/bundle/chunks/bedrock-converse-stream.js +35 -35
- package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
- package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
- package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
- package/dist/bundle/chunks/{chunk-FP2SXW5M.js → chunk-GNOKILVU.js} +472 -458
- package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
- package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
- package/dist/bundle/chunks/{chunk-UU4WS4BQ.js → chunk-ILRBME2Y.js} +611 -563
- package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
- package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
- package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBBBZ5HY.js → chunk-PYU5BR3Z.js} +3 -3
- package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
- package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
- package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
- package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
- package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
- package/dist/bundle/chunks/{compat-LJ4ZIVJZ.js → compat-J5FTRJ6S.js} +8 -8
- package/dist/bundle/chunks/{dist-UAQRGPZO.js → dist-6FQCCUSC.js} +308 -287
- package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
- package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
- package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
- package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
- package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
- package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
- package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
- package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
- package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
- package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-LWYOTTHQ.js → virtual-modules-TT2VTOSY.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +5 -5
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/core/tools/renderers/write.d.ts +2 -2
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +120 -15
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +30 -2
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +2 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +4 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/child-process.d.ts +8 -0
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +65 -4
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/windows-path.d.ts +9 -0
- package/dist/utils/windows-path.d.ts.map +1 -0
- package/dist/utils/windows-path.js +31 -0
- package/dist/utils/windows-path.js.map +1 -0
- package/docs/flow.md +2 -0
- package/docs/tui.md +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
|
@@ -1,27 +1,31 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
2
|
import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.js";var require_windows=__commonJS({"node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function checkPathExt(path,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat,path,options){return!stat.
|
|
3
3
|
isSymbolicLink()&&!stat.isFile()?!1:checkPathExt(path,options)}function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,path,options))})}function sync(path,options){return checkStat(fs.statSync(path),path,options)}}});var require_mode=__commonJS({"node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,options))})}function sync(path,options){return checkStat(fs.statSync(path),options)}function checkStat(stat,options){return stat.isFile()&&checkMode(stat,options)}function checkMode(stat,options){var mod=stat.mode,uid=stat.uid,gid=stat.gid,myUid=options.uid!==void 0?options.uid:
|
|
4
|
-
process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports,module){var fs=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(
|
|
5
|
-
|
|
6
|
-
"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((
|
|
7
|
-
getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;
|
|
4
|
+
process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"node_modules/isexe/index.js"(exports,module){var fs=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve3,reject){isexe(path,options||{},function(er,is){er?reject(er):
|
|
5
|
+
resolve3(is)})})}core(path,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path,options){try{return core.sync(path,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});var require_which=__commonJS({"node_modules/which/which.js"(exports,module){var isWindows=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",path=__require("path"),COLON=isWindows?";":":",isexe=require_isexe(),getNotFoundError=cmd=>Object.assign(new Error(`not found: ${cmd}`),{code:"ENOENT"}),getPathInfo=(cmd,opt)=>{let colon=opt.colon||COLON,pathEnv=cmd.match(/\//)||isWindows&&cmd.match(/\\/)?[""]:[...isWindows?[process.cwd()]:[],...(opt.path||process.env.PATH||
|
|
6
|
+
"").split(colon)],pathExtExe=isWindows?opt.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",pathExt=isWindows?pathExtExe.split(colon):[""];return isWindows&&cmd.indexOf(".")!==-1&&pathExt[0]!==""&&pathExt.unshift(""),{pathEnv,pathExt,pathExtExe}},which=(cmd,opt,cb)=>{typeof opt=="function"&&(cb=opt,opt={}),opt||(opt={});let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[],step=i=>new Promise((resolve3,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve3(found):reject(
|
|
7
|
+
getNotFoundError(cmd));let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;resolve3(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve3,reject)=>{if(ii===pathExt.length)return resolve3(step(i+1));let ext=pathExt[ii];isexe(p+ext,{pathExt:pathExtExe},(er,is)=>{if(!er&&is)if(opt.all)found.push(p+ext);else return resolve3(p+ext);return resolve3(subStep(p,i,ii+1))})});return cb?step(0).
|
|
8
8
|
then(res=>cb(null,res),cb):step(0)},whichSync=(cmd,opt)=>{opt=opt||{};let{pathEnv,pathExt,pathExtExe}=getPathInfo(cmd,opt),found=[];for(let i=0;i<pathEnv.length;i++){let ppRaw=pathEnv[i],pathPart=/^".*"$/.test(ppRaw)?ppRaw.slice(1,-1):ppRaw,pCmd=path.join(pathPart,cmd),p=!pathPart&&/^\.[\\\/]/.test(cmd)?cmd.slice(0,2)+pCmd:pCmd;for(let j=0;j<pathExt.length;j++){let cur=p+pathExt[j];try{if(isexe.sync(cur,{pathExt:pathExtExe}))if(opt.all)found.push(cur);else return cur}catch{}}}if(opt.all&&found.length)
|
|
9
9
|
return found;if(opt.nothrow)return null;throw getNotFoundError(cmd)};module.exports=which;which.sync=whichSync}});var require_path_key=__commonJS({"node_modules/path-key/index.js"(exports,module){"use strict";var pathKey=(options={})=>{let environment=options.env||process.env;return(options.platform||process.platform)!=="win32"?"PATH":Object.keys(environment).reverse().find(key=>key.toUpperCase()==="PATH")||"Path"};module.exports=pathKey;module.exports.default=pathKey}});var require_resolveCommand=__commonJS({"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports,module){"use strict";var path=__require("path"),which=require_which(),getPathKey=require_path_key();function resolveCommandAttempt(parsed,withoutPathExt){let env=parsed.options.env||process.env,cwd=process.cwd(),hasCustomCwd=parsed.options.cwd!=null,shouldSwitchCwd=hasCustomCwd&&process.chdir!==void 0&&!process.chdir.disabled;if(shouldSwitchCwd)try{process.chdir(parsed.options.cwd)}catch{}let resolved;
|
|
10
|
-
try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function
|
|
11
|
-
$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string="")=>{let match=string.match(shebangRegex);if(!match)return null;let[path,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs=__require("fs"),shebangCommand=require_shebang_command();function
|
|
12
|
-
parsed.file),parsed.command=shebang,
|
|
13
|
-
parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=
|
|
10
|
+
try{resolved=which.sync(parsed.command,{path:env[getPathKey({env})],pathExt:withoutPathExt?path.delimiter:void 0})}catch{}finally{shouldSwitchCwd&&process.chdir(cwd)}return resolved&&(resolved=path.resolve(hasCustomCwd?parsed.options.cwd:"",resolved)),resolved}function resolveCommand2(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand2}});var require_escape=__commonJS({"node_modules/cross-spawn/lib/util/escape.js"(exports,module){"use strict";var metaCharsRegExp=/([()\][%!^"`<>&|;, *?])/g;function escapeCommand(arg){return arg=arg.replace(metaCharsRegExp,"^$1"),arg}function escapeArgument(arg,doubleEscapeMetaChars){return arg=`${arg}`,arg=arg.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),arg=arg.replace(/(?=(\\+?)?)\1$/,"$1$1"),arg=`"${arg}"`,arg=arg.replace(metaCharsRegExp,"^$1"),doubleEscapeMetaChars&&(arg=arg.replace(metaCharsRegExp,"^\
|
|
11
|
+
$1")),arg}module.exports.command=escapeCommand;module.exports.argument=escapeArgument}});var require_shebang_regex=__commonJS({"node_modules/shebang-regex/index.js"(exports,module){"use strict";module.exports=/^#!(.*)/}});var require_shebang_command=__commonJS({"node_modules/shebang-command/index.js"(exports,module){"use strict";var shebangRegex=require_shebang_regex();module.exports=(string="")=>{let match=string.match(shebangRegex);if(!match)return null;let[path,argument]=match[0].replace(/#! ?/,"").split(" "),binary=path.split("/").pop();return binary==="env"?argument:argument?`${binary} ${argument}`:binary}}});var require_readShebang=__commonJS({"node_modules/cross-spawn/lib/util/readShebang.js"(exports,module){"use strict";var fs=__require("fs"),shebangCommand=require_shebang_command();function readShebang2(command){let buffer=Buffer.alloc(150),fd;try{fd=fs.openSync(command,"r"),fs.readSync(fd,buffer,0,150,0),fs.closeSync(fd)}catch{}return shebangCommand(buffer.toString())}module.exports=readShebang2}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path=__require("path"),resolveCommand2=require_resolveCommand(),escape=require_escape(),readShebang2=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand2(parsed);let shebang=parsed.file&&readShebang2(parsed.file);return shebang?(parsed.args.
|
|
12
|
+
unshift(parsed.file),parsed.command=shebang,resolveCommand2(parsed)):parsed.file}function parseNonShell(parsed){if(!isWin)return parsed;let commandFile=detectShebang(parsed),needsShell=!isExecutableRegExp.test(commandFile);if(parsed.options.forceShell||needsShell){let needsDoubleEscapeMetaChars=isCmdShimRegExp.test(commandFile);parsed.command=path.normalize(parsed.command),parsed.command=escape.command(parsed.command),parsed.args=parsed.args.map(arg=>escape.argument(arg,needsDoubleEscapeMetaChars));
|
|
13
|
+
let shellCommand=[parsed.command].concat(parsed.args).join(" ");parsed.args=["/d","/s","/c",`"${shellCommand}"`],parsed.command=process.env.comspec||"cmd.exe",parsed.options.windowsVerbatimArguments=!0}return parsed}function parse(command,args,options){args&&!Array.isArray(args)&&(options=args,args=null),args=args?args.slice(0):[],options=Object.assign({},options);let parsed={command,args,options,file:void 0,original:{command,args}};return options.shell?parsed:parseNonShell(parsed)}module.exports=
|
|
14
|
+
parse}});var require_enoent=__commonJS({"node_modules/cross-spawn/lib/enoent.js"(exports,module){"use strict";var isWin=process.platform==="win32";function notFoundError(original,syscall){return Object.assign(new Error(`${syscall} ${original.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${syscall} ${original.command}`,path:original.command,spawnargs:original.args})}function hookChildProcess(cp,parsed){if(!isWin)return;let originalEmit=cp.emit;cp.emit=function(name,arg1){if(name==="exit"){let err=verifyENOENT(
|
|
14
15
|
arg1,parsed);if(err)return originalEmit.call(cp,"error",err)}return originalEmit.apply(cp,arguments)}}function verifyENOENT(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawn"):null}function verifyENOENTSync(status,parsed){return isWin&&status===1&&!parsed.file?notFoundError(parsed.original,"spawnSync"):null}module.exports={hookChildProcess,verifyENOENT,verifyENOENTSync,notFoundError}}});var require_cross_spawn=__commonJS({"node_modules/cross-spawn/index.js"(exports,module){"use strict";var cp=__require("child_process"),parse=require_parse(),enoent=require_enoent();function spawn(command,args,options){let parsed=parse(command,args,options),spawned=cp.spawn(parsed.command,parsed.args,parsed.options);return enoent.hookChildProcess(spawned,parsed),spawned}function spawnSync(command,args,options){let parsed=parse(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.
|
|
15
|
-
options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse;module.exports._enoent=enoent}});import{accessSync,constants,existsSync,readFileSync,realpathSync as realpathSync2}from"fs";import{createRequire}from"module";import{homedir as homedir2}from"os";import{basename,dirname,join as
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn;module.exports.spawn=spawn;module.exports.sync=spawnSync;module.exports._parse=parse;module.exports._enoent=enoent}});import{accessSync,constants,existsSync,readFileSync,realpathSync as realpathSync2}from"fs";import{createRequire}from"module";import{homedir as homedir2}from"os";import{basename,dirname,join as join3,resolve as resolve2,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath3}from"url";var import_cross_spawn=__toESM(require_cross_spawn(),1),import_readShebang=__toESM(require_readShebang(),1),import_resolveCommand=__toESM(require_resolveCommand(),1);import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import{isAbsolute,join,resolve}from"node:path";import{fileURLToPath}from"node:url";import{lstatSync,statSync}from"node:fs";import{delimiter}from"node:path";function windowsPathDirectories(path){return path.split(delimiter).map(dir=>dir.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean)}function isProgramFile(file){try{let stats=statSync(file,{throwIfNoEntry:!1});if(stats)return stats.isFile()}catch{}try{let link=lstatSync(file,{throwIfNoEntry:!1});return link!==void 0&&!link.isDirectory()}catch{return!1}}var EXIT_STDIO_GRACE_MS=100;function spawnProcess(command,args,options){if(process.platform!=="win32")return nodeSpawn(command,args,options);let invocation=resolveWindowsInvocation(command,args,options);return(0,import_cross_spawn.default)(invocation.command,invocation.args,options)}function spawnProcessSync(command,args,options){if(process.platform!=="win32")return nodeSpawnSync(command,args,options);let invocation=resolveWindowsInvocation(command,args,options);return import_cross_spawn.default.
|
|
17
|
+
sync(invocation.command,invocation.args,options)}function resolveWindowsInvocation(command,args,options){let file=resolveWindowsCommand(command,options.env);if(options.shell)return{command:file,args};let cwd=typeof options.cwd=="object"?fileURLToPath(options.cwd):options.cwd,visited=new Set;for(;;){file=resolve(cwd??"",file);let script=(0,import_resolveCommand.default)({command:file,options:{env:options.env}})??file,key=script.toLowerCase();if(visited.has(key)||visited.size===32)return{command:resolveWindowsCommand(
|
|
18
|
+
"shebang-chain",{PATH:""}),args};visited.add(key);let interpreter=(0,import_readShebang.default)(script);if(!interpreter)return{command:script,args};file=resolveWindowsCommand(interpreter,options.env),args=[script,...args]}}function resolveWindowsCommand(command,env){if(/[\\/]/.test(command))return command;let source=env??process.env,pathKey="PATH"in source?"PATH":Object.keys(source).find(key=>key.toLowerCase()==="path"),dirs=windowsPathDirectories(pathKey?source[pathKey]??"":"").filter(dir=>isAbsolute(
|
|
19
|
+
dir)),pathExtensions=(source.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean),extensions=command.includes(".")?["",...pathExtensions]:pathExtensions;for(let dir of dirs)for(let extension of extensions){let file=join(dir,command+extension);if(isProgramFile(file))return file}return join(process.env.SystemRoot??"C:\\Windows","humain-code-no-such-command",`${command}.exe`)}function waitForChildProcess(child,drainSignal){return new Promise((resolve3,reject)=>{let settled=!1,exited=!1,exitCode=null,
|
|
20
|
+
postExitTimer,stdoutEnded=child.stdout===null,stderrEnded=child.stderr===null,cleanup=()=>{drainSignal?.removeEventListener("abort",onDrainAbort),postExitTimer&&(clearTimeout(postExitTimer),postExitTimer=void 0),child.removeListener("error",onError),child.removeListener("exit",onExit),child.removeListener("close",onClose),child.stdout?.removeListener("end",onStdoutEnd),child.stderr?.removeListener("end",onStderrEnd),child.stdout?.removeListener("data",onData),child.stderr?.removeListener("data",
|
|
21
|
+
onData)},finalize=code=>{settled||(settled=!0,cleanup(),child.stdout?.destroy(),child.stderr?.destroy(),resolve3(code))},onDrainAbort=()=>finalize(child.exitCode),maybeFinalizeAfterExit=()=>{!exited||settled||stdoutEnded&&stderrEnded&&finalize(exitCode)},armIdleTimer=()=>{postExitTimer&&clearTimeout(postExitTimer),postExitTimer=setTimeout(()=>finalize(exitCode),EXIT_STDIO_GRACE_MS)},onData=()=>{exited&&!settled&&armIdleTimer()},onStdoutEnd=()=>{stdoutEnded=!0,maybeFinalizeAfterExit()},onStderrEnd=()=>{
|
|
22
|
+
stderrEnded=!0,maybeFinalizeAfterExit()},onError=err=>{settled||(settled=!0,cleanup(),reject(err))},onExit=code=>{exited=!0,exitCode=code,maybeFinalizeAfterExit(),settled||armIdleTimer()},onClose=code=>{finalize(code)};child.stdout?.once("end",onStdoutEnd),child.stderr?.once("end",onStderrEnd),child.stdout?.on("data",onData),child.stderr?.on("data",onData),child.once("error",onError),child.once("exit",onExit),child.once("close",onClose),drainSignal?.addEventListener("abort",onDrainAbort,{once:!0}),
|
|
23
|
+
drainSignal?.aborted&&onDrainAbort()})}import{realpathSync,statSync as statSync2}from"node:fs";import{homedir}from"node:os";import{isAbsolute as isAbsolute2,join as join2,resolve as nodeResolvePath,relative,sep}from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";var UNICODE_SPACES=/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;function canonicalizePath(path){try{return realpathSync(path)}catch{return path}}function getFileRevision(path){try{let stats=statSync2(path,{bigint:!0});return`${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`}catch{return}}function isLocalPath(value){let trimmed=value.trim();return!(trimmed.startsWith("npm:")||trimmed.startsWith("git:")||trimmed.startsWith("github:")||trimmed.startsWith("http:")||trimmed.startsWith(
|
|
20
24
|
"https:")||trimmed.startsWith("ssh:")||trimmed.startsWith("builtin:"))}function normalizeWindowsShellPath(filePath){if(!filePath.startsWith("/")||filePath.startsWith("//")||filePath.includes("\\"))return filePath;let match=filePath.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(!match)return filePath;let suffix=match[2]?.replaceAll("/","\\");return`${match[1].toUpperCase()}:\\${suffix??""}`}function normalizePath(input,options={}){let normalized=options.trim?input.trim():input;if(options.
|
|
21
|
-
normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return
|
|
22
|
-
normalized):normalized}function resolvePath(input,baseDir=process.cwd(),options={}){let normalized=normalizePath(input,options),normalizedBaseDir=normalizePath(baseDir);return
|
|
23
|
-
startsWith(`..${sep}`)&&!
|
|
24
|
-
spawnProcessSync("xattr",["-w",attr,"1",path],{encoding:"utf-8",stdio:"ignore"}):spawnProcessSync("setfattr",["-n",attr,"-v","1",path],{encoding:"utf-8",stdio:"ignore"})}function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}var __filename=
|
|
25
|
+
normalizeUnicodeSpaces&&(normalized=normalized.replace(UNICODE_SPACES," ")),options.stripAtPrefix&&normalized.startsWith("@")&&(normalized=normalized.slice(1)),process.platform==="win32"&&(normalized=normalizeWindowsShellPath(normalized)),options.expandTilde??!0){let home=options.homeDir??homedir();if(normalized==="~")return home;if(normalized.startsWith("~/")||process.platform==="win32"&&normalized.startsWith("~\\"))return join2(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath2(
|
|
26
|
+
normalized):normalized}function resolvePath(input,baseDir=process.cwd(),options={}){let normalized=normalizePath(input,options),normalizedBaseDir=normalizePath(baseDir);return isAbsolute2(normalized)?nodeResolvePath(normalized):nodeResolvePath(normalizedBaseDir,normalized)}function getCwdRelativePath(filePath,cwd){let resolvedCwd=resolvePath(cwd),resolvedPath=resolvePath(filePath,resolvedCwd),relativePath=relative(resolvedCwd,resolvedPath);return relativePath===""||relativePath!==".."&&!relativePath.
|
|
27
|
+
startsWith(`..${sep}`)&&!isAbsolute2(relativePath)?relativePath||".":void 0}function formatPathRelativeToCwdOrAbsolute(filePath,cwd){let absolutePath=resolvePath(filePath,cwd);return(getCwdRelativePath(absolutePath,cwd)??absolutePath).split(sep).join("/")}function markPathIgnoredByCloudSync(path){let attrs=process.platform==="darwin"?["com.dropbox.ignored","com.apple.fileprovider.ignore#P"]:process.platform==="linux"?["user.com.dropbox.ignored"]:[];for(let attr of attrs)process.platform==="darwi\
|
|
28
|
+
n"?spawnProcessSync("xattr",["-w",attr,"1",path],{encoding:"utf-8",stdio:"ignore"}):spawnProcessSync("setfattr",["-n",attr,"-v","1",path],{encoding:"utf-8",stdio:"ignore"})}function splitBom(content){return content.startsWith("\uFEFF")?{bom:"\uFEFF",text:content.slice(1)}:{bom:"",text:content}}function stripBom(content){return splitBom(content).text}var __filename=fileURLToPath3(import.meta.url),__dirname=dirname(__filename),BOOTSTRAP_ENV_PACKAGE_DIR="HUMAIN_TERMINAL_PACKAGE_DIR",isBunBinary=import.meta.url.includes("$bunfs")||import.meta.url.includes("~BUN")||import.meta.url.includes("%7EBUN"),isBunRuntime=!!process.versions.bun,isBundledNode=!0;function normalizeSelfUpdatePackageTarget(target){return typeof target=="string"?{packageName:target,installSpec:target}:{packageName:target.packageName,installSpec:target.installSpec??target.packageName}}
|
|
25
29
|
function makeSelfUpdateCommand(installStep,uninstallStep){return uninstallStep?{...installStep,display:`${uninstallStep.display} && ${installStep.display}`,steps:[uninstallStep,installStep]}:installStep}function makeSelfUpdateCommandStep(command,args){return{command,args,display:[command,...args].map(arg=>/\s/.test(arg)?`"${arg}"`:arg).join(" ")}}function detectInstallMethod(){if(isBunBinary)return"bun-binary";let resolvedPath=`${__dirname}\0${process.execPath||""}`.toLowerCase().replace(/\\/g,"\
|
|
26
30
|
/");return resolvedPath.includes("/pnpm/")||resolvedPath.includes("/.pnpm/")?"pnpm":resolvedPath.includes("/yarn/")||resolvedPath.includes("/.yarn/")?"yarn":isBunRuntime||resolvedPath.includes("/install/global/node_modules/")?"bun":resolvedPath.includes("/npm/")||resolvedPath.includes("/node_modules/")?"npm":"unknown"}function getInferredNpmInstall(){let packageDir=getPackageDir(),path=process.platform==="win32"||packageDir.includes("\\")?win32:{basename,dirname},parent=path.dirname(packageDir),
|
|
27
31
|
root;if(path.basename(parent).startsWith("@")&&path.basename(path.dirname(parent))==="node_modules"?root=path.dirname(parent):path.basename(parent)==="node_modules"&&(root=parent),!root)return;let rootParent=path.dirname(root);if(path.basename(rootParent)==="lib")return{root,prefix:path.dirname(rootParent)}}function getSelfUpdateCommandForMethod(method,installedPackageName,updatePackageTarget=installedPackageName,npmCommand){let target=normalizeSelfUpdatePackageTarget(updatePackageTarget);switch(method){case"\
|
|
@@ -29,24 +33,24 @@ bun-binary":return;case"pnpm":{let match=readCommandOutput("pnpm",["root","-g"])
|
|
|
29
33
|
m",["remove","-g",...binDirArgs,installedPackageName]))}case"yarn":return makeSelfUpdateCommand(makeSelfUpdateCommandStep("yarn",["global","add","--ignore-scripts",target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("yarn",["global","remove",installedPackageName]));case"bun":return makeSelfUpdateCommand(makeSelfUpdateCommandStep("bun",["install","-g","--ignore-scripts","--minimum-release-age=0",target.installSpec]),target.packageName===installedPackageName?
|
|
30
34
|
void 0:makeSelfUpdateCommandStep("bun",["uninstall","-g",installedPackageName]));case"npm":{let[command="npm",...npmArgs]=npmCommand??[],inferred=npmCommand?.length?void 0:getInferredNpmInstall(),prefixArgs=[...npmArgs,...inferred?["--prefix",inferred.prefix]:[]],installStep=makeSelfUpdateCommandStep(command,[...prefixArgs,"install","-g","--ignore-scripts","--min-release-age=0",target.installSpec]),uninstallStep=target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep(command,[
|
|
31
35
|
...prefixArgs,"uninstall","-g",installedPackageName]);return makeSelfUpdateCommand(installStep,uninstallStep)}case"unknown":return}}function readCommandOutput(command,args,options={}){let result=spawnProcessSync(command,args,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]});if(result.status===0)return result.stdout.trim()||void 0;if(options.requireSuccess){let reason=result.error?.message||result.stderr.trim()||`exit code ${result.status??"unknown"}`;throw new Error(`Failed to run ${[command,...args].
|
|
32
|
-
join(" ")}: ${reason}`)}}function getGlobalPackageRoots(method,_packageName,npmCommand){switch(method){case"npm":{let configured=!!npmCommand?.length,[command="npm",...npmArgs]=npmCommand??[];if(configured&&command==="bun"){let bunBin=readCommandOutput(command,[...npmArgs,"pm","bin","-g"],{requireSuccess:!0}),roots=[
|
|
33
|
-
[...npmArgs,"root","-g"],{requireSuccess:configured}),inferred=configured?void 0:getInferredNpmInstall();return[root,inferred?.root].filter(x=>!!x)}case"pnpm":{let root=readCommandOutput("pnpm",["root","-g"]);if(root)return[root,dirname(root)];let match=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getPackageDir());return match?[match[1]]:[]}case"yarn":{let dir=readCommandOutput("yarn",["global","dir"]);return dir?[dir,
|
|
34
|
-
bun",["pm","bin","-g"]),roots=[
|
|
35
|
-
(normalizedPath=normalizedPath.toLowerCase()),normalizedPath}function getPathComparisonCandidates(path){return Array.from(new Set([normalizeExistingPathForComparison(path,!1),normalizeExistingPathForComparison(path,!0)].filter(candidate=>!!candidate)))}function getEntrypointPackageDir(){let entrypoint=process.argv[1];if(!entrypoint)return;let dir=dirname(entrypoint);for(;dir!==dirname(dir);){if(existsSync(
|
|
36
|
+
join(" ")}: ${reason}`)}}function getGlobalPackageRoots(method,_packageName,npmCommand){switch(method){case"npm":{let configured=!!npmCommand?.length,[command="npm",...npmArgs]=npmCommand??[];if(configured&&command==="bun"){let bunBin=readCommandOutput(command,[...npmArgs,"pm","bin","-g"],{requireSuccess:!0}),roots=[join3(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join3(dirname(bunBin),"install","global","node_modules")),roots}let root=readCommandOutput(command,
|
|
37
|
+
[...npmArgs,"root","-g"],{requireSuccess:configured}),inferred=configured?void 0:getInferredNpmInstall();return[root,inferred?.root].filter(x=>!!x)}case"pnpm":{let root=readCommandOutput("pnpm",["root","-g"]);if(root)return[root,dirname(root)];let match=/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getPackageDir());return match?[match[1]]:[]}case"yarn":{let dir=readCommandOutput("yarn",["global","dir"]);return dir?[dir,join3(dir,"node_modules")]:[]}case"bun":{let bunBin=readCommandOutput("\
|
|
38
|
+
bun",["pm","bin","-g"]),roots=[join3(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join3(dirname(bunBin),"install","global","node_modules")),roots}case"bun-binary":case"unknown":return[]}}function normalizeExistingPathForComparison(path,resolveSymlinks){let resolvedPath=resolve2(path);if(!existsSync(resolvedPath))return;let normalizedPath=resolvedPath;if(resolveSymlinks)try{normalizedPath=realpathSync2(resolvedPath)}catch{return}return process.platform==="win32"&&
|
|
39
|
+
(normalizedPath=normalizedPath.toLowerCase()),normalizedPath}function getPathComparisonCandidates(path){return Array.from(new Set([normalizeExistingPathForComparison(path,!1),normalizeExistingPathForComparison(path,!0)].filter(candidate=>!!candidate)))}function getEntrypointPackageDir(){let entrypoint=process.argv[1];if(!entrypoint)return;let dir=dirname(entrypoint);for(;dir!==dirname(dir);){if(existsSync(join3(dir,"package.json")))return dir;dir=dirname(dir)}}function isSelfUpdatePathWritable(){
|
|
36
40
|
let packageDir=getPackageDir();try{return accessSync(packageDir,constants.W_OK),accessSync(dirname(packageDir),constants.W_OK),!0}catch{return!1}}function isManagedByGlobalPackageManager(method,packageName,npmCommand){let packageDirCandidates=[getPackageDir(),getEntrypointPackageDir()].filter(dir=>!!dir).flatMap(dir=>getPathComparisonCandidates(dir));return getGlobalPackageRoots(method,packageName,npmCommand).some(root=>getPathComparisonCandidates(root).some(normalizedRoot=>{let rootPrefix=normalizedRoot.
|
|
37
41
|
endsWith(sep2)?normalizedRoot:`${normalizedRoot}${sep2}`;return packageDirCandidates.some(packageDir=>packageDir.startsWith(rootPrefix))}))}function getSelfUpdateCommand(packageName,npmCommand,updatePackageTarget=packageName){let method=detectInstallMethod(),command=getSelfUpdateCommandForMethod(method,packageName,updatePackageTarget,npmCommand);if(!(!command||!isManagedByGlobalPackageManager(method,packageName,npmCommand)||!isSelfUpdatePathWritable()))return command}function getSelfUpdateUnavailableInstruction(packageName,npmCommand,updatePackageTarget=packageName){
|
|
38
42
|
let method=detectInstallMethod(),target=normalizeSelfUpdatePackageTarget(updatePackageTarget);if(method==="bun-binary")return`Download from: ${getBinaryReleaseUrl()}`;let command=getSelfUpdateCommandForMethod(method,packageName,target,npmCommand);return command?isManagedByGlobalPackageManager(method,packageName,npmCommand)&&!isSelfUpdatePathWritable()?`This installation is managed by a global ${method} install, but the install path is not writable. Update it yourself with: ${command.display}`:`T\
|
|
39
|
-
his installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname(dir);){if(existsSync(
|
|
40
|
-
"theme");let packageDir=getPackageDir(),distThemes=
|
|
41
|
-
getPackageDir(),"package.json")}function getReadmePath(){return
|
|
42
|
-
"src":"dist";return
|
|
43
|
-
|
|
43
|
+
his installation is not managed by a global ${method} install. Update it with the package manager, wrapper, or source checkout that provides it.`:`Update ${target.installSpec} using the package manager, wrapper, or source checkout that provides this installation.`}function findNodePackageDir(startDir){let dir=startDir;for(;dir!==dirname(dir);){if(existsSync(join3(dir,"package.json"))){let parent=dirname(dir);return basename(dir)==="dist"&&existsSync(join3(parent,"package.json"))?parent:dir}dir=dirname(dir)}return startDir}function getPackageDir(){let envDir=process.env[BOOTSTRAP_ENV_PACKAGE_DIR];return envDir?normalizePath(envDir):isBunBinary?dirname(process.execPath):findNodePackageDir(__dirname)}function getThemesDir(){if(isBunBinary)return join3(getPackageDir(),
|
|
44
|
+
"theme");let packageDir=getPackageDir(),distThemes=join3(packageDir,"dist","modes","interactive","theme");return existsSync(join3(distThemes,"dark.json"))?distThemes:join3(packageDir,"src","modes","interactive","theme")}function getExportTemplateDir(){if(isBunBinary)return join3(getPackageDir(),"export-html");let packageDir=getPackageDir(),srcOrDist=existsSync(join3(packageDir,"src"))?"src":"dist";return join3(packageDir,srcOrDist,"core","export-html")}function getPackageJsonPath(){return join3(
|
|
45
|
+
getPackageDir(),"package.json")}function getReadmePath(){return resolve2(join3(getPackageDir(),"README.md"))}function getDocsPath(){return resolve2(join3(getPackageDir(),"docs"))}function getExamplesPath(){return resolve2(join3(getPackageDir(),"examples"))}function getChangelogPath(){return resolve2(join3(getPackageDir(),"CHANGELOG.md"))}function getInteractiveAssetsDir(){if(isBunBinary)return join3(getPackageDir(),"assets");let packageDir=getPackageDir(),srcOrDist=existsSync(join3(packageDir,"s\
|
|
46
|
+
rc"))?"src":"dist";return join3(packageDir,srcOrDist,"modes","interactive","assets")}function getBundledInteractiveAssetPath(name){return join3(getInteractiveAssetsDir(),name)}function getHumainModuleAssetsDir(moduleName){return isBunBinary?join3(getPackageDir(),"humain-modules",moduleName):join3(getPackageDir(),"src","humain",moduleName,"vendor")}function getBundledFlowPackageDir(){if(isBunBinary)return resolve2(getPackageDir(),"flow");if(isBundledNode)return resolve2(getPackageDir(),"dist","bu\
|
|
47
|
+
ndle","flow")}function getBundledFlowProfilesDir(){let packageDir=getBundledFlowPackageDir();return packageDir===void 0?void 0:join3(packageDir,"assets","profiles")}var quickJSWasmPath;function getQuickJSWasmPath(){return quickJSWasmPath??=createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm"),quickJSWasmPath}function resolveCodemodeWorkerSpecifier(runtime,moduleUrl){if(runtime==="bun-binary")return"./extensions/codemode/worker.ts";if(runtime==="bundled-node")return new URL("./codemode-worker.js",moduleUrl)}var codemodeWorkerDataUrl;function getCodemodeWorkerSpecifier(){let runtime=isBunBinary?"bun-binary":isBundledNode?"bundled-node":"unbundled",specifier=resolveCodemodeWorkerSpecifier(
|
|
44
48
|
runtime,import.meta.url);return runtime!=="bundled-node"||!(specifier instanceof URL)?specifier:(codemodeWorkerDataUrl??=new URL(`data:text/javascript;base64,${readFileSync(specifier).toString("base64")}`),codemodeWorkerDataUrl)}function detectInstallChange(packageJsonPath=startupPackageJsonPath){if(isBunBinary||!packageJsonPath)return;let installed;try{installed=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8")))}catch(error){return error.code==="ENOENT"?{kind:"removed"}:void 0}return installed.
|
|
45
49
|
version&&installed.version!==VERSION?{kind:"updated",version:installed.version}:void 0}var pkg={},startupPackageJsonPath;try{let packageJsonPath=getPackageJsonPath();pkg=JSON.parse(stripBom(readFileSync(packageJsonPath,"utf-8"))),startupPackageJsonPath=packageJsonPath}catch(e){if(e.code!=="ENOENT")throw e}var appConfig=pkg.humainTerminalConfig??pkg.piConfig,appConfigName=appConfig?.name,appConfigTitle=appConfig?.title,appConfigEnvPrefix=appConfig?.envPrefix;function sanitizeEnvPrefix(value){return value.
|
|
46
50
|
trim().replace(/[^a-zA-Z0-9]+/g,"_").replace(/^_+|_+$/g,"").toUpperCase()}var PACKAGE_NAME=pkg.name||"@humain/humain-code",APP_NAME=appConfigName||"pi",APP_TITLE=appConfigTitle||(appConfigName?APP_NAME:"\u03C0"),APP_COMMAND=APP_NAME==="humain-terminal"?"humain-code":APP_NAME,CONFIG_DIR_NAME=appConfig?.configDir||".pi",FIRST_TIME_SETUP_ENABLED=appConfig?.firstTimeSetup??!1,VERSION=pkg.version||"0.0.0",UPSTREAM_PI_VERSION=appConfig?.upstreamPiVersion||"0.0.0",ENV_PREFIX=sanitizeEnvPrefix(appConfigEnvPrefix||
|
|
47
51
|
APP_NAME),ENV_AGENT_DIR=`${ENV_PREFIX}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${ENV_PREFIX}_CODING_AGENT_SESSION_DIR`,ENV_SESSION_ID=`${ENV_PREFIX}_SESSION_ID`,ENV_SESSION_FILE=`${ENV_PREFIX}_SESSION_FILE`,ENV_PROVIDER=`${ENV_PREFIX}_PROVIDER`,ENV_MODEL=`${ENV_PREFIX}_MODEL`,ENV_MCP_CLIENT_METADATA_URL=`${ENV_PREFIX}_MCP_CLIENT_METADATA_URL`,ENV_REASONING_LEVEL=`${ENV_PREFIX}_REASONING_LEVEL`,ENV_OFFLINE=`${ENV_PREFIX}_OFFLINE`,ENV_PACKAGE_DIR=`${ENV_PREFIX}_PACKAGE_DIR`,ENV_SHARE_VIEWER_URL=`${ENV_PREFIX}\
|
|
48
52
|
_SHARE_VIEWER_URL`,ENV_SKIP_VERSION_CHECK=`${ENV_PREFIX}_SKIP_VERSION_CHECK`,ENV_STARTUP_BENCHMARK=`${ENV_PREFIX}_STARTUP_BENCHMARK`,ENV_TELEMETRY=`${ENV_PREFIX}_TELEMETRY`,ENV_VERSION_CHECK_URL=`${ENV_PREFIX}_VERSION_CHECK_URL`,ENV_BINARY_RELEASE_URL=`${ENV_PREFIX}_BINARY_RELEASE_URL`,ENV_INSTALL_TELEMETRY_URL=`${ENV_PREFIX}_INSTALL_TELEMETRY_URL`,ENV_CHANGELOG_URL=`${ENV_PREFIX}_CHANGELOG_URL`;function expandTildePath(path){return normalizePath(path)}var HUMAIN_TERMINAL_WEB_URL="https://code.h\
|
|
49
53
|
umain.com",HUMAIN_TERMINAL_BINARY_RELEASE_URL="https://gitlab.humain.com/humain/data-and-ai-modeling/standard/agentic/humain-terminal/-/releases/permalink/latest",HUMAIN_TERMINAL_VERSION_CHECK_URL="https://registry.npmjs.org/@humain%2fhumain-code/latest",HUMAIN_TERMINAL_INSTALL_TELEMETRY_URL=`${HUMAIN_TERMINAL_WEB_URL}/api/report-install`,HUMAIN_TERMINAL_CHANGELOG_URL=`${HUMAIN_TERMINAL_WEB_URL}/changelog`,DEFAULT_SHARE_VIEWER_URL=`${HUMAIN_TERMINAL_WEB_URL}/session/`;function getVersionCheckUrl(){
|
|
50
|
-
return process.env[ENV_VERSION_CHECK_URL]||HUMAIN_TERMINAL_VERSION_CHECK_URL}function getBinaryReleaseUrl(){return process.env[ENV_BINARY_RELEASE_URL]||HUMAIN_TERMINAL_BINARY_RELEASE_URL}function getShareViewerUrl(gistId){return`${process.env[ENV_SHARE_VIEWER_URL]||process.env.PI_SHARE_VIEWER_URL||DEFAULT_SHARE_VIEWER_URL}#${gistId}`}function getAgentDir(){let envDir=process.env[ENV_AGENT_DIR];return envDir?expandTildePath(envDir):
|
|
51
|
-
getHumainModuleAssetsDir,getBundledFlowPackageDir,getBundledFlowProfilesDir,getQuickJSWasmPath,getCodemodeWorkerSpecifier,detectInstallChange,PACKAGE_NAME,APP_NAME,APP_TITLE,APP_COMMAND,CONFIG_DIR_NAME,FIRST_TIME_SETUP_ENABLED,VERSION,UPSTREAM_PI_VERSION,ENV_PREFIX,ENV_AGENT_DIR,ENV_SESSION_DIR,ENV_MCP_CLIENT_METADATA_URL,ENV_OFFLINE,ENV_PACKAGE_DIR,ENV_SHARE_VIEWER_URL,ENV_SKIP_VERSION_CHECK,ENV_TELEMETRY,expandTildePath,HUMAIN_TERMINAL_WEB_URL,DEFAULT_SHARE_VIEWER_URL,
|
|
52
|
-
getAgentDir,getCustomThemesDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath};
|
|
54
|
+
return process.env[ENV_VERSION_CHECK_URL]||HUMAIN_TERMINAL_VERSION_CHECK_URL}function getBinaryReleaseUrl(){return process.env[ENV_BINARY_RELEASE_URL]||HUMAIN_TERMINAL_BINARY_RELEASE_URL}function getShareViewerUrl(gistId){return`${process.env[ENV_SHARE_VIEWER_URL]||process.env.PI_SHARE_VIEWER_URL||DEFAULT_SHARE_VIEWER_URL}#${gistId}`}function getAgentDir(){let envDir=process.env[ENV_AGENT_DIR];return envDir?expandTildePath(envDir):join3(homedir2(),CONFIG_DIR_NAME,"agent")}function getCustomThemesDir(){return join3(getAgentDir(),"themes")}function getAuthPath(){return join3(getAgentDir(),"auth.json")}function getSettingsPath(){return join3(getAgentDir(),"settings.json")}function getBinDir(){return join3(getAgentDir(),"bin")}function getSessionsDir(){return join3(getAgentDir(),"sessions")}function getDebugLogPath(){return join3(getAgentDir(),`${APP_NAME}-debug.log`)}export{require_resolveCommand,require_readShebang,require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBunRuntime,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getThemesDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,
|
|
55
|
+
getBundledInteractiveAssetPath,getHumainModuleAssetsDir,getBundledFlowPackageDir,getBundledFlowProfilesDir,getQuickJSWasmPath,getCodemodeWorkerSpecifier,detectInstallChange,PACKAGE_NAME,APP_NAME,APP_TITLE,APP_COMMAND,CONFIG_DIR_NAME,FIRST_TIME_SETUP_ENABLED,VERSION,UPSTREAM_PI_VERSION,ENV_PREFIX,ENV_AGENT_DIR,ENV_SESSION_DIR,ENV_MCP_CLIENT_METADATA_URL,ENV_OFFLINE,ENV_PACKAGE_DIR,ENV_SHARE_VIEWER_URL,ENV_SKIP_VERSION_CHECK,ENV_TELEMETRY,expandTildePath,HUMAIN_TERMINAL_WEB_URL,DEFAULT_SHARE_VIEWER_URL,
|
|
56
|
+
getVersionCheckUrl,getShareViewerUrl,getAgentDir,getCustomThemesDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{VisualLinePreview,formatSize,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs,truncateMiddle,writeOutputFile}from"./chunk-
|
|
2
|
+
import{VisualLinePreview,formatSize,formatToolCallWithArgs,getShellConfig,getTextOutput,replaceTabs,truncateMiddle,writeOutputFile}from"./chunk-PMISFIBM.js";import{Container,Spacer,Text,keyHint}from"./chunk-LQ4S7CRR.js";import{getAgentDir,getFileRevision,normalizePath,require_cross_spawn,require_readShebang,require_resolveCommand,stripBom}from"./chunk-3E4SMILM.js";import{__commonJS,__require,__toESM}from"./chunk-JXWJOIH4.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.
|
|
3
3
|
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),
|
|
4
4
|
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(){}),
|
|
5
5
|
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,
|
|
@@ -53,9 +53,9 @@ Object.assign(err2,{code:"ECOMPROMISED"})):(lock2.updateDelay=1e3,updateLock(fil
|
|
|
53
53
|
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"}));
|
|
54
54
|
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){
|
|
55
55
|
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.
|
|
56
|
-
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((
|
|
57
|
-
(err,result)=>{err?reject(err):
|
|
58
|
-
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,
|
|
56
|
+
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((resolve2,reject)=>{args.
|
|
57
|
+
push((err,result)=>{err?reject(err):resolve2(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("Cann\
|
|
58
|
+
ot 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,
|
|
59
59
|
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(
|
|
60
60
|
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+
|
|
61
61
|
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){
|
|
@@ -64,8 +64,8 @@ config,env).length===0}function resolveConfigValue(config,env){let reference=par
|
|
|
64
64
|
"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){
|
|
65
65
|
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){
|
|
66
66
|
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)}`);
|
|
67
|
-
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{randomBytes}from"crypto";import{closeSync,existsSync,fchmodSync,fchownSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,realpathSync,renameSync,rmSync,statSync,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((
|
|
68
|
-
(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),
|
|
67
|
+
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{randomBytes}from"crypto";import{closeSync,existsSync,fchmodSync,fchownSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,realpathSync,renameSync,rmSync,statSync,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((resolve2,reject)=>{let settled=!1,cleanup=()=>signal.removeEventListener("abort",onAbort),onAbort=()=>{settled||
|
|
68
|
+
(settled=!0,cleanup(),reject(abortReason(signal)))};signal.addEventListener("abort",onAbort,{once:!0}),operation.then(value=>{settled||(settled=!0,cleanup(),resolve2(value))},error=>{settled||(settled=!0,cleanup(),reject(error))}),signal.aborted&&onAbort()}):operation}var AccountSourceReplacementError=class extends Error{constructor(){super("Stored configuration reference cannot be replaced by account selection or login. Explicit replacement consent is required."),this.name="AccountSourceReplacementError"}},AUTH_FILE_WRITE_OPTIONS={encoding:"utf-8",mode:384};function writeFileAtomic(path,content){let target=path,existing;existsSync(path)&&(target=realpathSync(path),existing=statSync(target));let temp=`${target}.${randomBytes(6).toString("hex")}.tmp`,fd=openSync(
|
|
69
69
|
temp,"wx",AUTH_FILE_WRITE_OPTIONS.mode);try{try{let created=fstatSync(fd);if(existing&&(created.uid!==existing.uid||created.gid!==existing.gid))try{fchownSync(fd,existing.uid,existing.gid)}catch(error){let code=error.code;throw code!=="EPERM"&&code!=="EACCES"?error:new Error("Cannot preserve credential file owner and group; refusing to write in place",{cause:error})}writeFileSync(fd,content,AUTH_FILE_WRITE_OPTIONS.encoding),fchmodSync(fd,existing?existing.mode&4095:AUTH_FILE_WRITE_OPTIONS.mode),
|
|
70
70
|
fsyncSync(fd)}finally{closeSync(fd)}renameSync(temp,target)}catch(error){throw rmSync(temp,{force:!0}),error}}var sharedAuthFileReadState,FileAuthStorageBackend=class{authPath;constructor(authPath=join(getAgentDir(),"auth.json")){this.authPath=normalizePath(authPath)}makePrivate(){let fd=openSync(this.authPath,"r");try{fchmodSync(fd,384),fsyncSync(fd)}finally{closeSync(fd)}}ensureParentDir(){let dir=dirname(this.authPath);existsSync(dir)||mkdirSync(dir,{recursive:!0,mode:448})}ensureFileExists(){
|
|
71
71
|
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 \
|
|
@@ -121,27 +121,30 @@ return this.closeListeners.add(listener),()=>this.closeListeners.delete(listener
|
|
|
121
121
|
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(
|
|
122
122
|
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))
|
|
123
123
|
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?.
|
|
124
|
-
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((
|
|
125
|
-
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}),
|
|
126
|
-
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(
|
|
127
|
-
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(
|
|
128
|
-
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;
|
|
124
|
+
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((resolve2,reject)=>{let entry={
|
|
125
|
+
resolve:resolve2,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}),
|
|
126
|
+
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(
|
|
127
|
+
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(
|
|
128
|
+
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;
|
|
129
129
|
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.
|
|
130
130
|
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===
|
|
131
131
|
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.
|
|
132
132
|
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&&
|
|
133
133
|
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[
|
|
134
|
-
...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.
|
|
135
|
-
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
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
134
|
+
...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_readShebang=__toESM(require_readShebang(),1),import_resolveCommand=__toESM(require_resolveCommand(),1);import{spawn}from"node:child_process";import{lstatSync,statSync as statSync2}from"node:fs";import{delimiter,isAbsolute,join as join2,resolve}from"node:path";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.
|
|
135
|
+
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 isProgramFile(file){try{let stats=statSync2(file,{throwIfNoEntry:!1});if(stats)return stats.isFile()}catch{}try{let link=lstatSync(file,{throwIfNoEntry:!1});return link!==void 0&&!link.isDirectory()}catch{return!1}}function resolveWindowsServerCommand(command,env){if(/[\\/]/.test(command))return command;let pathKey="\
|
|
136
|
+
PATH"in env?"PATH":Object.keys(env).find(key=>key.toLowerCase()==="path"),dirs=(pathKey?env[pathKey]??"":"").split(delimiter).map(dir=>dir.trim().replace(/^"(.*)"$/,"$1")).filter(dir=>dir&&isAbsolute(dir)),pathExtensions=(env.PATHEXT??".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean),extensions=command.includes(".")?["",...pathExtensions]:pathExtensions;for(let dir of dirs)for(let extension of extensions){let file=join2(dir,command+extension);if(isProgramFile(file))return file}return join2(process2.
|
|
137
|
+
env.SystemRoot??"C:\\Windows","humain-code-no-such-command",`${command}.exe`)}function killProcessTree(child,signal){let pid=child.pid;if(process2.platform==="win32"&&pid!==void 0){if(child.exitCode!==null)return;let taskkill=join2(process2.env.SystemRoot??"C:\\Windows","System32","taskkill.exe");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{}}
|
|
138
|
+
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(
|
|
139
|
+
"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},command=this.options.command,args=this.options.args??[];if(process2.platform==="win32"){let visited=new Set;for(;;){command=resolve(this.options.cwd??"",resolveWindowsServerCommand(command,env)),command=(0,import_resolveCommand.default)({command,
|
|
140
|
+
options:{env}})??command;let key=command.toLowerCase();if(visited.has(key)||visited.size===32){command=resolveWindowsServerCommand("shebang-chain",{PATH:""});break}visited.add(key);let interpreter=(0,import_readShebang.default)(command);if(!interpreter)break;args=[command,...args],command=interpreter}}let child=(0,import_cross_spawn.default)(command,args,{cwd:this.options.cwd,env,stdio:["pipe","pipe",this.options.stderr==="inherit"?"inherit":"pipe"],windowsHide:!0,detached:USE_PROCESS_GROUPS});this.
|
|
141
|
+
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.
|
|
142
|
+
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((resolve2,reject)=>{let onSpawn=()=>{child.off("error",onError),resolve2()},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;
|
|
140
143
|
if(!this.started||this.closed||!stdin?.writable)throw new McpConnectionClosedError;let payload=`${JSON.stringify(message)}
|
|
141
|
-
`;await new Promise((
|
|
142
|
-
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){
|
|
143
|
-
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(
|
|
144
|
-
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(`
|
|
144
|
+
`;await new Promise((resolve2,reject)=>{stdin.write(payload,error=>error?reject(error):resolve2())})}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(resolve2=>{let timers=[];child.once("close",()=>{for(let timer of timers)clearTimeout(timer);killProcessTree(child,"SIGTERM"),
|
|
145
|
+
resolve2()});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){
|
|
146
|
+
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(
|
|
147
|
+
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(`
|
|
145
148
|
`);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.
|
|
146
149
|
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(`
|
|
147
150
|
`);for(;newline>=0;)processLine(buffered.slice(0,newline)),buffered=buffered.slice(newline+1),newline=buffered.indexOf(`
|
|
@@ -161,7 +164,7 @@ void 0?"stream ended without a response":toError(failure).message;this.emitMessa
|
|
|
161
164
|
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){
|
|
162
165
|
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){
|
|
163
166
|
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(){
|
|
164
|
-
return this.options.reconnect?.maxRetries??DEFAULT_RECONNECT_MAX_RETRIES}sleep(ms){let signal=this.controller.signal;return signal.aborted?Promise.resolve(!1):new Promise(
|
|
167
|
+
return this.options.reconnect?.maxRetries??DEFAULT_RECONNECT_MAX_RETRIES}sleep(ms){let signal=this.controller.signal;return signal.aborted?Promise.resolve(!1):new Promise(resolve2=>{let onAbort=()=>{clearTimeout(timer),resolve2(!1)},timer=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve2(!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.
|
|
165
168
|
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}from"node:crypto";function toToolExposure(exposure){return exposure==="codemode"?"deferred":exposure}var MAX_TOOL_NAME_LENGTH=64,MCP_OUTPUT_MAX_BYTES=20*1024,OUTPUT_PREVIEW_LINES=5;function saveToTempFile(data,extension){return writeOutputFile("pi-mcp",extension,data)}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").
|
|
166
169
|
map(block=>block.text).join(`
|
|
167
170
|
`)}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{
|