blade-code 0.10.14 → 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 (51) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-wj4cjb73.js → chunk-09k2b1tw.js} +1 -1
  3. package/dist/{chunk-0hbvc51n.js → chunk-0z7rg4f3.js} +1 -1
  4. package/dist/{chunk-sntbbkbf.js → chunk-1amhvwmj.js} +2 -2
  5. package/dist/chunk-1c9rkm57.js +1 -0
  6. package/dist/{chunk-r6bha0vm.js → chunk-25abj6rx.js} +1 -1
  7. package/dist/{chunk-xk7svrdb.js → chunk-2cqsqrxx.js} +1 -1
  8. package/dist/{chunk-m088381q.js → chunk-3m8pschr.js} +1 -1
  9. package/dist/{chunk-avsv4e5g.js → chunk-5psydp1v.js} +1 -1
  10. package/dist/{chunk-hpbyvwhm.js → chunk-5tpjb8yn.js} +1 -1
  11. package/dist/{chunk-snv4bpbv.js → chunk-5wecprcp.js} +1 -1
  12. package/dist/chunk-67vf8r5v.js +6 -0
  13. package/dist/{chunk-3be2feze.js → chunk-6y9w5296.js} +1 -1
  14. package/dist/{chunk-hrmfhv8k.js → chunk-7bq9p4ab.js} +1 -1
  15. package/dist/{chunk-se1tfys3.js → chunk-7x5cqfy7.js} +1 -1
  16. package/dist/{chunk-wznyzdtg.js → chunk-a170cgzr.js} +1 -1
  17. package/dist/{chunk-321n9hem.js → chunk-afxpp33r.js} +1 -1
  18. package/dist/{chunk-j7k5x43d.js → chunk-agdamn30.js} +1 -1
  19. package/dist/{chunk-kesgbws4.js → chunk-csn0epd2.js} +1 -1
  20. package/dist/chunk-d7976m5f.js +5 -0
  21. package/dist/{chunk-8y2zs0p0.js → chunk-eav8jpk1.js} +2 -2
  22. package/dist/{chunk-8zr7h97n.js → chunk-ee7an1kq.js} +1 -1
  23. package/dist/{chunk-9ajyeqa7.js → chunk-jjy8sg10.js} +1 -1
  24. package/dist/{chunk-mcqe9km3.js → chunk-k47f7zqm.js} +1 -1
  25. package/dist/{chunk-2z6261pz.js → chunk-m4f213hk.js} +1 -1
  26. package/dist/{chunk-4rn3r12e.js → chunk-mc29y7tj.js} +2 -2
  27. package/dist/{chunk-3jnhd81j.js → chunk-n72www7h.js} +3 -3
  28. package/dist/{chunk-cyhmfcqq.js → chunk-nfqsnkbt.js} +47 -47
  29. package/dist/{chunk-zvt8ngpt.js → chunk-ng8a4btc.js} +1 -1
  30. package/dist/{chunk-m2b2w90y.js → chunk-qpd1jmm4.js} +1 -1
  31. package/dist/{chunk-e0y9nb0a.js → chunk-t6cmqsdj.js} +1 -1
  32. package/dist/{chunk-k5fw5abr.js → chunk-wz3z8908.js} +1 -1
  33. package/dist/{chunk-rbph12qe.js → chunk-x1qw695m.js} +3 -3
  34. package/dist/{chunk-pt0en61h.js → chunk-zmg66vp7.js} +1 -1
  35. package/dist/{chunk-2cgcht30.js → chunk-zn2cec1d.js} +1 -1
  36. package/dist/{chunk-xq403rac.js → chunk-zn7c21zj.js} +3 -3
  37. package/dist/web/assets/{ChatView-CxSysoN5.js → ChatView-rHWZ9qCy.js} +5 -5
  38. package/dist/web/assets/{CodeBlockHighlighter-a5UaDQQg.js → CodeBlockHighlighter-KpN8jpS4.js} +1 -1
  39. package/dist/web/assets/{FilePreview-CvGTS9CJ.js → FilePreview-BbEcYewq.js} +1 -1
  40. package/dist/web/assets/{MarkdownRenderer-D50Cw9OM.js → MarkdownRenderer-Cpqkv5Ml.js} +3 -3
  41. package/dist/web/assets/{SettingsModal-DtREOjs-.js → SettingsModal-D6NZP8vM.js} +1 -1
  42. package/dist/web/assets/{TaskSwitcher-BlMvq8mt.js → TaskSwitcher-cT1qKR6s.js} +1 -1
  43. package/dist/web/assets/{TerminalPanel-B8LccKzq.js → TerminalPanel-0MehdzKr.js} +1 -1
  44. package/dist/web/assets/index-BYd4kNGp.js +11 -0
  45. package/dist/web/assets/{session-events-_Kir2HH_.js → session-events-BH7O5JJl.js} +5 -5
  46. package/dist/web/index.html +2 -2
  47. package/package.json +1 -1
  48. package/dist/chunk-99tdg2ny.js +0 -1
  49. package/dist/chunk-g3w00xb7.js +0 -5
  50. package/dist/chunk-qb076ca2.js +0 -6
  51. package/dist/web/assets/index-CQP8XT9a.js +0 -11
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Ac as W}from"./chunk-pt0en61h.js";import{Dc as F,Ec as M}from"./chunk-ktf3bpmw.js";import"./chunk-xq403rac.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-zvt8ngpt.js";import"./chunk-7wjy6kgt.js";import{de as T}from"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.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-se1tfys3.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-3be2feze.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-2cgcht30.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-qb076ca2.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-9ajyeqa7.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-sntbbkbf.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-99tdg2ny.js"),import("./chunk-m2b2w90y.js"),import("./chunk-8y2zs0p0.js"),import("./chunk-74shfpve.js"),import("./chunk-wznyzdtg.js"),import("./chunk-mtk2tf9n.js"),import("./chunk-4zs5r4n4.js"),import("./chunk-e0y9nb0a.js"),import("./chunk-xx1d9kfd.js"),import("./chunk-wj4cjb73.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-cyhmfcqq.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-3jnhd81j.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-321n9hem.js";import"./chunk-mcqe9km3.js";import"./chunk-rbph12qe.js";import"./chunk-8zr7h97n.js";import"./chunk-p4zt7ts9.js";import"./chunk-4rn3r12e.js";import"./chunk-095x2ykj.js";import"./chunk-kesgbws4.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-xq403rac.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-g3w00xb7.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-2z6261pz.js";import"./chunk-j7k5x43d.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-zvt8ngpt.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.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-se1tfys3.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-se1tfys3.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,4 +1,4 @@
1
- import{r as R}from"./chunk-321n9hem.js";import{s as WJ}from"./chunk-mcqe9km3.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-rbph12qe.js";import{ka as zJ}from"./chunk-8zr7h97n.js";import"./chunk-p4zt7ts9.js";import{Va as g,Ya as c,hb as v}from"./chunk-4rn3r12e.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-kesgbws4.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import"./chunk-xq403rac.js";import"./chunk-vmq248m7.js";import{fd as QJ}from"./chunk-ybvdac8k.js";import"./chunk-g3w00xb7.js";import"./chunk-2mzcxq6c.js";import{od as ZJ}from"./chunk-8j01ssaf.js";import"./chunk-2z6261pz.js";import"./chunk-j7k5x43d.js";import"./chunk-9tnaads5.js";import{Td as $J}from"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-zvt8ngpt.js";import"./chunk-7wjy6kgt.js";import{ee as E}from"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.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-se1tfys3.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(`
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
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
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
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}
@@ -7,7 +7,7 @@ import{r as R}from"./chunk-321n9hem.js";import{s as WJ}from"./chunk-mcqe9km3.js"
7
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
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
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"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]
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
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
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
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}">
@@ -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-kesgbws4.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-se1tfys3.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-rbph12qe.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-kesgbws4.js";import{Ld as $}from"./chunk-j7k5x43d.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-2z6261pz.js";import"./chunk-hrmfhv8k.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-se1tfys3.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-4rn3r12e.js";import"./chunk-095x2ykj.js";import"./chunk-kesgbws4.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-g3w00xb7.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-zvt8ngpt.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-se1tfys3.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-xq403rac.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.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-se1tfys3.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-xq403rac.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-hrmfhv8k.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-se1tfys3.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};
@@ -1,4 +1,4 @@
1
- import{We as Zn,Xe as Jn}from"./chunk-3aqdjrtm.js";import{Ye as rn,Ze as D,_e as m}from"./chunk-kvx3sb3z.js";import{cf as pn,df as Nn}from"./chunk-f4z3gkbs.js";import{if as b}from"./chunk-5s123nbs.js";import{kf as Dn,nf as H}from"./chunk-s5666ta0.js";import{vf as fn,wf as En}from"./chunk-se1tfys3.js";import{Af as P}from"./chunk-gav4hxcv.js";import{Kf as un}from"./chunk-363pgv1e.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{We as Zn,Xe as Jn}from"./chunk-3aqdjrtm.js";import{Ye as rn,Ze as D,_e as m}from"./chunk-kvx3sb3z.js";import{cf as pn,df as Nn}from"./chunk-f4z3gkbs.js";import{if as b}from"./chunk-5s123nbs.js";import{kf as Dn,nf as H}from"./chunk-s5666ta0.js";import{vf as fn,wf as En}from"./chunk-7x5cqfy7.js";import{Af as P}from"./chunk-gav4hxcv.js";import{Kf as un}from"./chunk-363pgv1e.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!l(u,"ENOENT"))throw u}}}catch(r){if(!l(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!it(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class cn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ft(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.10.14",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.10.15",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
2
2
  export{i as uf,n as vf,o as wf,c as xf,a as yf,d as zf};
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-8zr7h97n.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-xq403rac.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-zvt8ngpt.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-hrmfhv8k.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as k}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-se1tfys3.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-ee7an1kq.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.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{if as k}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 U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,4 +1,4 @@
1
- import{G as P}from"./chunk-rbph12qe.js";import{gb as K}from"./chunk-4rn3r12e.js";import{$b as B,Cb as G,Db as N,Eb as S,Fb as O,Gb as s}from"./chunk-kesgbws4.js";import{ec as j}from"./chunk-4hawehmd.js";import{fd as q}from"./chunk-ybvdac8k.js";import{vd as v}from"./chunk-j7k5x43d.js";import{Gf as z}from"./chunk-363pgv1e.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{G as P}from"./chunk-x1qw695m.js";import{gb as K}from"./chunk-mc29y7tj.js";import{$b as B,Cb as G,Db as N,Eb as S,Fb as O,Gb as s}from"./chunk-csn0epd2.js";import{ec as j}from"./chunk-4hawehmd.js";import{fd as q}from"./chunk-ybvdac8k.js";import{vd as v}from"./chunk-agdamn30.js";import{Gf as z}from"./chunk-363pgv1e.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,4 +1,4 @@
1
- import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-zvt8ngpt.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-hrmfhv8k.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-se1tfys3.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-ng8a4btc.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-7bq9p4ab.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-7x5cqfy7.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the