@astralyn/pi 1.4.4 → 1.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (230) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/chunk-5M3YJ54Z.js +82 -0
  4. package/dist/bundle/chunks/chunk-6QGV3IWD.js +6 -0
  5. package/dist/bundle/chunks/chunk-ALHAFUHP.js +7 -0
  6. package/dist/bundle/chunks/chunk-AXFWZIHH.js +4 -0
  7. package/dist/bundle/chunks/chunk-EYKC6ESU.js +2 -0
  8. package/dist/bundle/chunks/chunk-KDO6L76C.js +230 -0
  9. package/dist/bundle/chunks/chunk-RBTJBQWX.js +1500 -0
  10. package/dist/bundle/chunks/chunk-RLNMABLM.js +9 -0
  11. package/dist/bundle/chunks/cli-FH77R7JR.js +51 -0
  12. package/dist/bundle/chunks/execute-5ZQUS52M.js +505 -0
  13. package/dist/bundle/chunks/runtime-R5CMHJ5P.js +2 -0
  14. package/dist/bundle/chunks/virtual-modules-KCQU7LOC.js +2 -0
  15. package/dist/bundle/cli.js +1 -1
  16. package/dist/bundle/index.js +1 -1
  17. package/dist/bundle/rpc-entry.js +1 -1
  18. package/dist/core/agent-session.d.ts.map +1 -1
  19. package/dist/core/agent-session.js +2 -0
  20. package/dist/core/agent-session.js.map +1 -1
  21. package/dist/core/extensions/index.d.ts +1 -1
  22. package/dist/core/extensions/index.d.ts.map +1 -1
  23. package/dist/core/extensions/index.js.map +1 -1
  24. package/dist/core/extensions/runner.d.ts +2 -0
  25. package/dist/core/extensions/runner.d.ts.map +1 -1
  26. package/dist/core/extensions/runner.js +18 -0
  27. package/dist/core/extensions/runner.js.map +1 -1
  28. package/dist/core/extensions/types.d.ts +6 -0
  29. package/dist/core/extensions/types.d.ts.map +1 -1
  30. package/dist/core/extensions/types.js.map +1 -1
  31. package/dist/core/isolated-session.d.ts +23 -0
  32. package/dist/core/isolated-session.d.ts.map +1 -0
  33. package/dist/core/isolated-session.js +55 -0
  34. package/dist/core/isolated-session.js.map +1 -0
  35. package/dist/core/model-config.d.ts +1 -3
  36. package/dist/core/model-config.d.ts.map +1 -1
  37. package/dist/core/model-config.js +1 -3
  38. package/dist/core/model-config.js.map +1 -1
  39. package/dist/core/settings-manager.d.ts +4 -0
  40. package/dist/core/settings-manager.d.ts.map +1 -1
  41. package/dist/core/settings-manager.js +38 -0
  42. package/dist/core/settings-manager.js.map +1 -1
  43. package/dist/core/settings-schema.d.ts +1 -0
  44. package/dist/core/settings-schema.d.ts.map +1 -1
  45. package/dist/core/settings-schema.js +3 -0
  46. package/dist/core/settings-schema.js.map +1 -1
  47. package/dist/core/tasks/codec.d.ts +12 -0
  48. package/dist/core/tasks/codec.d.ts.map +1 -0
  49. package/dist/core/tasks/codec.js +139 -0
  50. package/dist/core/tasks/codec.js.map +1 -0
  51. package/dist/core/tasks/execution.d.ts +64 -0
  52. package/dist/core/tasks/execution.d.ts.map +1 -0
  53. package/dist/core/tasks/execution.js +272 -0
  54. package/dist/core/tasks/execution.js.map +1 -0
  55. package/dist/core/tasks/output.d.ts +12 -5
  56. package/dist/core/tasks/output.d.ts.map +1 -1
  57. package/dist/core/tasks/output.js +38 -37
  58. package/dist/core/tasks/output.js.map +1 -1
  59. package/dist/core/tasks/presentation.d.ts +14 -5
  60. package/dist/core/tasks/presentation.d.ts.map +1 -1
  61. package/dist/core/tasks/presentation.js +56 -185
  62. package/dist/core/tasks/presentation.js.map +1 -1
  63. package/dist/core/tasks/runtime.d.ts +9 -9
  64. package/dist/core/tasks/runtime.d.ts.map +1 -1
  65. package/dist/core/tasks/runtime.js +63 -252
  66. package/dist/core/tasks/runtime.js.map +1 -1
  67. package/dist/core/tasks/scheduler.d.ts +16 -0
  68. package/dist/core/tasks/scheduler.d.ts.map +1 -0
  69. package/dist/core/tasks/scheduler.js +42 -0
  70. package/dist/core/tasks/scheduler.js.map +1 -0
  71. package/dist/core/tasks/session.d.ts +1 -0
  72. package/dist/core/tasks/session.d.ts.map +1 -1
  73. package/dist/core/tasks/session.js +15 -27
  74. package/dist/core/tasks/session.js.map +1 -1
  75. package/dist/core/tasks/store.js +4 -4
  76. package/dist/core/tasks/store.js.map +1 -1
  77. package/dist/core/tasks/types.d.ts +63 -49
  78. package/dist/core/tasks/types.d.ts.map +1 -1
  79. package/dist/core/tasks/types.js +3 -9
  80. package/dist/core/tasks/types.js.map +1 -1
  81. package/dist/core/tools/render-utils.d.ts +6 -4
  82. package/dist/core/tools/render-utils.d.ts.map +1 -1
  83. package/dist/core/tools/render-utils.js +34 -14
  84. package/dist/core/tools/render-utils.js.map +1 -1
  85. package/dist/core/tools/shell-execution.js +4 -4
  86. package/dist/core/tools/shell-execution.js.map +1 -1
  87. package/dist/core/tools/shell-tool.d.ts.map +1 -1
  88. package/dist/core/tools/shell-tool.js +23 -30
  89. package/dist/core/tools/shell-tool.js.map +1 -1
  90. package/dist/core/usage-totals.d.ts +1 -3
  91. package/dist/core/usage-totals.d.ts.map +1 -1
  92. package/dist/core/usage-totals.js +17 -8
  93. package/dist/core/usage-totals.js.map +1 -1
  94. package/dist/extensions/agent/activity.d.ts +13 -0
  95. package/dist/extensions/agent/activity.d.ts.map +1 -0
  96. package/dist/extensions/agent/activity.js +75 -0
  97. package/dist/extensions/agent/activity.js.map +1 -0
  98. package/dist/extensions/agent/index.d.ts +4 -0
  99. package/dist/extensions/agent/index.d.ts.map +1 -0
  100. package/dist/extensions/agent/index.js +11 -0
  101. package/dist/extensions/agent/index.js.map +1 -0
  102. package/dist/extensions/agent/progress.d.ts +31 -0
  103. package/dist/extensions/agent/progress.d.ts.map +1 -0
  104. package/dist/extensions/agent/progress.js +145 -0
  105. package/dist/extensions/agent/progress.js.map +1 -0
  106. package/dist/extensions/agent/render.d.ts +6 -0
  107. package/dist/extensions/agent/render.d.ts.map +1 -0
  108. package/dist/extensions/agent/render.js +120 -0
  109. package/dist/extensions/agent/render.js.map +1 -0
  110. package/dist/extensions/agent/report.d.ts +9 -0
  111. package/dist/extensions/agent/report.d.ts.map +1 -0
  112. package/dist/extensions/agent/report.js +40 -0
  113. package/dist/extensions/agent/report.js.map +1 -0
  114. package/dist/extensions/agent/settings-panel.d.ts +43 -0
  115. package/dist/extensions/agent/settings-panel.d.ts.map +1 -0
  116. package/dist/extensions/agent/settings-panel.js +125 -0
  117. package/dist/extensions/agent/settings-panel.js.map +1 -0
  118. package/dist/extensions/agent/settings.d.ts +15 -0
  119. package/dist/extensions/agent/settings.d.ts.map +1 -0
  120. package/dist/extensions/agent/settings.js +201 -0
  121. package/dist/extensions/agent/settings.js.map +1 -0
  122. package/dist/extensions/agent/tool.d.ts +13 -0
  123. package/dist/extensions/agent/tool.d.ts.map +1 -0
  124. package/dist/extensions/agent/tool.js +84 -0
  125. package/dist/extensions/agent/tool.js.map +1 -0
  126. package/dist/extensions/agent/types.d.ts +43 -0
  127. package/dist/extensions/agent/types.d.ts.map +1 -0
  128. package/dist/extensions/agent/types.js +6 -0
  129. package/dist/extensions/agent/types.js.map +1 -0
  130. package/dist/extensions/agent/worker.d.ts +16 -0
  131. package/dist/extensions/agent/worker.d.ts.map +1 -0
  132. package/dist/extensions/agent/worker.js +68 -0
  133. package/dist/extensions/agent/worker.js.map +1 -0
  134. package/dist/extensions/codemode/execute.js +1 -1
  135. package/dist/extensions/codemode/execute.js.map +1 -1
  136. package/dist/extensions/codemode/execute.lazy.d.ts +2 -2
  137. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -1
  138. package/dist/extensions/codemode/execute.lazy.js +2 -2
  139. package/dist/extensions/codemode/execute.lazy.js.map +1 -1
  140. package/dist/extensions/index.d.ts.map +1 -1
  141. package/dist/extensions/index.js +2 -0
  142. package/dist/extensions/index.js.map +1 -1
  143. package/dist/extensions/mcp/cli.lazy.d.ts +2 -2
  144. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -1
  145. package/dist/extensions/mcp/cli.lazy.js +2 -2
  146. package/dist/extensions/mcp/cli.lazy.js.map +1 -1
  147. package/dist/extensions/mcp/index.d.ts.map +1 -1
  148. package/dist/extensions/mcp/index.js +2 -2
  149. package/dist/extensions/mcp/index.js.map +1 -1
  150. package/dist/extensions/mcp/runtime.lazy.d.ts +2 -2
  151. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -1
  152. package/dist/extensions/mcp/runtime.lazy.js +2 -2
  153. package/dist/extensions/mcp/runtime.lazy.js.map +1 -1
  154. package/dist/extensions/provider/compat-fields.js +1 -1
  155. package/dist/extensions/provider/compat-fields.js.map +1 -1
  156. package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
  157. package/dist/extensions/tasks/tool/actions.js +1 -9
  158. package/dist/extensions/tasks/tool/actions.js.map +1 -1
  159. package/dist/extensions/tasks/tool/schema.js +1 -1
  160. package/dist/extensions/tasks/tool/schema.js.map +1 -1
  161. package/dist/extensions/tasks/tool/types.d.ts +2 -8
  162. package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
  163. package/dist/extensions/tasks/tool/types.js +0 -2
  164. package/dist/extensions/tasks/tool/types.js.map +1 -1
  165. package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
  166. package/dist/extensions/tasks/ui/completion-render.js +27 -26
  167. package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
  168. package/dist/extensions/tasks/ui/inspector.d.ts +5 -3
  169. package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
  170. package/dist/extensions/tasks/ui/inspector.js +18 -6
  171. package/dist/extensions/tasks/ui/inspector.js.map +1 -1
  172. package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
  173. package/dist/extensions/tasks/ui/layout.js +111 -75
  174. package/dist/extensions/tasks/ui/layout.js.map +1 -1
  175. package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
  176. package/dist/extensions/tasks/ui/list.js +43 -28
  177. package/dist/extensions/tasks/ui/list.js.map +1 -1
  178. package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
  179. package/dist/extensions/tasks/ui/manager.js +8 -2
  180. package/dist/extensions/tasks/ui/manager.js.map +1 -1
  181. package/dist/extensions/tasks/ui/model.d.ts +4 -0
  182. package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
  183. package/dist/extensions/tasks/ui/model.js +12 -1
  184. package/dist/extensions/tasks/ui/model.js.map +1 -1
  185. package/dist/extensions/tasks/ui/render.js +3 -4
  186. package/dist/extensions/tasks/ui/render.js.map +1 -1
  187. package/dist/extensions/tasks/ui/task-view.d.ts +0 -5
  188. package/dist/extensions/tasks/ui/task-view.d.ts.map +1 -1
  189. package/dist/extensions/tasks/ui/task-view.js +0 -7
  190. package/dist/extensions/tasks/ui/task-view.js.map +1 -1
  191. package/dist/extensions/tasks/ui/tree.js +1 -1
  192. package/dist/extensions/tasks/ui/tree.js.map +1 -1
  193. package/dist/extensions/tasks/ui/views.d.ts +10 -6
  194. package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
  195. package/dist/extensions/tasks/ui/views.js +64 -28
  196. package/dist/extensions/tasks/ui/views.js.map +1 -1
  197. package/dist/index.d.ts +2 -1
  198. package/dist/index.d.ts.map +1 -1
  199. package/dist/index.js.map +1 -1
  200. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  201. package/dist/modes/interactive/components/keybinding-hints.js +2 -1
  202. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  203. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  204. package/dist/modes/interactive/components/model-selector.js +7 -4
  205. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  206. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  207. package/dist/modes/interactive/components/thinking-selector.js +10 -3
  208. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  209. package/docs/bundled/README.md +1 -0
  210. package/docs/bundled/extensions/agent.md +68 -0
  211. package/docs/bundled/extensions/statusline.md +1 -1
  212. package/docs/bundled/tasks.md +15 -14
  213. package/docs/docs.json +4 -0
  214. package/docs/extensions.md +33 -6
  215. package/docs/sdk.md +2 -2
  216. package/docs/session-format.md +27 -23
  217. package/npm-shrinkwrap.json +2 -2
  218. package/package.json +1 -1
  219. package/schemas/settings.schema.json +12 -0
  220. package/dist/bundle/chunks/chunk-SBVVM3NV.js +0 -2361
  221. package/dist/bundle/chunks/chunk-VGSZTBVJ.js +0 -2
  222. package/dist/bundle/chunks/virtual-modules-ETYFHSUG.js +0 -2
  223. package/dist/core/tasks/history.d.ts +0 -4
  224. package/dist/core/tasks/history.d.ts.map +0 -1
  225. package/dist/core/tasks/history.js +0 -121
  226. package/dist/core/tasks/history.js.map +0 -1
  227. package/dist/extensions/codemode/search.d.ts +0 -33
  228. package/dist/extensions/codemode/search.d.ts.map +0 -1
  229. package/dist/extensions/codemode/search.js +0 -117
  230. package/dist/extensions/codemode/search.js.map +0 -1
