blade-code 0.10.13 → 0.10.15

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 (54) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-j8fkhkan.js → chunk-09k2b1tw.js} +1 -1
  3. package/dist/{chunk-x9t4ryyf.js → chunk-0z7rg4f3.js} +1 -1
  4. package/dist/{chunk-ke4n1nv5.js → chunk-1amhvwmj.js} +20 -20
  5. package/dist/chunk-1c9rkm57.js +1 -0
  6. package/dist/{chunk-097zrzyy.js → chunk-25abj6rx.js} +1 -1
  7. package/dist/{chunk-c9m16hqc.js → chunk-2cqsqrxx.js} +1 -1
  8. package/dist/{chunk-hf3dwmfa.js → chunk-3m8pschr.js} +1 -1
  9. package/dist/{chunk-8p5a371t.js → chunk-5psydp1v.js} +1 -1
  10. package/dist/{chunk-zgg0y0sy.js → chunk-5tpjb8yn.js} +1 -1
  11. package/dist/{chunk-pmz455nq.js → chunk-5wecprcp.js} +1 -1
  12. package/dist/chunk-67vf8r5v.js +6 -0
  13. package/dist/{chunk-nsxkd8bq.js → chunk-6y9w5296.js} +1 -1
  14. package/dist/{chunk-5wnxafpf.js → chunk-7bq9p4ab.js} +1 -1
  15. package/dist/{chunk-cy6emyt9.js → chunk-7x5cqfy7.js} +1 -1
  16. package/dist/{chunk-0q7pvmvz.js → chunk-a170cgzr.js} +1 -1
  17. package/dist/{chunk-74wm5qnw.js → chunk-afxpp33r.js} +1 -1
  18. package/dist/{chunk-cx0tdprs.js → chunk-agdamn30.js} +1 -1
  19. package/dist/{chunk-97fyx4hr.js → chunk-csn0epd2.js} +1 -1
  20. package/dist/chunk-d7976m5f.js +5 -0
  21. package/dist/{chunk-ab4sp3m4.js → chunk-eav8jpk1.js} +2 -2
  22. package/dist/{chunk-c477j84k.js → chunk-ee7an1kq.js} +1 -1
  23. package/dist/{chunk-9ac3eajy.js → chunk-jjy8sg10.js} +1 -1
  24. package/dist/{chunk-8yypkbew.js → chunk-k47f7zqm.js} +1 -1
  25. package/dist/{chunk-k653znk8.js → chunk-m4f213hk.js} +1 -1
  26. package/dist/{chunk-p42cz164.js → chunk-mc29y7tj.js} +24 -24
  27. package/dist/{chunk-820ek28g.js → chunk-n72www7h.js} +3 -3
  28. package/dist/{chunk-4em4jxj5.js → chunk-nfqsnkbt.js} +47 -47
  29. package/dist/{chunk-kfgv64hg.js → chunk-ng8a4btc.js} +1 -1
  30. package/dist/{chunk-7s99zkve.js → chunk-qpd1jmm4.js} +1 -1
  31. package/dist/{chunk-45wpygt9.js → chunk-t6cmqsdj.js} +1 -1
  32. package/dist/{chunk-9cnm1hgp.js → chunk-wz3z8908.js} +1 -1
  33. package/dist/{chunk-nysyp11q.js → chunk-x1qw695m.js} +3 -3
  34. package/dist/{chunk-a3mwn9zj.js → chunk-zmg66vp7.js} +1 -1
  35. package/dist/{chunk-5vgjhqk9.js → chunk-zn2cec1d.js} +1 -1
  36. package/dist/{chunk-xjyctv33.js → chunk-zn7c21zj.js} +7 -7
  37. package/dist/web/assets/ChatView-rHWZ9qCy.js +7 -0
  38. package/dist/web/assets/{CodeBlockHighlighter-GS19h8wb.js → CodeBlockHighlighter-KpN8jpS4.js} +2 -2
  39. package/dist/web/assets/{FilePreview-BIjFuDdg.js → FilePreview-BbEcYewq.js} +3 -3
  40. package/dist/web/assets/{MarkdownRenderer-D-NrQgb1.js → MarkdownRenderer-Cpqkv5Ml.js} +3 -3
  41. package/dist/web/assets/{SettingsModal-BNz9vyER.js → SettingsModal-D6NZP8vM.js} +2 -2
  42. package/dist/web/assets/TaskSwitcher-cT1qKR6s.js +1 -0
  43. package/dist/web/assets/TerminalPanel-0MehdzKr.js +1 -0
  44. package/dist/web/assets/index-BYd4kNGp.js +11 -0
  45. package/dist/web/assets/session-events-BH7O5JJl.js +22 -0
  46. package/dist/web/index.html +2 -1
  47. package/package.json +1 -1
  48. package/dist/chunk-ah97bmns.js +0 -5
  49. package/dist/chunk-j4rfyz81.js +0 -6
  50. package/dist/chunk-m6sg36pw.js +0 -1
  51. package/dist/web/assets/ChatView-ucu62nNl.js +0 -7
  52. package/dist/web/assets/TaskSwitcher-HnRA3Mj8.js +0 -1
  53. package/dist/web/assets/TerminalPanel-Df2CK9n_.js +0 -1
  54. package/dist/web/assets/index-DWTihvUI.js +0 -32
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Ac as W}from"./chunk-a3mwn9zj.js";import{Dc as F,Ec as M}from"./chunk-ktf3bpmw.js";import"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import{de as T}from"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{hf as N,if as B}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as J}from"./chunk-g11hq0e5.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(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 c(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 m(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 t(){if(c(E)){let{getVersion:K}=await import("./chunk-nsxkd8bq.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-5vgjhqk9.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-fvrmjhz5.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-j4rfyz81.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-9ac3eajy.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-ke4n1nv5.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-m6sg36pw.js"),import("./chunk-7s99zkve.js"),import("./chunk-ab4sp3m4.js"),import("./chunk-74shfpve.js"),import("./chunk-0q7pvmvz.js"),import("./chunk-mtk2tf9n.js"),import("./chunk-4zs5r4n4.js"),import("./chunk-45wpygt9.js"),import("./chunk-xx1d9kfd.js"),import("./chunk-j8fkhkan.js")]),A=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(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).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),p&&Z.stack)console.error(`
2
+ import{Ac as W}from"./chunk-zmg66vp7.js";import{Dc as F,Ec as M}from"./chunk-ktf3bpmw.js";import"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import{de as T}from"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{hf as N,if as B}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as J}from"./chunk-g11hq0e5.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(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 c(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 m(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 t(){if(c(E)){let{getVersion:K}=await import("./chunk-6y9w5296.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-zn2cec1d.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-fvrmjhz5.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-67vf8r5v.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-jjy8sg10.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-1amhvwmj.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-1c9rkm57.js"),import("./chunk-qpd1jmm4.js"),import("./chunk-eav8jpk1.js"),import("./chunk-74shfpve.js"),import("./chunk-a170cgzr.js"),import("./chunk-mtk2tf9n.js"),import("./chunk-4zs5r4n4.js"),import("./chunk-t6cmqsdj.js"),import("./chunk-xx1d9kfd.js"),import("./chunk-09k2b1tw.js")]),A=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(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).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),p&&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,h=import("./chunk-hxp5qs1x.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-4em4jxj5.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t 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,h=import("./chunk-hxp5qs1x.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-nfqsnkbt.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
@@ -1,4 +1,4 @@
1
- import{f as Q,g as R,h as T,i as W}from"./chunk-820ek28g.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-74wm5qnw.js";import"./chunk-8yypkbew.js";import"./chunk-nysyp11q.js";import"./chunk-c477j84k.js";import"./chunk-p4zt7ts9.js";import"./chunk-p42cz164.js";import"./chunk-095x2ykj.js";import"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-k653znk8.js";import"./chunk-cx0tdprs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import{vf as J}from"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import b from"chalk";import H from"open";var $=`
1
+ import{f as Q,g as R,h as T,i as W}from"./chunk-n72www7h.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-afxpp33r.js";import"./chunk-k47f7zqm.js";import"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import{vf as J}from"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,2 +1,2 @@
1
- import{vf as d,xf as h}from"./chunk-cy6emyt9.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},"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{vf as d,xf as h}from"./chunk-7x5cqfy7.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},"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 sc,w as tc};
@@ -1,22 +1,22 @@
1
- import{r as R}from"./chunk-74wm5qnw.js";import{s as WJ}from"./chunk-8yypkbew.js";import{$ as a,F as p,I as m,J as d,L as l,Z as i,_ as r,aa as n,v as P}from"./chunk-nysyp11q.js";import{ka as zJ}from"./chunk-c477j84k.js";import"./chunk-p4zt7ts9.js";import{Va as g,Ya as c,hb as v}from"./chunk-p42cz164.js";import{sb as y}from"./chunk-095x2ykj.js";import{$b as B,Fb as C,Kb as O,Nb as f,Tb as T,Ub as u,Yb as q}from"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import{fd as QJ}from"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import{od as ZJ}from"./chunk-8j01ssaf.js";import"./chunk-k653znk8.js";import"./chunk-cx0tdprs.js";import"./chunk-9tnaads5.js";import{Td as $J}from"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import{ee as E}from"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import{cf as h,df as S,ef as I}from"./chunk-f4z3gkbs.js";import{if as s}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import{of as e,rf as JJ}from"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import{Readable as BJ,Writable as VJ}from"node:stream";import*as b from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as LJ}from"@agentclientprotocol/sdk";import t from"node:path";import{RequestError as FJ}from"@agentclientprotocol/sdk";import{nanoid as x}from"nanoid";var j=E("Agent");function k(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function GJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:k(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:k("headers"in J?J.headers:void 0)};return null}function XJ(J){let Z={};for(let Q of J){let W=GJ(Q);if(W)Z[Q.name]=W}return Z}function o(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function jJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:T(Z)}]:o(J.content)}function DJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class A{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,W,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=W;this.options=H;this.messages=[...H.initialMessages??[]],this.mode=this.mapPermissionModeToMode(H.permissionMode)}mapPermissionModeToMode(J){switch(J){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 l.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await B.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await B.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?XJ(this.options.mcpServers):void 0,Q=P.getInstance().getTerminalService(this.id);if(this.runtime=await p.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(z,$)=>{let G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await R.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await B.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await r(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of jJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.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(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!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($)=>{if(await this.setServiceTier($),!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($)=>{if(await this.setResponseVerbosity($),!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($)=>{if(await this.setCommunicationStyle($),!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($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,X,L=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},Y=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(D)=>{if(F)L(D);else X=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.session.id,status:"in_progress",title:`Resuming ${Y.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${Y.source.id} at depth ${Y.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,X)L(X);return Y}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await R.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(Y)=>{if(Y.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.toolCall.id,status:"in_progress",title:`Review: ${Y.toolCall.function.name}`,content:[],kind:this.mapToolKind(Y.toolKind)});else if(Y.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.toolCall.id,status:Y.result.success?"completed":"failed",content:[]})}}),X=await F.completion,L=(await R.list(this.cwd,this.id)).find((Y)=>Y.start.reviewId===F.reviewId);if(!L)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await B.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:X.status,findings:X.findings.length,content:C(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:L})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},W=await a(J,Q),H=W.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages];if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages)this.messages=[...W.data.compactedMessages];let z=W.content||W.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return{stopReason:W.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],W=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),j.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),W=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=f(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)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 F=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),i(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Y)=>{this.mode=this.mapPermissionModeToMode(Y),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}},X=await g(this.agent.chatStream(W,F,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(Y)=>{switch(Y.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let D=Y.toolCall,U=D.function.name;if(U===O)break;let _=this.mapToolKind(Y.toolKind),V=`Executing ${U}`;if(U==="Task"&&"function"in D)try{let N=JSON.parse(D.function.arguments),w=N.resume_from??N.resume;if(typeof w==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:V,content:[],kind:_});break}case"tool_progress":{let D=Y.toolCall;if(D.function.name===O)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Y.update.message}}]});break}case"tool_result":{let D=Y.toolCall;if(D.function.name===O)break;let U=Y.result,_=[],V=U.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;_.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))_.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=D.function.name,YJ=d(m(w,U));_.push({type:"content",content:{type:"text",text:YJ}})}if(D.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))_.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=U.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:N,content:_});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Y.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
3
- `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Y.contentKind} r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
4
- `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Y.revision} (${Y.serverName}): ${Y.uri}
5
- `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Y.revision} (${Y.serverName}): ${Y.phase} ${Y.attempt}/${Y.maxAttempts}
6
- `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Y.revision} (${Y.serverName}) ${Y.level}${Y.logger?` logger=${Y.logger}`:""}: ${Y.message}
7
- `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Y.revision} (${Y.serverName}): ${Y.action}${Y.detailsOmitted?" details-omitted":""}
8
- `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Y.revision} ${Y.taskId} (${Y.serverName}/${Y.toolName}): ${Y.status}${Y.hasResult?" result-available":""}
9
- `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Y.files.length}${Y.blockedWrite?" (write retry required)":""}
10
- `}});break;case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let D of Y.messages){if(!D.recovered||D.persisted)continue;for(let U of o(D.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:U})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
11
- `}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;default:break}});if(this.messages=[...F.messages],!X.success){let Y=X.error?.type??"unknown";throw FJ.internalError({failureType:Y},`Agent turn failed (${Y})`)}if(G.signal.aborted)return{stopReason:"cancelled"};let L={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let W,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(W=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=T($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?DJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((W)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,W)})}cancel(){j.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)j.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",W=this.mapModeIdToPermissionMode(Q);await B.setSessionPermissionMode(this.id,this.cwd,W),this.mode=Q,j.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(j.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await B.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((W)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(W){if(!(W instanceof q)&&W.code!=="ENOENT")throw W;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:Z.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,W=async(H)=>{try{await H()}catch(z){Q??=z}};if(await W(()=>this.cancel()),J)await W(()=>J.destroy());if(Z)await W(()=>Z.dispose());if(await W(()=>P.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],W=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let X=`data:${F.mimeType};base64,${F.data}`;W+=1,H+=X.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(F.type==="resource"){let X=F.resource;if("text"in X){let L=`<file path="${X.uri}">
1
+ import{r as R}from"./chunk-afxpp33r.js";import{s as WJ}from"./chunk-k47f7zqm.js";import{$ as a,F as p,I as m,J as d,L as l,Z as i,_ as r,aa as n,v as P}from"./chunk-x1qw695m.js";import{ka as zJ}from"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as g,Ya as c,hb as v}from"./chunk-mc29y7tj.js";import{sb as y}from"./chunk-095x2ykj.js";import{$b as B,Fb as C,Kb as O,Nb as f,Tb as T,Ub as u,Yb as q}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import{fd as QJ}from"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import{od as ZJ}from"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import{Td as $J}from"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import{ee as E}from"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import{cf as h,df as S,ef as I}from"./chunk-f4z3gkbs.js";import{if as s}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import{of as e,rf as JJ}from"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import{Readable as BJ,Writable as VJ}from"node:stream";import*as b from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as LJ}from"@agentclientprotocol/sdk";import t from"node:path";import{RequestError as FJ}from"@agentclientprotocol/sdk";import{nanoid as x}from"nanoid";var j=E("Agent");function k(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function GJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:k(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:k("headers"in J?J.headers:void 0)};return null}function XJ(J){let Z={};for(let Q of J){let Y=GJ(Q);if(Y)Z[Q.name]=Y}return Z}function o(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function jJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:T(Z)}]:o(J.content)}function DJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class A{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.mode=this.mapPermissionModeToMode(H.permissionMode)}mapPermissionModeToMode(J){switch(J){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 l.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await B.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await B.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?XJ(this.options.mcpServers):void 0,Q=P.getInstance().getTerminalService(this.id);if(this.runtime=await p.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(z,$)=>{let G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await R.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await B.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await r(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of jJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.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(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!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($)=>{if(await this.setServiceTier($),!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($)=>{if(await this.setResponseVerbosity($),!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($)=>{if(await this.setCommunicationStyle($),!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($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,X,L=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},W=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(D)=>{if(F)L(D);else X=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.session.id,status:"in_progress",title:`Resuming ${W.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${W.source.id} at depth ${W.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,X)L(X);return W}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await R.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(W)=>{if(W.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.toolCall.id,status:"in_progress",title:`Review: ${W.toolCall.function.name}`,content:[],kind:this.mapToolKind(W.toolKind)});else if(W.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.toolCall.id,status:W.result.success?"completed":"failed",content:[]})}}),X=await F.completion,L=(await R.list(this.cwd,this.id)).find((W)=>W.start.reviewId===F.reviewId);if(!L)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await B.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:X.status,findings:X.findings.length,content:C(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:L})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},Y=await a(J,Q),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];if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages)this.messages=[...Y.data.compactedMessages];let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=f(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)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 F=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),i(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},X=await g(this.agent.chatStream(Y,F,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let D=W.toolCall,U=D.function.name;if(U===O)break;let _=this.mapToolKind(W.toolKind),V=`Executing ${U}`;if(U==="Task"&&"function"in D)try{let N=JSON.parse(D.function.arguments),w=N.resume_from??N.resume;if(typeof w==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:V,content:[],kind:_});break}case"tool_progress":{let D=W.toolCall;if(D.function.name===O)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let D=W.toolCall;if(D.function.name===O)break;let U=W.result,_=[],V=U.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;_.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))_.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=D.function.name,YJ=d(m(w,U));_.push({type:"content",content:{type:"text",text:YJ}})}if(D.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))_.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=U.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:N,content:_});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
3
+ `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
4
+ `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
5
+ `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
6
+ `}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
7
+ `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
8
+ `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
9
+ `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
10
+ `}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let D of W.messages){if(!D.recovered||D.persisted)continue;for(let U of o(D.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:U})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
11
+ `}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
12
+ `}});break;case"goal_continuation_started":break;default:break}});if(this.messages=[...F.messages],!X.success){let W=X.error?.type??"unknown";throw FJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(G.signal.aborted)return{stopReason:"cancelled"};let L={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(Y=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=T($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?DJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){j.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)j.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await B.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,j.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(j.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await B.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof q)&&Y.code!=="ENOENT")throw Y;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>P.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
+ `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let X=`data:${F.mimeType};base64,${F.data}`;Y+=1,H+=X.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(F.type==="resource"){let X=F.resource;if("text"in X){let L=`<file path="${X.uri}">
14
14
  ${X.text}
15
- </file>`;Z.push(L),$({type:"text",text:L})}}else if(F.type==="resource_link"){let X=`[Resource: ${F.uri}]`;Z.push(X),$({type:"text",text:X})}if(W>h)throw Error(`ACP prompt contains more than ${h} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>I)throw Error(`ACP prompt text exceeds ${I} characters`);let G=Z.join(`
16
- `);return{content:W>0?Q:G,displayText:G}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));j.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=x(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
15
+ </file>`;Z.push(L),$({type:"text",text:L})}}else if(F.type==="resource_link"){let X=`[Resource: ${F.uri}]`;Z.push(X),$({type:"text",text:X})}if(Y>h)throw Error(`ACP prompt contains more than ${h} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>I)throw Error(`ACP prompt text exceeds ${I} characters`);let G=Z.join(`
16
+ `);return{content:Y>0?Q:G,displayText:G}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));j.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=x(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
17
  - ${J.risks.join(`
18
- - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:W,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:y};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=F.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(W){return j.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[H,z]of Q.entries()){let $=z.options.map((L,Y)=>`answer:${H}:${Y}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,Y)=>({optionId:$[Y],name:L.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
- `)}}]}}),Z);if(!F)return{approved:!1,reason:y};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(F.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};W[z.header]=z.options[X].label}return{approved:!0,answers:W}}catch(H){return j.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)W[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return j.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),W=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
- `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(W==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===W);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,W){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),W);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,W)=>{let H=!1,z=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>W(G)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var K=E("Agent");class M{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:LJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=QJ("acp"),Q=J.cwd||s(),W=J._meta?.["blade/taskIsolation"],H=W==="local"||W==="worktree"?W:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await WJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new A(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(X){throw await F.destroy().catch(()=>{return}),X}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!t.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await B.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!t.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await B.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new A(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(W){throw await Q.destroy().catch(()=>{return}),W}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),K.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),W=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,W);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===W)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await B.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,W]=await Promise.all([B.loadSession(J.sessionId,J.cwd),B.findSessionMetadata(J.sessionId,J.cwd)]);if(!W)throw Error(`Session not found: ${J.sessionId}`);let H=new A(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:W.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],W=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&JJ(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&$J(J.value))K.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await zJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function sJ(){let J=VJ.toWeb(process.stdout),Z=BJ.toWeb(process.stdin),Q=b.ndJsonStream(J,Z);await new b.AgentSideConnection((H)=>new M(H),Q).closed}export{sJ as runAcpIntegration};
18
+ - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:y};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=F.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(Y){return j.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((L,W)=>`answer:${H}:${W}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,W)=>({optionId:$[W],name:L.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
+ `)}}]}}),Z);if(!F)return{approved:!1,reason:y};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(F.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[X].label}return{approved:!0,answers:Y}}catch(H){return j.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
+ `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return j.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),Y=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
+ `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
+ `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,Y){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,Y)=>{let H=!1,z=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>Y(G)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var K=E("Agent");class M{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:LJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=QJ("acp"),Q=J.cwd||s(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await WJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new A(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(X){throw await F.destroy().catch(()=>{return}),X}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!t.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await B.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!t.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await B.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new A(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),K.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await B.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,Y]=await Promise.all([B.loadSession(J.sessionId,J.cwd),B.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new A(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],Y=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&JJ(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&$J(J.value))K.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await zJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function sJ(){let J=VJ.toWeb(process.stdout),Z=BJ.toWeb(process.stdin),Q=b.ndJsonStream(J,Z);await new b.AgentSideConnection((H)=>new M(H),Q).closed}export{sJ as runAcpIntegration};
@@ -0,0 +1 @@
1
+ import{sc as a,tc as b}from"./chunk-0z7rg4f3.js";import"./chunk-7x5cqfy7.js";import"./chunk-g11hq0e5.js";export{a as globalOptions,b as cliConfig};
@@ -1 +1 @@
1
- import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import"./chunk-8j01ssaf.js";import"./chunk-heqs3xan.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
1
+ import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-8j01ssaf.js";import"./chunk-heqs3xan.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -1,4 +1,4 @@
1
- import{$ as F,Z as y}from"./chunk-nysyp11q.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-97fyx4hr.js";import{Ld as $}from"./chunk-cx0tdprs.js";import{if as K}from"./chunk-5s123nbs.js";async function O(){await $(K())}async function j(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 V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});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:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`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{$ as F,Z as y}from"./chunk-x1qw695m.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-csn0epd2.js";import{Ld as $}from"./chunk-agdamn30.js";import{if as K}from"./chunk-5s123nbs.js";async function O(){await $(K())}async function j(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 V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});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:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`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 B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function P(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 L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await Q.loadSession(b,K())}catch(q){if(J(q))return null;throw q}}async function T(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=K();return Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}let[q,z]=await Promise.all([Q.loadSession(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:K()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=K();return Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}return{sessionId:z,messages:await Q.loadSession(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,K())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{O as m,j as n,I as o,P as p,T as q};
@@ -1 +1 @@
1
- import{qd as a,rd as b,sd as c}from"./chunk-k653znk8.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{qd as a,rd as b,sd as c}from"./chunk-m4f213hk.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +1 @@
1
- import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-p42cz164.js";import"./chunk-095x2ykj.js";import"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +1 @@
1
- import{$c as m,Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g,Wc as h,Xc as i,Yc as j,Zc as k,_c as l,ad as n,bd as o,cd as p,dd as q}from"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{$c as m,Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g,Wc as h,Xc as i,Yc as j,Zc as k,_c as l,ad as n,bd as o,cd as p,dd as q}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,4 +1,4 @@
1
- import{xc as I}from"./chunk-632rgzcf.js";import{Qc as A}from"./chunk-xjyctv33.js";import{ee as h}from"./chunk-4dq9y7zn.js";import{Ie as f,Me as T,Ne as w,Oe as M,Pe as P,Se as k,Te as E}from"./chunk-5wnxafpf.js";import{Ue as c,Ve as y}from"./chunk-3aqdjrtm.js";import{Ye as S,_e as n,bf as p}from"./chunk-kvx3sb3z.js";import{gf as O}from"./chunk-5s123nbs.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
1
+ import{xc as I}from"./chunk-632rgzcf.js";import{Qc as A}from"./chunk-zn7c21zj.js";import{ee as h}from"./chunk-4dq9y7zn.js";import{Ie as f,Me as T,Ne as w,Oe as M,Pe as P,Se as k,Te as E}from"./chunk-7bq9p4ab.js";import{Ue as c,Ve as y}from"./chunk-3aqdjrtm.js";import{Ye as S,_e as n,bf as p}from"./chunk-kvx3sb3z.js";import{gf as O}from"./chunk-5s123nbs.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -0,0 +1,6 @@
1
+ import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-2cqsqrxx.js";import{s as $q}from"./chunk-k47f7zqm.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as i,Ya as s,hb as r}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import{$b as h,Kb as S}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import{sc as qq}from"./chunk-0z7rg4f3.js";import{uc as Qq,vc as Yq,wc as Zq}from"./chunk-5wecprcp.js";import{xc as e}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Xc as v}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import{Ue as m,Ve as l}from"./chunk-3aqdjrtm.js";import{$e as w,Ye as u,_e as Q,bf as b}from"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as I}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=b(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:b(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:b(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:b(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:b(["added","removed"]),reason:b(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:b(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:b(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:b(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:b(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:b(["turn","searching","inspecting","target_hit","executing","completed"]),status:b(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:b(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(b(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(b(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:b(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(b(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:b(["started","completed"])}),lq=K({type:Q.Literal("provider_retry"),phase:b(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:b(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:b(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:b(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:b(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=b(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(b(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to 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"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).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("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
2
+ `)}function GQ(Y){return`[task] [${Y.status}] ${Y.subject}`}function VQ(){return{requestConfirmation:async(Y)=>Y.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Y.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function XQ(Y){if(!(Y instanceof Error))return"Unknown error";let V=Y.lastError??Y;if(V.responseBody)try{let j=JSON.parse(V.responseBody)?.error?.message;if(j)return V.statusCode?`${j} (HTTP ${V.statusCode})`:j}catch{}let q=Y.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Y.message}function BQ(Y){return Y==="jsonl"?"jsonl":"text"}function d(Y,Z){let H=(...V)=>{for(let q of V){let $=Z[q];if(typeof $==="string"&&$.trim()!=="")return $}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function KQ(Y,Z,H,V){let q=new Set(["Glob","Grep","WebSearch","LS"]),$=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!V.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(V.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(q.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if($.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:V.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function p(Y,Z,H=!1){let V=(q,$)=>{Y.stdout.write(`${JSON.stringify(c(q,$))}
3
+ `)};return{contentDelta(q){if(Z==="jsonl"){V("content_delta",{delta:q});return}if(H)return;Y.stdout.write(q)},thinkingDelta(q,$){if(Z==="jsonl")return V("thinking_delta",{delta:q}),$;if(!$)Y.stderr.write("[thinking] ");return Y.stderr.write(q),!0},thinking(q){if(Z==="jsonl"){V("thinking",{content:q});return}D(Y.stderr,`[thinking] ${q}`)},streamEnd(q,$){if(Z==="jsonl"){V("stream_end",{});return}if($)Y.stderr.write(`
4
+ `);if(q)Y.stdout.write(`
5
+ `)},content(q){if(Z==="jsonl"){V("content",{content:q});return}D(Y.stdout,q)},structuredOutput(q){if(Z==="jsonl"){V("structured_output",{output:q.output,schema_digest:q.schemaDigest});return}D(Y.stdout,JSON.stringify(q.output))},toolStart(q,$,j,z){if(Z==="jsonl"){V("tool_start",{tool_name:q,summary:$,target:j,tool_kind:z});return}D(Y.stderr,`[tool:start] ${$}`)},toolProgress(q,$,j,z){if(Z==="jsonl"){V("tool_progress",{tool_name:q,message:$,progress:j,total:z});return}D(Y.stderr,`[tool:progress] ${q}: ${$}`)},toolResult(q,$,j,z,R){if(Z==="jsonl"){V("tool_result",{tool_name:q,summary:$,target:j,tool_kind:z,success:R?.success,error_type:R?.errorType,error_message:R?.errorMessage});return}D(Y.stderr,`[tool:result] ${$}`)},mcpCatalogChanged(q){if(Z==="jsonl"){V("mcp_catalog_changed",{revision:q.revision,server_name:q.serverName,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:catalog] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpContentChanged(q){if(Z==="jsonl"){V("mcp_content_changed",{revision:q.revision,server_name:q.serverName,content_kind:q.contentKind==="resourceTemplates"?"resource_templates":q.contentKind,added:q.added,removed:q.removed,updated:q.updated});return}D(Y.stderr,`[mcp:${q.contentKind}] r${q.revision} ${q.serverName} +${q.added.length} -${q.removed.length} ~${q.updated.length}`)},mcpResourceUpdated(q){if(Z==="jsonl"){V("mcp_resource_updated",{revision:q.revision,server_name:q.serverName,uri:q.uri});return}D(Y.stderr,`[mcp:resource] r${q.revision} ${q.serverName} updated ${q.uri}`)},mcpConnectionChanged(q){if(Z==="jsonl"){V("mcp_connection_changed",{revision:q.revision,server_name:q.serverName,phase:q.phase,reason:q.reason,attempt:q.attempt,max_attempts:q.maxAttempts,...q.nextRetryAt!==void 0?{next_retry_at:q.nextRetryAt}:{},...q.error?{error:q.error}:{}});return}D(Y.stderr,`[mcp:connection] r${q.revision} ${q.serverName} ${q.phase} ${q.attempt}/${q.maxAttempts}`)},mcpLog(q){if(Z==="jsonl"){V("mcp_log",{revision:q.revision,server_name:q.serverName,level:q.level,logger:q.logger,message:q.message,projected_bytes:q.projectedBytes,data_sha256:q.dataSha256,truncated:q.truncated,details_omitted:q.detailsOmitted,timestamp:q.timestamp,synthetic:q.synthetic});return}D(Y.stderr,`[mcp:log] ${q.level} ${q.serverName}${q.logger?` logger=${q.logger}`:""}: ${q.message}`)},mcpInstructionsChanged(q){if(Z==="jsonl"){V("mcp_instructions_changed",{revision:q.revision,server_name:q.serverName,action:q.action,reason:q.reason,text:q.text,source_bytes:q.sourceBytes,projected_bytes:q.projectedBytes,sha256:q.sha256,truncated:q.truncated,details_omitted:q.detailsOmitted});return}D(Y.stderr,`[mcp:instructions] ${q.action} ${q.serverName}${q.truncated?" (truncated)":""}`)},mcpTaskChanged(q){if(Z==="jsonl"){V("mcp_task_changed",{revision:q.revision,task_id:q.taskId,server_name:q.serverName,tool_name:q.toolName,status:q.status,status_message:q.statusMessage,created_at:q.createdAt,updated_at:q.updatedAt,completed_at:q.completedAt,has_result:q.hasResult,error:q.error});return}D(Y.stderr,`[mcp:task] ${q.taskId} ${q.serverName}/${q.toolName} `+q.status)},projectRulesLoaded(q){if(Z==="jsonl"){V("project_rules_loaded",{files:q.files.map(($)=>({id:$.id,relative_path:$.relativePath,source:$.source,conditional:$.conditional,content_sha256:$.contentSha256})),trigger_paths:q.triggerPaths,blocked_write:q.blockedWrite});return}D(Y.stderr,`[project-rules] loaded ${q.files.length} file(s)${q.blockedWrite?" before write":""}`)},userShellStarted(q,$,j){if(Z==="jsonl"){V("user_shell_started",{execution_id:q,command:$,auxiliary:j});return}D(Y.stderr,`[user-shell:start] ${$}`)},userShellOutput(q,$,j,z){if(Z==="jsonl"){V("user_shell_output",{execution_id:q,stream:$,chunk:j,stream_truncated:z});return}($==="stderr"?Y.stderr:Y.stdout).write(j)},userShellCompleted(q){if(Z==="jsonl"){V("user_shell_completed",{execution_id:q.executionId,message_id:q.messageId,status:q.record.status,exit_code:q.record.exitCode,duration_ms:q.record.durationMs,stdout:q.record.stdout,stderr:q.record.stderr,truncated:q.record.truncated,auxiliary:q.auxiliary});return}D(Y.stderr,`[user-shell:${q.record.status}] exit=${q.record.exitCode??"null"} ${q.record.durationMs}ms`)},phase(q,$,j,z={}){if(Z==="jsonl"){V("phase",{phase:q,status:$,message:j,turn:z.turn,tool_name:z.toolName,target:z.target});return}D(Y.stderr,`[phase:${q}] ${j}`)},toolDetail(q,$){if(Z==="jsonl"){V("tool_detail",{tool_name:q,detail:$});return}D(Y.stderr,$)},taskUpdate(q){if(Z==="jsonl"){V("task_update",{tasks:q});return}for(let $ of q)D(Y.stderr,GQ($))},goal(q){if(Z==="jsonl"){V("goal",{state:q.goal?"updated":"cleared",goal_id:q.goal?.goalId,status:q.goal?.status,verification_attempt:q.goal?.completionVerification?.attempt,verification_status:q.goal?.completionVerification?.status,verifier_session_id:q.goal?.completionVerification?.verifierSessionId,verification_evidence_sha256:q.goal?.completionVerification?.evidenceSha256});return}if(q.goal)D(Y.stderr,`[goal:${q.goal.status}] ${q.goal.objective}`);else D(Y.stderr,"[goal:cleared]")},subagent(q){let $=q.kind==="subagent_spawned";if(Z==="jsonl"){V("subagent",{state:$?"spawned":"completed",session_id:q.sessionId,subagent_type:q.type,success:$?void 0:q.success,summary:$?void 0:q.summary,verification_verdict:$?void 0:q.verificationVerdict,resumed_from:q.resumedFrom,root_agent_id:q.rootAgentId,resume_depth:q.resumeDepth});return}D(Y.stderr,`[subagent:${$?"spawned":"completed"}] ${q.sessionId}${q.resumedFrom?` resumed from ${q.resumedFrom}`:""}`)},tokenUsage(q){if(Z==="jsonl"){V("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens,cache_read_tokens:q.cacheReadTokens,cache_write_tokens:q.cacheWriteTokens,cost_usd:q.costUsd});return}D(Y.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){if(Z==="jsonl"){V("compacting",{state:q?"started":"completed"});return}D(Y.stderr,q?"[context] compacting started":"[context] compacting completed")},providerRetry(q){if(Z==="jsonl"){V("provider_retry",{phase:q.phase,attempt:q.attempt,max_retries:q.maxRetries,reason:q.reason,status_code:q.statusCode,delay_ms:q.delayMs,next_retry_at:q.nextRetryAt});return}let $=q.delayMs!==void 0?` in ${Math.max(0,Math.ceil(q.delayMs/1000))}s`:"";D(Y.stderr,`[provider-retry:${q.phase}] ${q.attempt}/${q.maxRetries} ${q.reason}${$}`)},providerStall(q){if(Z==="jsonl"){V("provider_stall",{phase:q.phase,stall_count:q.stallCount,duration_ms:q.durationMs,warning_after_ms:q.warningAfterMs,timeout_ms:q.timeoutMs,output_started:q.outputStarted});return}D(Y.stderr,`[provider-stall:${q.phase}] ${q.durationMs}ms / ${q.timeoutMs}ms`)},turnLimit(q){if(Z==="jsonl"){V("turn_limit",{turns_count:q,action:"continue"});return}D(Y.stderr,`[turn-limit] continuing after ${q} turns`)},taskSession(q){if(Z==="jsonl"){V("task_session",{session_id:q.sessionId,project_path:q.projectPath,source_project_path:q.sourceProjectPath,isolation:q.isolation,worktree_branch:q.worktreeBranch,base_commit:q.baseCommit});return}D(Y.stderr,`[task:${q.isolation}] ${q.sessionId} ${q.sourceProjectPath} -> ${q.projectPath}${q.worktreeBranch?` (${q.worktreeBranch})`:""}`)},taskAdmission(q){if(Z==="jsonl"){V("task_admission",{state:q.state,queue_position:q.queuePosition,queue_depth:q.queueDepth,in_flight:q.inFlight,max_concurrent_tasks:q.maxConcurrentTasks});return}D(Y.stderr,q.state==="queued"?`[task:queued] position ${q.queuePosition??1}/${q.queueDepth} (running ${q.inFlight}/${q.maxConcurrentTasks})`:`[task:running] admitted (running ${q.inFlight}/${q.maxConcurrentTasks})`)},output(q,$=0){if(Z==="jsonl"){V("output",{content:q,exit_code:$});return}D($===0?Y.stdout:Y.stderr,q)},error(q){if(Z==="jsonl"){V("error",{message:q});return}D(Y.stderr,q)}}}async function DQ(Y,Z={stdout:process.stdout,stderr:process.stderr},H){let V="text",q=p(Z,V),$=new Dq,j={targetLocked:!1},z,R,J=eq(H);try{let B=ZQ(Y);V=BQ(B.outputFormat);let P=await Bq(B);q=p(Z,V,Boolean(P)),await Gq();let jq=await Vq(B),A=await Xq(jq);if(A.mode==="output"){if(A.content)q.output(A.content,A.exitCode??0);return A.exitCode??0}let L=A.content.trimStart().startsWith("!")?A.content.trimStart().slice(1).trim():void 0;if(L!==void 0&&B.taskIsolation)throw Error("User shell commands cannot be combined with --task-isolation");if(L!==void 0&&P)throw Error("Output schemas cannot be combined with user shell commands");if(B.taskIsolation&&(B.continue||B.resume||B.forkSession))throw Error("--task-isolation cannot be combined with --continue, --resume, or --fork-session");let{sessionId:U,messages:C,metadata:k}=await Kq({sessionId:B.sessionId,continue:B.continue,resume:B.resume,forkSession:B.forkSession,fallbackSessionPrefix:"headless"}),E=B.permissionMode??k?.permissionMode??"yolo",F=B.model&&B.model!=="inherit"?B.model:v()?.id,_=B.taskIsolation?await $q.createSessionTask({sessionId:U,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,dispatch:{version:1,prompt:A.content,sourceProjectPath:I(),isolation:B.taskIsolation,permissionMode:E,...F?{modelId:F}:{},...P?{outputSchema:P}:{}}}):void 0,M=_?.metadata.projectPath??k?.projectPath??I();if(!_)await h.setSessionPermissionMode(U,M,E);let bq=_?!1:await r.cancelPendingNonInteractive(M,U);if(_)q.taskSession({sessionId:U,projectPath:M,sourceProjectPath:_.metadata.taskSourceProjectPath??I(),isolation:B.taskIsolation,worktreeBranch:_.metadata.taskWorktreeBranch,baseCommit:_.metadata.taskBaseCommit}),R=s.subscribe((G)=>{if(G.type!=="task.status"||G.sessionId!==U||G.projectPath!==M||!["queued","running"].includes(String(G.properties.taskStatus))||typeof G.properties.taskQueueDepth!=="number"||typeof G.properties.taskInFlight!=="number"||typeof G.properties.taskConcurrencyLimit!=="number")return;q.taskAdmission({state:G.properties.taskStatus,queuePosition:typeof G.properties.taskQueuePosition==="number"?G.properties.taskQueuePosition:void 0,queueDepth:G.properties.taskQueueDepth,inFlight:G.properties.taskInFlight,maxConcurrentTasks:G.properties.taskConcurrencyLimit})});let Hq={messages:bq?await h.loadSession(U,M):[...C],userId:"cli-user",sessionId:U,workspaceRoot:M,permissionMode:E,signal:J.signal,..._?.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:VQ()};if(z=await a.create({sessionId:U,workspaceRoot:M,modelId:B.model,permissionMode:E,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig,agents:B.agents?e(B.agents):void 0,..._?.taskWorktree?{taskWorktree:_.taskWorktree}:{},..._?.metadata.taskIsolation?{taskIsolation:_.metadata.taskIsolation}:{},...C.length>0?{sessionStart:{isResume:!0,resumeSessionId:U}}:{}}),L!==void 0){let G=await z.executeUserShellCommand(L,{signal:J.signal,onEvent:(X)=>{if(X.type==="started")q.userShellStarted(X.executionId,X.command,X.auxiliary);else if(X.type==="output")q.userShellOutput(X.executionId,X.stream,X.chunk,X.streamTruncated)}});return q.userShellCompleted(G),G.record.status==="completed"?0:G.record.status==="aborted"?130:G.record.exitCode??1}let zq=B.maxTurns??z.getConfig().maxTurns,_q=_?.taskWorktree?[...new Set([...B.disallowedTools??[],"EnterWorktree","ExitWorktree"])]:B.disallowedTools,Aq=await t.createWithRuntime(z,{sessionId:U,systemPrompt:B.systemPrompt,appendSystemPrompt:B.appendSystemPrompt,maxTurns:B.maxTurns,modelId:B.model,permissionMode:E,toolWhitelist:B.allowedTools,toolBlacklist:_q,mcpConfig:B.mcpConfig,strictMcpConfig:B.strictMcpConfig}),O=await i(Aq.chatStream(A.content,Hq,{stream:!0,signal:J.signal,maxTurns:B.maxTurns,outputSchema:P,...zq===-1?{onTurnLimitReached:async(G)=>{return q.turnLimit(G.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}:{}}),async(G)=>{switch(G.kind){case"content_delta":if(!P||V==="jsonl")$.markAssistantContent();q.contentDelta(G.delta);break;case"thinking_delta":$.setThinkingOpened(q.thinkingDelta(G.delta,$.hasOpenThinking()));break;case"stream_end":{let X=$.completeStream();q.streamEnd(X.wroteAssistantContent,X.openedThinking);break}case"tool_start":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;if(["TaskCreate","TaskUpdate","TaskList"].includes(X.function.name))break;try{let f=JSON.parse(X.function.arguments),N=o(X.function.name,f),x=d(X.function.name,f),W=KQ(X.function.name,N,x,j);if(W.shouldLockTarget)j.targetLocked=!0;q.phase(W.phase,W.status,W.message,{toolName:X.function.name,target:x}),q.toolStart(X.function.name,N,x,G.toolKind)}catch{q.phase(j.targetLocked?"executing":"searching",j.targetLocked?"hit":"ongoing",j.targetLocked?`Working within target: ${X.function.name}`:`Still searching: ${X.function.name}`,{toolName:X.function.name}),q.toolStart(X.function.name,X.function.name,void 0,G.toolKind)}break}case"tool_progress":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;q.toolProgress(X.function.name,G.update.message,G.update.progress,G.update.total);break}case"tool_result":{let X=G.toolCall;if(!("function"in X))break;if(X.function.name===S)break;let f;try{let x=JSON.parse(X.function.arguments);f=d(X.function.name,x)}catch{f=void 0}let N=n(X.function.name,G.result);if(q.toolResult(X.function.name,N.summary,f,void 0,{success:G.result.success,errorType:G.result.error?.type,errorMessage:G.result.error?.message}),N.detail)q.toolDetail(X.function.name,N.detail);break}case"token_usage":q.tokenUsage(G.usage);break;case"compaction":q.compacting(G.phase==="start");break;case"task_update":q.taskUpdate(G.tasks);break;case"structured_output":q.structuredOutput(G);break;case"mcp_catalog_changed":q.mcpCatalogChanged(G);break;case"mcp_content_changed":q.mcpContentChanged(G);break;case"mcp_resource_updated":q.mcpResourceUpdated(G);break;case"mcp_connection_changed":q.mcpConnectionChanged(G);break;case"mcp_log":q.mcpLog(G);break;case"mcp_instructions_changed":q.mcpInstructionsChanged(G);break;case"mcp_task_changed":q.mcpTaskChanged(G);break;case"project_rules_loaded":q.projectRulesLoaded(G);break;case"steering_applied":case"follow_up_started":case"goal_continuation_started":break;case"goal_updated":q.goal(G);break;case"subagent_spawned":case"subagent_completed":q.subagent(G);break;case"model_fallback":break;case"provider_retry":q.providerRetry(G);break;case"provider_stall":q.providerStall(G);break;case"turn_start":if(G.turn===1)j.targetLocked=!1;q.phase("turn",j.targetLocked?"hit":"ongoing",`Turn ${G.turn} started`,{turn:G.turn});break;default:{let X=G}}});if(O.metadata?.outputTruncated)q.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!O.success)return q.error(`Error: ${O.error?.message??"Agent execution failed"}`),1;return q.phase("completed","done","Headless run completed"),0}catch(B){if($.hasOpenThinking()&&V==="text")Z.stderr.write(`
6
+ `);return q.error(`Error: ${XQ(B)}`),1}finally{R?.();try{await z?.dispose()}finally{J.dispose()}}}async function cQ(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:H,"output-format":V,"system-prompt":q,"append-system-prompt":$,"max-turns":j,...z}=qq,R=nq(tq(process.argv)).scriptName("blade").strict(!1).options(z).middleware([Yq,Qq,Zq]);return $Q(R),await R.parse(),!0}export{DQ as runHeadless,cQ as handleHeadlessMode,QQ as HeadlessOptionsSchema};
@@ -1 +1 @@
1
- import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-cy6emyt9.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-7x5cqfy7.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};