blade-code 0.10.94 → 0.10.95

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 (69) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-nahy2t67.js → chunk-09ya3a21.js} +1 -1
  3. package/dist/{chunk-fts2cp88.js → chunk-2f0wn3ne.js} +1 -1
  4. package/dist/{chunk-v5c34zya.js → chunk-2ge1zqts.js} +1 -1
  5. package/dist/{chunk-5hh577nr.js → chunk-2zzc7g29.js} +1 -1
  6. package/dist/{chunk-wxm2zjs9.js → chunk-3aayczyy.js} +1 -1
  7. package/dist/{chunk-0z3c8p6d.js → chunk-4fmyjf1x.js} +1 -1
  8. package/dist/chunk-4hb71f98.js +1 -0
  9. package/dist/{chunk-pkcvxa1z.js → chunk-4p69xraf.js} +1 -1
  10. package/dist/{chunk-zgd524h0.js → chunk-4smdhn1h.js} +1 -1
  11. package/dist/{chunk-kfmpnq2r.js → chunk-871g570t.js} +255 -255
  12. package/dist/{chunk-088bnp26.js → chunk-8pvsw4gw.js} +1 -1
  13. package/dist/{chunk-0ytp28pf.js → chunk-bd4nqrtm.js} +1 -1
  14. package/dist/{chunk-b5bwg47r.js → chunk-bxtqcgvs.js} +1 -1
  15. package/dist/{chunk-vnnxvpnn.js → chunk-cbafxem4.js} +1 -1
  16. package/dist/{chunk-076txzms.js → chunk-cnnht4m3.js} +1 -1
  17. package/dist/{chunk-kp6cjt82.js → chunk-cvybf60x.js} +1 -1
  18. package/dist/{chunk-xdvjwtfc.js → chunk-e5ht9d18.js} +1 -1
  19. package/dist/{chunk-reb25993.js → chunk-eqbcxa12.js} +1 -1
  20. package/dist/{chunk-rvpveaf3.js → chunk-es4evt6m.js} +1 -1
  21. package/dist/{chunk-73hasjfg.js → chunk-esstp9h0.js} +2 -2
  22. package/dist/{chunk-216xzne9.js → chunk-f66cptes.js} +1 -1
  23. package/dist/chunk-gnzcz6e1.js +1 -0
  24. package/dist/{chunk-gzv143jr.js → chunk-h2a3edj4.js} +1 -1
  25. package/dist/{chunk-8488pkzv.js → chunk-hajer580.js} +1 -1
  26. package/dist/{chunk-4rw9kt3s.js → chunk-hfd00skc.js} +1 -1
  27. package/dist/{chunk-bbvw06fr.js → chunk-hqb6qxzj.js} +1 -1
  28. package/dist/{chunk-939sa81a.js → chunk-hrpqz2jv.js} +1 -1
  29. package/dist/{chunk-zd410m70.js → chunk-ktt7vmqz.js} +1 -1
  30. package/dist/{chunk-k40dje0b.js → chunk-qp165b79.js} +1 -1
  31. package/dist/{chunk-7cx577bv.js → chunk-rjw8pj7t.js} +1 -1
  32. package/dist/{chunk-0538yd6h.js → chunk-rrav5aea.js} +1 -1
  33. package/dist/chunk-s2erwc49.js +8 -0
  34. package/dist/{chunk-5qanqw0d.js → chunk-sckqp0t9.js} +1 -1
  35. package/dist/{chunk-cd2xwddv.js → chunk-vt99w0vh.js} +1 -1
  36. package/dist/{chunk-zkxszt12.js → chunk-vxwqsmqg.js} +1 -1
  37. package/dist/{chunk-k8c48qxn.js → chunk-wwzc3ryj.js} +1 -1
  38. package/dist/{chunk-11fmyrjt.js → chunk-xm8w4jaa.js} +1 -1
  39. package/dist/web/assets/{ChatView-DacNycYI.js → ChatView-CpKiglLV.js} +7 -7
  40. package/dist/web/assets/{CodeBlockHighlighter-CevKBV7g.js → CodeBlockHighlighter-BzmHeWKU.js} +1 -1
  41. package/dist/web/assets/FilePreview-uShTCL2_.js +59 -0
  42. package/dist/web/assets/{KanbanBoard-C9620zMQ.js → KanbanBoard-CnZoKZFy.js} +2 -2
  43. package/dist/web/assets/{MarkdownRenderer-DR0tbtqc.js → MarkdownRenderer-CxcqGo57.js} +3 -3
  44. package/dist/web/assets/{SettingsModal-C_TpGMs0.js → SettingsModal-Bu5uH8ic.js} +2 -2
  45. package/dist/web/assets/{TaskSwitcher-CGWELaxg.js → TaskSwitcher-BDwk7i6w.js} +6 -6
  46. package/dist/web/assets/{TerminalPanel-DPxm68h1.js → TerminalPanel-PiLhnW-8.js} +2 -2
  47. package/dist/web/assets/{arrow-left-n3ENbaSb.js → arrow-left-B7RwOx8T.js} +1 -1
  48. package/dist/web/assets/{calendar-clock-C2E8mlWS.js → calendar-clock-BeSXiMFw.js} +1 -1
  49. package/dist/web/assets/{chevrons-up-down-DgOF3xz6.js → chevrons-up-down-DuC8PppK.js} +1 -1
  50. package/dist/web/assets/{clock-3-D9h1svFg.js → clock-3-lYrt_Amt.js} +1 -1
  51. package/dist/web/assets/{external-link-kvylbcSF.js → external-link-BTHyQJWk.js} +1 -1
  52. package/dist/web/assets/{folder-C_KPQmg6.js → folder-CX6zAF9w.js} +1 -1
  53. package/dist/web/assets/{index-DI8ZWdWH.js → index-B5mUEr6D.js} +3 -3
  54. package/dist/web/assets/{index-D11FYWsc.js → index-FdbcPJSj.js} +56 -56
  55. package/dist/web/assets/index-zY4JU9fd.css +1 -0
  56. package/dist/web/assets/{pause-hCE9Bvm9.js → pause-qlDcCjBJ.js} +1 -1
  57. package/dist/web/assets/{play-BpCmIsMH.js → play-BGPTTFWa.js} +1 -1
  58. package/dist/web/assets/session-events-Ci1823tS.js +22 -0
  59. package/dist/web/assets/{teamService-7LNlaq8e.js → teamService-Bk8B4hZp.js} +1 -1
  60. package/dist/web/assets/{vendor-radix-DXRuAJHH.js → vendor-radix-Bc1_Q9tz.js} +1 -1
  61. package/dist/web/assets/{vendor-react-DG5dkZ_t.js → vendor-react-DofNRwfy.js} +1 -1
  62. package/dist/web/index.html +5 -5
  63. package/package.json +1 -1
  64. package/dist/chunk-fc7dbcad.js +0 -1
  65. package/dist/chunk-h9ww5k16.js +0 -1
  66. package/dist/chunk-k3crvmvt.js +0 -8
  67. package/dist/web/assets/FilePreview-DiS4nCrp.js +0 -54
  68. package/dist/web/assets/index-C8M-7zAh.css +0 -1
  69. package/dist/web/assets/session-events-qDVUI3Ca.js +0 -22
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{re as W}from"./chunk-nahy2t67.js";import{ue as F,ve as M}from"./chunk-ztp2ff01.js";import"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Hh as N,Ih as B}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{hi as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import{Qi as J}from"./chunk-nh45xp7r.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-5qanqw0d.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-k8c48qxn.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-d45gd36e.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-4rw9kt3s.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-5hh577nr.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-wxm2zjs9.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-fc7dbcad.js"),import("./chunk-bbvw06fr.js"),import("./chunk-dwttn5xg.js"),import("./chunk-73hasjfg.js"),import("./chunk-va1exak5.js"),import("./chunk-0ytp28pf.js"),import("./chunk-epmxrw4f.js"),import("./chunk-am66822r.js"),import("./chunk-11fmyrjt.js"),import("./chunk-b5bwg47r.js"),import("./chunk-216xzne9.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
2
+ import{re as W}from"./chunk-09ya3a21.js";import{ue as F,ve as M}from"./chunk-ztp2ff01.js";import"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Hh as N,Ih as B}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{hi as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import{Qi as J}from"./chunk-nh45xp7r.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-sckqp0t9.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-wwzc3ryj.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-d45gd36e.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-hfd00skc.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-2zzc7g29.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-3aayczyy.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-4hb71f98.js"),import("./chunk-hqb6qxzj.js"),import("./chunk-dwttn5xg.js"),import("./chunk-esstp9h0.js"),import("./chunk-va1exak5.js"),import("./chunk-bd4nqrtm.js"),import("./chunk-epmxrw4f.js"),import("./chunk-am66822r.js"),import("./chunk-xm8w4jaa.js"),import("./chunk-bxtqcgvs.js"),import("./chunk-f66cptes.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-h9ww5k16.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-rvpveaf3.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-gnzcz6e1.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-es4evt6m.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
@@ -1,4 +1,4 @@
1
- import{He as N}from"./chunk-reb25993.js";import{jg as $}from"./chunk-gzv143jr.js";import{Ih as _}from"./chunk-qa4efys0.js";import{gi as Y,ii as Z}from"./chunk-h4j0nve8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{He as N}from"./chunk-eqbcxa12.js";import{jg as $}from"./chunk-h2a3edj4.js";import{Ih as _}from"./chunk-qa4efys0.js";import{gi as Y,ii as Z}from"./chunk-h4j0nve8.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as pe,y as qe,j as re,C as se};
@@ -1,4 +1,4 @@
1
- import{Wb as Xt,Xb as fn,Yb as yn,Zb as En}from"./chunk-ya5p7mx7.js";import{jg as Bt}from"./chunk-gzv143jr.js";import{Ag as dn,Bg as on,Cg as pn,Dg as lt,Eg as cn,Fg as un,Gg as Mn,Ig as S,Lg as wn,Mg as Gt,Ng as Ut,Og as h,Pg as Ht,og as gt,pg as vi,qg as sn,rg as zt,sg as U,tg as en,ug as xt,vg as mt,xg as rn,yg as Tn,zg as B}from"./chunk-pkcvxa1z.js";import{uh as X,wh as g}from"./chunk-7dqh8bqm.js";import{Ih as It}from"./chunk-qa4efys0.js";import{wi as tn,xi as nn}from"./chunk-cd2xwddv.js";import{Qi as ns}from"./chunk-nh45xp7r.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Wb as Xt,Xb as fn,Yb as yn,Zb as En}from"./chunk-ya5p7mx7.js";import{jg as Bt}from"./chunk-h2a3edj4.js";import{Ag as dn,Bg as on,Cg as pn,Dg as lt,Eg as cn,Fg as un,Gg as Mn,Ig as S,Lg as wn,Mg as Gt,Ng as Ut,Og as h,Pg as Ht,og as gt,pg as vi,qg as sn,rg as zt,sg as U,tg as en,ug as xt,vg as mt,xg as rn,yg as Tn,zg as B}from"./chunk-4p69xraf.js";import{uh as X,wh as g}from"./chunk-7dqh8bqm.js";import{Ih as It}from"./chunk-qa4efys0.js";import{wi as tn,xi as nn}from"./chunk-vt99w0vh.js";import{Qi as ns}from"./chunk-nh45xp7r.js";import{EventEmitter as bs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,2 +1,2 @@
1
- import{wi as d,yi as h}from"./chunk-cd2xwddv.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{wi as d,yi as h}from"./chunk-vt99w0vh.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as je,w as ke};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-0z3c8p6d.js";import{$ as y,T as M}from"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import"./chunk-fts2cp88.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-7cx577bv.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-v5c34zya.js";import{le as I,me as S,ne as v}from"./chunk-xdvjwtfc.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import"./chunk-pkcvxa1z.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-4fmyjf1x.js";import{$ as y,T as M}from"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import"./chunk-2f0wn3ne.js";import"./chunk-8eh0vp98.js";import{Cb as h,Lb as A}from"./chunk-rjw8pj7t.js";import"./chunk-ya5p7mx7.js";import{Nd as U,zd as w}from"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{je as C}from"./chunk-2ge1zqts.js";import{le as I,me as S,ne as v}from"./chunk-e5ht9d18.js";import{oe as O}from"./chunk-wbfa6xce.js";import"./chunk-ztp2ff01.js";import{Le as P}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import"./chunk-zj4kfyer.js";import"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import"./chunk-ktt7vmqz.js";import"./chunk-yjh47zv6.js";import"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import"./chunk-4p69xraf.js";import{sh as F}from"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import{Ih as z}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,4 +1,4 @@
1
- import{s as hz,t as Sz}from"./chunk-076txzms.js";import{u as b}from"./chunk-0538yd6h.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-k40dje0b.js";import{$ as jz,G as N,O as $z,P as Qz,T as Wz,W as Yz,X as Hz,pa as Fz,qa as Uz,ra as Vz,sa as wz}from"./chunk-kfmpnq2r.js";import"./chunk-z5rtzcm4.js";import{Ga as Tz}from"./chunk-fts2cp88.js";import{Ia as Zz}from"./chunk-8eh0vp98.js";import{Cb as zz,Lb as Jz,qb as e}from"./chunk-7cx577bv.js";import{Wb as I}from"./chunk-ya5p7mx7.js";import{Ad as s,Cd as x,Fd as t,Kd as q,Nd as U,_c as l,id as i,jd as r,od as a,rd as o,td as n,zd as C}from"./chunk-vnnxvpnn.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as Mz}from"./chunk-nahy2t67.js";import"./chunk-ztp2ff01.js";import{Le as Nz,Me as Ez}from"./chunk-reb25993.js";import"./chunk-v508x7cg.js";import{Xe as f}from"./chunk-zj4kfyer.js";import{af as v}from"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import{lf as xz}from"./chunk-z6xfknxe.js";import"./chunk-zkxszt12.js";import"./chunk-zd410m70.js";import"./chunk-yjh47zv6.js";import{bg as bz}from"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-gzv143jr.js";import"./chunk-74yge4ka.js";import{Vg as qz,Yg as Pz}from"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as S,Bh as d,Dh as M,Eh as k}from"./chunk-d83bfr0b.js";import{Ih as Oz}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{ii as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import{pi as Az,si as Rz}from"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as m}from"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as hz,t as Sz}from"./chunk-cnnht4m3.js";import{u as b}from"./chunk-rrav5aea.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-qp165b79.js";import{$ as jz,G as N,O as $z,P as Qz,T as Wz,W as Yz,X as Hz,pa as Fz,qa as Uz,ra as Vz,sa as wz}from"./chunk-871g570t.js";import"./chunk-z5rtzcm4.js";import{Ga as Tz}from"./chunk-2f0wn3ne.js";import{Ia as Zz}from"./chunk-8eh0vp98.js";import{Cb as zz,Lb as Jz,qb as e}from"./chunk-rjw8pj7t.js";import{Wb as I}from"./chunk-ya5p7mx7.js";import{Ad as s,Cd as x,Fd as t,Kd as q,Nd as U,_c as l,id as i,jd as r,od as a,rd as o,td as n,zd as C}from"./chunk-cbafxem4.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as Mz}from"./chunk-09ya3a21.js";import"./chunk-ztp2ff01.js";import{Le as Nz,Me as Ez}from"./chunk-eqbcxa12.js";import"./chunk-v508x7cg.js";import{Xe as f}from"./chunk-zj4kfyer.js";import{af as v}from"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import{lf as xz}from"./chunk-z6xfknxe.js";import"./chunk-vxwqsmqg.js";import"./chunk-ktt7vmqz.js";import"./chunk-yjh47zv6.js";import{bg as bz}from"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-h2a3edj4.js";import"./chunk-74yge4ka.js";import{Vg as qz,Yg as Pz}from"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as S,Bh as d,Dh as M,Eh as k}from"./chunk-d83bfr0b.js";import{Ih as Oz}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{ii as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import{pi as Az,si as Rz}from"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as m}from"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function pz(z){if(!v(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...i("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Gz({maxPendingItems:Xz,maxPendingBytes:Dz,writeTimeoutMs:Lz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return jz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?uz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Wz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(D)=>Q.onOutput?.("stdout",D)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Uz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=e.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:D}=W.properties,X=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof D==="string"&&Qz(X,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(D,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:X});if(!L?.accepted)return;if(await new $z(Q,m()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!n(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of gz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=!1,X,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(D)L(B);else X=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),D=!0,X)L(X);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,D)},complete:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,D)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),X=await D.completion,L=(await b.list(this.cwd,this.id)).find((F)=>F.start.reviewId===D.reviewId);if(!L)throw Error(`Review not found: ${D.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:D.reviewId,status:X.status,findings:X.findings.length,content:l(L.start,X)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,D)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(D);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Vz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=wz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Zz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController,X=!1,L,F=new Promise((B)=>{L=B});this.pendingPrompt=D,this.pendingPromptCompletion=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Fz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,D.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await zz(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let P=JSON.parse(V.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")w=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,kz=Hz(o(Yz(K,O),a));R.push({type:"content",content:{type:"text",text:kz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let P=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:P,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -1,4 +1,4 @@
1
- import{pa as F,ra as L}from"./chunk-kfmpnq2r.js";import{Dd as $,Fd as B,Nd as Q}from"./chunk-vnnxvpnn.js";import{Nf as y}from"./chunk-zd410m70.js";import{Ih as V}from"./chunk-qa4efys0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{pa as F,ra as L}from"./chunk-871g570t.js";import{Dd as $,Fd as B,Nd as Q}from"./chunk-cbafxem4.js";import{Nf as y}from"./chunk-ktt7vmqz.js";import{Ih as V}from"./chunk-qa4efys0.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{j as m,I as n,M as o,R as p,_ as q,C as r};
@@ -0,0 +1 @@
1
+ import{je as a,ke as b}from"./chunk-2ge1zqts.js";import"./chunk-vt99w0vh.js";import"./chunk-nh45xp7r.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{th as Y}from"./chunk-t48zm299.js";import{uh as on,vh as F,wh as o}from"./chunk-7dqh8bqm.js";import{Ah as ct,Bh as bt}from"./chunk-d83bfr0b.js";import{Ih as x}from"./chunk-qa4efys0.js";import{$h as Ht,Jh as Jn,Kh as Xt,Lh as pt,Ph as gt,Qh as kn,Rh as it,Sh as Rt,Th as Ct,Uh as un,Vh as zt,Wh as Bt,Xh as On,Yh as Kt,Zh as Ut,_h as jn,ai as Yt,bi as qt,ci as Vt,di as Qt,ei as Gt}from"./chunk-hrfh7wck.js";import{ii as fn}from"./chunk-h4j0nve8.js";import{li as $t,oi as J}from"./chunk-w63dfcx5.js";import{wi as Pn,xi as Ln}from"./chunk-cd2xwddv.js";import{Di as h}from"./chunk-rzja9zza.js";import{Oi as Tn}from"./chunk-na1cney5.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{th as Y}from"./chunk-t48zm299.js";import{uh as on,vh as F,wh as o}from"./chunk-7dqh8bqm.js";import{Ah as ct,Bh as bt}from"./chunk-d83bfr0b.js";import{Ih as x}from"./chunk-qa4efys0.js";import{$h as Ht,Jh as Jn,Kh as Xt,Lh as pt,Ph as gt,Qh as kn,Rh as it,Sh as Rt,Th as Ct,Uh as un,Vh as zt,Wh as Bt,Xh as On,Yh as Kt,Zh as Ut,_h as jn,ai as Yt,bi as qt,ci as Vt,di as Qt,ei as Gt}from"./chunk-hrfh7wck.js";import{ii as fn}from"./chunk-h4j0nve8.js";import{li as $t,oi as J}from"./chunk-w63dfcx5.js";import{wi as Pn,xi as Ln}from"./chunk-vt99w0vh.js";import{Di as h}from"./chunk-rzja9zza.js";import{Oi as Tn}from"./chunk-na1cney5.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1 +1 @@
1
- import{nf as a,of as b,pf as c}from"./chunk-zkxszt12.js";import"./chunk-pkcvxa1z.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-cd2xwddv.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{nf as a,of as b,pf as c}from"./chunk-vxwqsmqg.js";import"./chunk-4p69xraf.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import"./chunk-d83bfr0b.js";import"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import"./chunk-n4gtzx4x.js";import"./chunk-vt99w0vh.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};