@@ -0,0 +1,9 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{__commonJS,__require,__toESM}from"./chunk-4L3WN2XY.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.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: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(resolve2,reject){isexe(path,options||{},function(er,is){er?reject(er):resolve2(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||"").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((resolve2,reject)=>{if(i===pathEnv.length)return opt.all&&found.length?resolve2(found):reject(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;resolve2(subStep(p,i,0))}),subStep=(p,i,ii)=>new Promise((resolve2,reject)=>{if(ii===pathExt.length)return resolve2(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 resolve2(p+ext);return resolve2(subStep(p,i,ii+1))})});return cb?step(0).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)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;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 resolveCommand(parsed){return resolveCommandAttempt(parsed)||resolveCommandAttempt(parsed,!0)}module.exports=resolveCommand}});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,"^$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 readShebang(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=readShebang}});var require_parse=__commonJS({"node_modules/cross-spawn/lib/parse.js"(exports,module){"use strict";var path=__require("path"),resolveCommand=require_resolveCommand(),escape=require_escape(),readShebang=require_readShebang(),isWin=process.platform==="win32",isExecutableRegExp=/\.(?:com|exe)$/i,isCmdShimRegExp=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function detectShebang(parsed){parsed.file=resolveCommand(parsed);let shebang=parsed.file&&readShebang(parsed.file);return shebang?(parsed.args.unshift(parsed.file),parsed.command=shebang,resolveCommand(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));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=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(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 spawn2(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 spawnSync2(command,args,options){let parsed=parse(command,args,options),result=cp.spawnSync(parsed.command,parsed.args,parsed.options);return result.error=result.error||enoent.verifyENOENTSync(result.status,parsed),result}module.exports=spawn2;module.exports.spawn=spawn2;module.exports.sync=spawnSync2;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 join2,resolve,sep as sep2,win32}from"path";import{fileURLToPath as fileURLToPath2}from"url";var import_cross_spawn=__toESM(require_cross_spawn(),1);import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";var EXIT_STDIO_GRACE_MS=100;function spawnProcess(command,args,options){return process.platform==="win32"?(0,import_cross_spawn.default)(command,args,options):nodeSpawn(command,args,options)}function spawnProcessSync(command,args,options){return process.platform==="win32"?import_cross_spawn.default.sync(command,args,options):nodeSpawnSync(command,args,options)}function waitForChildProcess(child){return new Promise((resolve2,reject)=>{let settled=!1,exited=!1,exitCode=null,postExitTimer,stdoutEnded=child.stdout===null,stderrEnded=child.stderr===null,cleanup=()=>{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",onData)},finalize=code=>{settled||(settled=!0,cleanup(),child.stdout?.destroy(),child.stderr?.destroy(),resolve2(code))},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=()=>{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)})}import{realpathSync,statSync}from"node:fs";import{homedir}from"node:os";import{isAbsolute,join,resolve as nodeResolvePath,relative,sep}from"node:path";import{fileURLToPath}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=statSync(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("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.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 join(home,normalized.slice(2))}return/^file:\/\//.test(normalized)?fileURLToPath(normalized):normalized}function resolvePath(input,baseDir=process.cwd(),options={}){let normalized=normalizePath(input,options),normalizedBaseDir=normalizePath(baseDir);return isAbsolute(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.startsWith(`..${sep}`)&&!isAbsolute(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==="darwin"?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=fileURLToPath2(import.meta.url),__dirname=dirname(__filename),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}}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,"/");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),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"bun-binary":return;case"pnpm":{let match=readCommandOutput("pnpm",["root","-g"])?void 0:/^(.*[\\/]global[\\/][^\\/]+)[\\/]\.pnpm[\\/]/.exec(getPackageDir()),binDirArgs=match?[`--config.global-bin-dir=${process.env.PNPM_HOME||dirname(dirname(match[1]))}`]:[];return makeSelfUpdateCommand(makeSelfUpdateCommandStep("pnpm",["install","-g","--ignore-scripts","--config.minimumReleaseAge=0",...binDirArgs,target.installSpec]),target.packageName===installedPackageName?void 0:makeSelfUpdateCommandStep("pnpm",["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?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,[...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].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=[join2(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join2(dirname(bunBin),"install","global","node_modules")),roots}let root=readCommandOutput(command,[...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,join2(dir,"node_modules")]:[]}case"bun":{let bunBin=readCommandOutput("bun",["pm","bin","-g"]),roots=[join2(homedir2(),".bun","install","global","node_modules")];return bunBin&&roots.push(join2(dirname(bunBin),"install","global","node_modules")),roots}case"bun-binary":case"unknown":return[]}}function normalizeExistingPathForComparison(path,resolveSymlinks){let resolvedPath=resolve(path);if(!existsSync(resolvedPath))return;let normalizedPath=resolvedPath;if(resolveSymlinks)try{normalizedPath=realpathSync2(resolvedPath)}catch{return}return process.platform==="win32"&&(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(join2(dir,"package.json")))return dir;dir=dirname(dir)}}function isSelfUpdatePathWritable(){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.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){let method=detectInstallMethod(),target=normalizeSelfUpdatePackageTarget(updatePackageTarget);if(method==="bun-binary")return"Download from: https://github.com/earendil-works/pi/releases/latest";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}`:`This 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(join2(dir,"package.json"))){let parent=dirname(dir);return basename(dir)==="dist"&&existsSync(join2(parent,"package.json"))?parent:dir}dir=dirname(dir)}return startDir}function getPackageDir(){let envDir=process.env.PI_PACKAGE_DIR;return envDir?normalizePath(envDir):isBunBinary?dirname(process.execPath):findNodePackageDir(__dirname)}function getThemesDir(){if(isBunBinary)return join2(getPackageDir(),"theme");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"modes","interactive","theme")}function getExportTemplateDir(){if(isBunBinary)return join2(getPackageDir(),"export-html");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"core","export-html")}function getPackageJsonPath(){return join2(getPackageDir(),"package.json")}function getReadmePath(){return resolve(join2(getPackageDir(),"README.md"))}function getDocsPath(){return resolve(join2(getPackageDir(),"docs"))}function getExamplesPath(){return resolve(join2(getPackageDir(),"examples"))}function getChangelogPath(){return resolve(join2(getPackageDir(),"CHANGELOG.md"))}function getInteractiveAssetsDir(){if(isBunBinary)return join2(getPackageDir(),"assets");let packageDir=getPackageDir(),srcOrDist=existsSync(join2(packageDir,"src"))?"src":"dist";return join2(packageDir,srcOrDist,"modes","interactive","assets")}function getBundledInteractiveAssetPath(name){return join2(getInteractiveAssetsDir(),name)}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"./src/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(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.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 piConfigName=pkg.piConfig?.name,DISTRIBUTION_PACKAGE_NAME="@astralyn/pi",INSTALL_TELEMETRY_URL=void 0,UPDATE_CHANGELOG_HINT="Run /changelog to view changes.",PACKAGE_NAME=pkg.name||DISTRIBUTION_PACKAGE_NAME,APP_NAME=piConfigName||"pi",APP_TITLE=piConfigName?APP_NAME:"\u03C0",CONFIG_DIR_NAME=pkg.piConfig?.configDir||".pi",VERSION=pkg.version||"0.0.0",ENV_AGENT_DIR=`${APP_NAME.toUpperCase()}_CODING_AGENT_DIR`,ENV_SESSION_DIR=`${APP_NAME.toUpperCase()}_CODING_AGENT_SESSION_DIR`;function expandTildePath(path){return normalizePath(path)}var DEFAULT_SHARE_VIEWER_URL="https://pi.dev/session/";function getShareViewerUrl(gistId){return`${process.env.PI_SHARE_VIEWER_URL||DEFAULT_SHARE_VIEWER_URL}#${gistId}`}function getAgentDir(){let envDir=process.env[ENV_AGENT_DIR];return envDir?expandTildePath(envDir):join2(homedir2(),CONFIG_DIR_NAME,"agent")}function getCustomThemesDir(){return join2(getAgentDir(),"themes")}function getAuthPath(){return join2(getAgentDir(),"auth.json")}function getSettingsPath(){return join2(getAgentDir(),"settings.json")}function getBinDir(){return join2(getAgentDir(),"bin")}function getSessionsDir(){return join2(getAgentDir(),"sessions")}function getDebugLogPath(){return join2(getAgentDir(),`${APP_NAME}-debug.log`)}import{accessSync as accessSync2,constants as constants2}from"node:fs";import{delimiter,join as join3,win32 as win322}from"node:path";import{spawn,spawnSync}from"child_process";function isLegacyWslBashPath(path){let normalized=win322.normalize(path).toLowerCase(),systemRoot=process.env.SystemRoot;return systemRoot?/^[a-z]:[\\/]/i.test(systemRoot)?["System32","Sysnative"].some(directory=>normalized===win322.join(systemRoot,directory,"bash.exe").toLowerCase()):!1:/^[a-z]:\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(normalized)}function getBashShellConfig(shell){return isLegacyWslBashPath(shell)?{shell,args:["-s"],commandTransport:"stdin"}:{shell,args:["-c"]}}function shellPathExists(path){try{return accessSync2(path,constants2.F_OK),!0}catch{return!1}}function findExecutableOnPath(executable){if(process.platform==="win32"){try{let result=spawnSync("where",[executable],{encoding:"utf-8",timeout:5e3,windowsHide:!0});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch&&shellPathExists(firstMatch))return firstMatch}}catch{}return null}try{let result=spawnSync("which",[executable],{encoding:"utf-8",timeout:5e3});if(result.status===0&&result.stdout){let firstMatch=result.stdout.trim().split(/\r?\n/)[0];if(firstMatch)return firstMatch}}catch{}return null}function getShellConfig(customShellPath){if(customShellPath){if(shellPathExists(customShellPath))return getBashShellConfig(customShellPath);throw new Error(`Custom shell path not found: ${customShellPath}`)}if(process.platform==="win32"){let paths=[],programFiles=process.env.ProgramFiles;programFiles&&paths.push(`${programFiles}\\Git\\bin\\bash.exe`);let programFilesX86=process.env["ProgramFiles(x86)"];programFilesX86&&paths.push(`${programFilesX86}\\Git\\bin\\bash.exe`);for(let path of paths)if(shellPathExists(path))return getBashShellConfig(path);let bashOnPath2=findExecutableOnPath("bash.exe");if(bashOnPath2)return getBashShellConfig(bashOnPath2);throw new Error(`No bash shell found. Options:
3
+ 1. Install Git for Windows: https://git-scm.com/download/win
4
+ 2. Add your bash to PATH (Cygwin, MSYS2, etc.)
5
+ 3. Set shellPath in settings.json
6
+
7
+ Searched Git Bash in:
8
+ ${paths.map(p=>` ${p}`).join(`
9
+ `)}`)}if(shellPathExists("/bin/bash"))return getBashShellConfig("/bin/bash");let bashOnPath=findExecutableOnPath("bash");return bashOnPath?getBashShellConfig(bashOnPath):{shell:"sh",args:["-c"]}}var POWERSHELL_ARGS=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];function getPowerShellConfig(){if(process.platform!=="win32")throw new Error("The powershell tool is only available on Windows.");let shell=findExecutableOnPath("pwsh.exe"),programFiles=process.env.ProgramFiles;if(!shell&&programFiles){let pwsh7=win322.join(programFiles,"PowerShell","7","pwsh.exe");shellPathExists(pwsh7)&&(shell=pwsh7)}shell??=findExecutableOnPath("powershell.exe");let systemRoot=process.env.SystemRoot;if(!shell&&systemRoot){let windowsPowerShell=win322.join(systemRoot,"System32","WindowsPowerShell","v1.0","powershell.exe");shellPathExists(windowsPowerShell)&&(shell=windowsPowerShell)}if(!shell)throw new Error("No PowerShell executable found. Install PowerShell or add powershell.exe/pwsh.exe to PATH.");return{shell,args:[...POWERSHELL_ARGS]}}function getShellEnv(){let binDir=getBinDir(),pathKey=Object.keys(process.env).find(key=>key.toLowerCase()==="path")??"PATH",currentPath=process.env[pathKey]??"",updatedPath=currentPath.split(delimiter).filter(Boolean).includes(binDir)?currentPath:[binDir,currentPath].filter(Boolean).join(delimiter);return{...process.env,[pathKey]:updatedPath}}function sanitizeBinaryOutput(str){return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\uFFF9-\uFFFB]/g,"")}var trackedDetachedChildPids=new Set;function trackDetachedChildPid(pid){trackedDetachedChildPids.add(pid)}function untrackDetachedChildPid(pid){trackedDetachedChildPids.delete(pid)}function killTrackedDetachedChildren(){for(let pid of trackedDetachedChildPids)killProcessTree(pid);trackedDetachedChildPids.clear()}function killProcessTree(pid){if(process.platform==="win32")try{spawn(join3(process.env.SystemRoot||"C:\\Windows","System32","taskkill.exe"),["/F","/T","/PID",String(pid)],{stdio:"ignore",detached:!0,windowsHide:!0}).once("error",()=>{})}catch{}else try{process.kill(-pid,"SIGKILL")}catch{try{process.kill(pid,"SIGKILL")}catch{}}}export{require_cross_spawn,spawnProcess,spawnProcessSync,waitForChildProcess,canonicalizePath,getFileRevision,isLocalPath,normalizePath,resolvePath,getCwdRelativePath,formatPathRelativeToCwdOrAbsolute,markPathIgnoredByCloudSync,splitBom,stripBom,isBunBinary,isBundledNode,detectInstallMethod,getSelfUpdateCommand,getSelfUpdateUnavailableInstruction,getPackageDir,getThemesDir,getExportTemplateDir,getReadmePath,getDocsPath,getExamplesPath,getChangelogPath,getBundledInteractiveAssetPath,getQuickJSWasmPath,getCodemodeWorkerSpecifier,detectInstallChange,DISTRIBUTION_PACKAGE_NAME,INSTALL_TELEMETRY_URL,UPDATE_CHANGELOG_HINT,PACKAGE_NAME,APP_NAME,APP_TITLE,CONFIG_DIR_NAME,VERSION,ENV_AGENT_DIR,ENV_SESSION_DIR,expandTildePath,getShareViewerUrl,getAgentDir,getCustomThemesDir,getAuthPath,getSettingsPath,getBinDir,getSessionsDir,getDebugLogPath,getShellConfig,getPowerShellConfig,getShellEnv,sanitizeBinaryOutput,trackDetachedChildPid,untrackDetachedChildPid,killTrackedDetachedChildren,killProcessTree};
@@ -0,0 +1,51 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{McpOAuthCredentialStore,McpServerConnection,McpServerLog,McpSignInCancelledError,createDefaultTransport,signInMcpServer}from"./chunk-5M3YJ54Z.js";import{ProjectTrustStore,addMcpServerConfig,loadMcpConfig,openBrowser,removeMcpServerConfig}from"./chunk-AXFWZIHH.js";import{getMcpToolExposure,validateMcpServerConfig}from"./chunk-ALHAFUHP.js";import{source_default}from"./chunk-6QGV3IWD.js";import{APP_NAME,CONFIG_DIR_NAME}from"./chunk-RLNMABLM.js";import"./chunk-4L3WN2XY.js";import{existsSync}from"node:fs";import{join}from"node:path";import{createInterface}from"node:readline/promises";var HELP=`${source_default.bold("Usage:")}
3
+ ${APP_NAME} mcp add <server> [options] -- <command> [args...]
4
+ ${APP_NAME} mcp add <server> [options] --url <url>
5
+ ${APP_NAME} mcp remove <server> [-l]
6
+ ${APP_NAME} mcp list [--json]
7
+ ${APP_NAME} mcp login <server> [--timeout <seconds>]
8
+ ${APP_NAME} mcp logout <server>
9
+
10
+ Configure and check MCP servers and sign in to OAuth servers without starting a session.
11
+ Reads ~/${CONFIG_DIR_NAME}/agent/mcp.json and, in trusted projects, ${CONFIG_DIR_NAME}/mcp.json.
12
+
13
+ Commands:
14
+ add <server> Add or replace a server in mcp.json
15
+ remove <server> Remove a server from mcp.json
16
+ list Show state, tools, and errors (exits 1 on failure)
17
+ login <server> Sign in through the browser
18
+ logout <server> Delete the stored OAuth credentials
19
+
20
+ Options for add and remove:
21
+ -l, --local Use ${CONFIG_DIR_NAME}/mcp.json in the current project instead of the global file
22
+
23
+ Options for add:
24
+ --url <url> Streamable HTTP server URL (instead of a command)
25
+ --env <KEY=VALUE> Environment variable for a stdio server (repeatable)
26
+ --cwd <dir> Working directory for a stdio server
27
+ --header <KEY=VALUE> HTTP header (repeatable)
28
+ --bearer-token-env-var <NAME>
29
+ Send "Authorization: Bearer \${NAME}"
30
+ --oauth-client-id <id> Pre-registered OAuth client id
31
+ --oauth-client-secret <secret>
32
+ OAuth client secret (may be \${NAME} or !command)
33
+ --oauth-callback-port <port>
34
+ Fixed OAuth callback port
35
+ --oauth-client-name <name>
36
+ Client name sent when registering with the OAuth server
37
+ --exposure <mode> codemode (default), deferred, direct, or hidden
38
+ --description <text> What the server offers, shown in the system prompt
39
+
40
+ Other options:
41
+ --json Print the list as JSON
42
+ --timeout <seconds> Time limit for the whole sign-in (default: 300)`,HELP_HINT=source_default.dim(`Use "${APP_NAME} mcp --help" for usage.`),DEFAULT_LOGIN_TIMEOUT_SECONDS=300;function errorMessage(error){return error instanceof Error?error.message:String(error)}function describeTransport(entry){let{config}=entry;return"url"in config?config.url:[config.command,...config.args??[]].join(" ")}function createConnection(entry,options,credentials){return new McpServerConnection({entry,cwd:options.cwd,createTransport:createDefaultTransport,credentials,log:new McpServerLog(join(options.agentDir,"mcp.log")),onTools:()=>{}})}var OPTION_ALIASES=new Map([["-l","--local"]]);function parseOptions(args,known,error,maxPositionals=Number.POSITIVE_INFINITY){let positional=[],values=new Map,lists=new Map;for(let index=0;index<args.length;index++){let arg=OPTION_ALIASES.get(args[index])??args[index];if(arg==="--"||positional.length>=maxPositionals){positional.push(...args.slice(arg==="--"?index+1:index));break}if(!arg.startsWith("--")){positional.push(arg);continue}let name=arg.slice(2),kind=known[name];if(!kind){error(`Unknown option ${arg}.
43
+ ${HELP_HINT}`);return}if(kind==="flag"){values.set(name,!0);continue}let value=args[++index];if(value===void 0){error(`${arg} needs a value.`);return}kind==="list"?lists.set(name,[...lists.get(name)??[],value]):values.set(name,value)}return{positional,values,lists}}async function runMcpCommand(args,options){let log=options.log??(line=>console.log(line)),error=options.error??(line=>console.error(line)),[command,...rest]=args;if(command===void 0||command==="help"||args.includes("--help")||args.includes("-h"))return log(HELP),0;let projectConfig=join(options.cwd,CONFIG_DIR_NAME,"mcp.json");if(command==="add"||command==="remove")return command==="add"?add(rest,projectConfig,options,log,error):remove(rest,projectConfig,options,log,error);let projectTrusted=new ProjectTrustStore(options.agentDir).get(options.cwd)===!0,loaded=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted}),untrustedNote=!projectTrusted&&existsSync(projectConfig)?`${projectConfig} is ignored because the project is not trusted. Start ${APP_NAME} in the project to trust it.`:void 0,credentials=options.credentials??new McpOAuthCredentialStore;switch(command){case"list":{let parsed=parseOptions(rest,{json:"flag"},error);return parsed?parsed.positional.length>0?(error(`Usage: ${APP_NAME} mcp list [--json]
44
+ ${HELP_HINT}`),1):list(loaded,parsed.values.has("json"),untrustedNote,options,credentials,log):1}case"login":case"logout":{let parsed=parseOptions(rest,command==="login"?{timeout:"value"}:{},error);if(!parsed)return 1;let[name,...extra]=parsed.positional;if(!name||extra.length>0)return error(`Usage: ${APP_NAME} mcp ${command} <server>
45
+ ${HELP_HINT}`),1;let entry=loaded.servers.find(server=>server.name===name);if(!entry)return error(`No MCP server named "${name}".${untrustedNote?` ${untrustedNote}`:""} Configured: ${loaded.servers.map(server=>server.name).join(", ")||"none"}.`),1;let connection=createConnection(entry,options,credentials),url=connection.oauthUrl;if(!url)return error(`MCP server "${name}" does not use OAuth. Only HTTP servers without an Authorization header do.`),1;if(command==="logout"){let removed=credentials.remove(name,url);return log(removed?`Signed out of MCP server "${name}".`:`No stored credentials for MCP server "${name}".`),0}let timeout=Number(parsed.values.get("timeout")??DEFAULT_LOGIN_TIMEOUT_SECONDS);if(!Number.isFinite(timeout)||timeout<=0)return error("--timeout must be a positive number of seconds."),1;try{return await login(entry,connection,url,timeout*1e3,options,credentials,log,error)}finally{await connection.close()}}default:return error(`Unknown mcp command "${command}".
46
+ ${HELP_HINT}`),1}}function parsePairs(option,pairs,error){if(!pairs)return{};let record={};for(let pair of pairs){let separator=pair.indexOf("=");if(separator<=0){error(`--${option} expects KEY=VALUE, got "${pair}".`);return}record[pair.slice(0,separator)]=pair.slice(separator+1)}return record}function add(args,projectConfig,options,log,error){let usage=`Usage: ${APP_NAME} mcp add <server> [options] (--url <url> | -- <command> [args...])
47
+ ${HELP_HINT}`,parsed=parseOptions(args,{local:"flag",url:"value",env:"list",cwd:"value",header:"list","bearer-token-env-var":"value","oauth-client-id":"value","oauth-client-secret":"value","oauth-callback-port":"value","oauth-client-name":"value",exposure:"value",description:"value"},error,2);if(!parsed)return 1;let{positional,values,lists}=parsed,[name,...command]=positional,url=values.get("url");if(!name||url===void 0==(command.length===0))return error(usage),1;let value=option=>{let found=values.get(option);return typeof found=="string"?found:void 0},exposure=value("exposure"),misplaced=(url===void 0?["header","bearer-token-env-var","oauth-client-id","oauth-client-secret","oauth-callback-port","oauth-client-name"]:["env","cwd"]).find(option=>values.has(option)||lists.has(option));if(misplaced)return error(`--${misplaced} only applies to ${url===void 0?"HTTP servers (--url)":"stdio servers"}.`),1;let config;if(typeof url=="string"){let headers=parsePairs("header",lists.get("header"),error);if(!headers)return 1;let bearer=value("bearer-token-env-var");bearer!==void 0&&(headers.Authorization=`Bearer \${${bearer}}`);let port=value("oauth-callback-port"),oauth={...value("oauth-client-id")===void 0?{}:{clientId:value("oauth-client-id")},...value("oauth-client-secret")===void 0?{}:{clientSecret:value("oauth-client-secret")},...port===void 0?{}:{callbackPort:Number(port)},...value("oauth-client-name")===void 0?{}:{clientName:value("oauth-client-name")}};config={url,...Object.keys(headers).length>0?{headers}:{},...Object.keys(oauth).length>0?{oauth}:{}}}else{let env=parsePairs("env",lists.get("env"),error);if(!env)return 1;let[executable,...commandArgs]=command;config={command:executable,...commandArgs.length>0?{args:commandArgs}:{},...Object.keys(env).length>0?{env}:{},...value("cwd")===void 0?{}:{cwd:value("cwd")}}}exposure!==void 0&&(config.exposure=exposure);let description=value("description");description!==void 0&&(config.description=description);let validated=validateMcpServerConfig(name,config);if(typeof validated=="string")return error(validated),1;let project=values.has("local"),path=project?projectConfig:join(options.agentDir,"mcp.json"),scope=project?"project":"global",replaced;try{replaced=addMcpServerConfig(path,name,validated)}catch(addError){return error(`Could not update ${path}: ${errorMessage(addError)}`),1}log(`${replaced?"Replaced":"Added"} ${scope} MCP server "${name}" in ${path}.`),project&&new ProjectTrustStore(options.agentDir).get(options.cwd)!==!0&&log(`The project is not trusted, so ${path} is ignored until you start ${APP_NAME} in the project and trust it.`);let mayNeedSignIn="url"in validated&&!Object.keys(validated.headers??{}).some(header=>header.toLowerCase()==="authorization");return log(`Check it with: ${APP_NAME} mcp list${mayNeedSignIn?`. If it requires sign-in: ${APP_NAME} mcp login ${name}`:""}`),0}function remove(args,projectConfig,options,log,error){let parsed=parseOptions(args,{local:"flag"},error);if(!parsed)return 1;let[name,...extra]=parsed.positional;if(!name||extra.length>0)return error(`Usage: ${APP_NAME} mcp remove <server> [-l]
48
+ ${HELP_HINT}`),1;let project=parsed.values.has("local"),globalConfig=join(options.agentDir,"mcp.json"),path=project?projectConfig:globalConfig,scope=project?"project":"global",removed;try{removed=removeMcpServerConfig(path,name)}catch(removeError){return error(`Could not update ${path}: ${errorMessage(removeError)}`),1}if(removed)return log(`Removed ${scope} MCP server "${name}" from ${path}.`),0;let other=loadMcpConfig({agentDir:options.agentDir,cwd:options.cwd,projectTrusted:!0}).servers.find(server=>server.name===name&&server.scope!==scope);return error(`No ${scope} MCP server named "${name}" in ${path}.${other?` It is defined in ${other.source}${other.scope==="project"?"; use --local":"; omit --local"}.`:""}`),1}async function list(loaded,json,untrustedNote,options,credentials,log){let reports=await Promise.all(loaded.servers.map(async entry=>{let report={name:entry.name,scope:entry.scope??"global",source:entry.source,...entry.override?{override:entry.override}:{},enabled:entry.config.enabled!==!1,exposure:entry.config.exposure??"codemode",transport:describeTransport(entry),state:"disabled",tools:[]};if(!report.enabled)return report;let connection=createConnection(entry,options,credentials);try{await connection.getClient()}catch{}report.state=connection.state,report.tools=connection.tools.map(tool=>tool.name);let overrides=connection.tools.flatMap(tool=>{let exposure=getMcpToolExposure(entry.config,tool.name);return exposure===report.exposure?[]:[[tool.name,exposure]]});return overrides.length>0&&(report.toolExposure=Object.fromEntries(overrides)),connection.hasResources&&(report.resources=!0),connection.state!=="connected"&&connection.error&&(report.error=connection.error),await connection.close(),report})),failed=loaded.errors.length>0||reports.some(report=>report.enabled&&report.state!=="connected");if(json)return log(JSON.stringify({servers:reports,errors:loaded.errors,...untrustedNote?{note:untrustedNote}:{}},null,2)),failed?1:0;reports.length===0&&loaded.errors.length===0&&log(`No MCP servers configured. Add them to ${join(options.agentDir,"mcp.json")} or .pi/mcp.json.`);for(let report of reports){let state=report.state==="connected"?`connected, ${report.tools.length} tool${report.tools.length===1?"":"s"}`:report.state==="needs-auth"?"needs sign-in":report.state;if(log(`${report.name}: ${state} (${report.exposure}, ${report.scope})`),log(` ${report.transport}`),report.override&&log(` project override: ${report.override}`),report.state==="needs-auth"&&log(` sign in with: ${APP_NAME} mcp login ${report.name}`),report.tools.length>0){let tools=report.tools.map(tool=>{let exposure=report.toolExposure?.[tool];return exposure?`${tool} [${exposure}]`:tool});log(` tools: ${tools.join(", ")}`)}report.resources&&log(" offers resources"),report.error&&log(` ${report.error.split(`
49
+ `).join(`
50
+ `)}`)}for(let configError of loaded.errors)log(`config error: ${configError}`);return untrustedNote&&log(untrustedNote),failed?1:0}async function login(entry,connection,url,timeoutMs,options,credentials,log,error){let{name}=entry;try{return await connection.getClient(),log(`Already signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}catch{if(connection.state!=="needs-auth")return error(`MCP server "${name}" failed to connect: ${connection.error??"unknown error"}`),1}let openUrl=options.openUrl??openBrowser,interactive=process.stdin.isTTY===!0&&options.openUrl===void 0;try{await signInMcpServer({serverUrl:url,store:credentials.forServer(name,url),settings:connection.oauthSettings(),challenge:connection.challenge,prompt:{showAuthorizationUrl:authorizationUrl=>{log(`Sign in to MCP server "${name}" in your browser:
51
+ ${authorizationUrl.href}`),openUrl(authorizationUrl.href)},promptForRedirectUrl:signal=>waitForRedirectUrl(signal,interactive)},signal:AbortSignal.timeout(timeoutMs)})}catch(signInError){return error(signInError instanceof McpSignInCancelledError?`Sign-in to MCP server "${name}" was cancelled or not completed within ${Math.round(timeoutMs/1e3)} seconds.`:`Sign-in to MCP server "${name}" failed: ${errorMessage(signInError)}`),1}connection.challenge=void 0;try{await connection.reconnect()}catch(connectError){return error(`Signed in, but ${errorMessage(connectError)}`),1}return log(`Signed in to MCP server "${name}" (${connection.tools.length} tools).`),0}async function waitForRedirectUrl(signal,interactive){if(!interactive){signal.aborted||await new Promise(resolve=>signal.addEventListener("abort",resolve,{once:!0}));return}let readline=createInterface({input:process.stdin,output:process.stderr});try{return await readline.question("If the browser cannot reach this machine, paste the URL it was redirected to: ",{signal})}catch{return}finally{readline.close()}}export{runMcpCommand};