blade-code 0.10.43 → 0.10.44

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 (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-t2r7tqn0.js → chunk-1vydfzvy.js} +1 -1
  3. package/dist/{chunk-k87p7x1e.js → chunk-3nfse1ps.js} +1 -1
  4. package/dist/{chunk-rwjm6p0f.js → chunk-50a5xx45.js} +1 -1
  5. package/dist/{chunk-7s5hw0gr.js → chunk-583kv07t.js} +1 -1
  6. package/dist/{chunk-pyk2ey7y.js → chunk-619q1w65.js} +1 -1
  7. package/dist/{chunk-bct3s5vs.js → chunk-63p5mj97.js} +1 -1
  8. package/dist/{chunk-e1vyznkn.js → chunk-706zda55.js} +1 -1
  9. package/dist/{chunk-jpz805fs.js → chunk-74hcqcn7.js} +1 -1
  10. package/dist/{chunk-8vsx6m43.js → chunk-7z5t63ke.js} +1 -1
  11. package/dist/chunk-86tba7p4.js +1 -0
  12. package/dist/{chunk-fzqsea19.js → chunk-99nka030.js} +1 -1
  13. package/dist/{chunk-6skymhz5.js → chunk-a68fws4p.js} +1 -1
  14. package/dist/{chunk-m8a2qj5c.js → chunk-agbyfdvw.js} +1 -1
  15. package/dist/{chunk-c8ddch38.js → chunk-aw7w91f0.js} +3 -3
  16. package/dist/{chunk-yqy000kg.js → chunk-cf2541w5.js} +1 -1
  17. package/dist/{chunk-n7dvqbrc.js → chunk-ckqj0pxz.js} +1 -1
  18. package/dist/{chunk-txkrtgcd.js → chunk-d18mw6d1.js} +1 -1
  19. package/dist/{chunk-32g59k4p.js → chunk-fk0q25dp.js} +1 -1
  20. package/dist/{chunk-ag5ea7ce.js → chunk-g96t2yrz.js} +1 -1
  21. package/dist/{chunk-vbpykrxd.js → chunk-j0k3mbkd.js} +1 -1
  22. package/dist/{chunk-yypnfmed.js → chunk-m1b6v1zn.js} +1 -1
  23. package/dist/{chunk-3bpxvanm.js → chunk-mzq3ps9j.js} +2 -2
  24. package/dist/{chunk-nynfqgsj.js → chunk-n4ywszmn.js} +1 -1
  25. package/dist/{chunk-qnxgzyyx.js → chunk-p4egmgt6.js} +1 -1
  26. package/dist/chunk-pk9peyzp.js +1 -0
  27. package/dist/{chunk-c3020yav.js → chunk-qzd9d0p8.js} +1 -1
  28. package/dist/{chunk-w5ayh9b8.js → chunk-r085zhqr.js} +1 -1
  29. package/dist/{chunk-372mmzj3.js → chunk-s4denzh4.js} +1 -1
  30. package/dist/{chunk-x2vqgssm.js → chunk-svj24r6g.js} +1 -1
  31. package/dist/{chunk-skb4h36j.js → chunk-synjj8b3.js} +1 -1
  32. package/dist/{chunk-qmcj20g2.js → chunk-t33njg4e.js} +1 -1
  33. package/dist/{chunk-5wzjdfde.js → chunk-tzp486wc.js} +1 -1
  34. package/dist/{chunk-nsrghqdx.js → chunk-vx5tjahq.js} +1 -1
  35. package/dist/{chunk-s9s9daak.js → chunk-wr2rkg9t.js} +1 -1
  36. package/dist/{chunk-6ch7a6xf.js → chunk-wx5nj2s2.js} +1 -1
  37. package/dist/{chunk-dcp5gg6q.js → chunk-x3cyg9pe.js} +1 -1
  38. package/dist/{chunk-d5x5wknc.js → chunk-z9absgab.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-nwzjmcxq.js +0 -1
  41. package/dist/chunk-yt9qer14.js +0 -1
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{dd as W}from"./chunk-yqy000kg.js";import{gd as F,hd as M}from"./chunk-fk4wbmv6.js";import"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{cg as N,dg as B}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Dg as T}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as J}from"./chunk-hfrcwkc8.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-s9s9daak.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-k87p7x1e.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3y784b9c.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-nsrghqdx.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-bct3s5vs.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-c3020yav.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-yt9qer14.js"),import("./chunk-6skymhz5.js"),import("./chunk-3bpxvanm.js"),import("./chunk-c9s4n31b.js"),import("./chunk-skb4h36j.js"),import("./chunk-2eddqgnh.js"),import("./chunk-9rrced3b.js"),import("./chunk-fzqsea19.js"),import("./chunk-n7dvqbrc.js"),import("./chunk-8vsx6m43.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{dd as W}from"./chunk-cf2541w5.js";import{gd as F,hd as M}from"./chunk-fk4wbmv6.js";import"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{cg as N,dg as B}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Dg as T}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as J}from"./chunk-hfrcwkc8.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-wr2rkg9t.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-3nfse1ps.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3y784b9c.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-vx5tjahq.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-63p5mj97.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-qzd9d0p8.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-pk9peyzp.js"),import("./chunk-a68fws4p.js"),import("./chunk-mzq3ps9j.js"),import("./chunk-c9s4n31b.js"),import("./chunk-synjj8b3.js"),import("./chunk-2eddqgnh.js"),import("./chunk-9rrced3b.js"),import("./chunk-99nka030.js"),import("./chunk-ckqj0pxz.js"),import("./chunk-7z5t63ke.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-nwzjmcxq.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-rwjm6p0f.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-86tba7p4.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-50a5xx45.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,2 +1,2 @@
1
- import{Sg as d,Ug as h}from"./chunk-vbpykrxd.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{Sg as d,Ug as h}from"./chunk-j0k3mbkd.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as Xc,w as Yc};
@@ -1 +1 @@
1
- import{re as a,se as b,te as c,ue as d,ve as e}from"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
1
+ import{re as a,se as b,te as c,ue as d,ve as e}from"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -1,4 +1,4 @@
1
- import{b as iJ,c as nJ,d as tJ}from"./chunk-d5x5wknc.js";import{j as XJ,k as GJ}from"./chunk-8vtyatd6.js";import{u as x8}from"./chunk-x2vqgssm.js";import{$ as MJ,B as L6,D as UY,F as e2,G as o2,H as q6,N as j1,P as D4,Q as V4,V as Z8,W as PJ,X as RJ,_ as yJ,ea as T6,fa as k6,ga as OY,ha as l4,ja as d4,la as B6}from"./chunk-c8ddch38.js";import{pa as j9,qa as h9,ra as E9,ua as qY}from"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import{Xa as t4,Ya as s4,lb as e4,ub as l2}from"./chunk-dcp5gg6q.js";import{Db as K8}from"./chunk-mrsc4a55.js";import{$b as S4,Ac as P0,Wb as r4,ec as v4,lc as E4,mc as u2,nc as g4,pc as j8,xc as Y8}from"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{ad as aJ}from"./chunk-v9tzhe90.js";import{bd as q8,cd as u8,ed as T1}from"./chunk-yqy000kg.js";import"./chunk-fk4wbmv6.js";import{Bd as x4,Id as m0,id as I$,jd as r0,kd as Q$,ld as MQ,md as D$,nd as h8,od as Z9,pd as dQ,qd as t9,rd as X9,sd as f$,td as $1,ud as GY,vd as a0,wd as rJ,xd as R2,yd as X8}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import{Vd as rQ}from"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import{ee as M6,he as hJ,ne as AJ,te as KY}from"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import{He as TQ,Je as O1}from"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import{Lf as ZY,Qf as bJ,Rf as XY}from"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import{$f as kQ,Zf as V$,_f as E8}from"./chunk-j7edwwg1.js";import{dg as l0}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Bg as YY,Eg as e1}from"./chunk-fhnkyqfb.js";import{Gg as JJ,Hg as YJ,Kg as h1}from"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Wg as r9}from"./chunk-vbpykrxd.js";import{Xg as $4}from"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as IQ}from"./chunk-hfrcwkc8.js";import{useMemoizedFn as D2}from"ahooks";import{useEffect as xX,useState as V2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as jX,useRef as f2}from"react";import{useShallow as _Y}from"zustand/react/shallow";import{useStore as zY}from"zustand";function n($){return zY(f$,$)}var NY=[],S$=()=>n(($)=>$.session.sessionId),I1=()=>n(($)=>$.session.workspaceRoot),Q4=()=>n(($)=>$.session.messages),J4=()=>n(($)=>$.session.clearCount),Y4=()=>n(($)=>$.session.isCompacting),Z4=()=>n(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>n(($)=>$.session.providerCircuit),G4=()=>n(($)=>$.session.providerAdmission),K4=()=>n(($)=>$.session.providerRetry),q4=()=>n(($)=>$.session.providerStall),U4=()=>n(($)=>$.session.actionStationarity),n1=()=>n(($)=>$.session.actions),O4=()=>n(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),z4=()=>n(($)=>$.app.initializationStatus),_4=()=>n(($)=>$.app.initializationError),y8=()=>n(($)=>$.app.activeModal),N4=()=>n(($)=>$.app.tasks),F4=()=>n(($)=>$.app.modelEditorTarget),H4=()=>n(($)=>$.app.sessionSelectorData),W4=()=>n(($)=>$.app.awaitingSecondCtrlC),t1=()=>n(($)=>$.app.actions),M8=()=>n(($)=>$.app.initializationStatus==="ready"),L4=()=>n(($)=>$.app.tasks.length>0),v$=()=>n(($)=>$.config.config?.permissionMode||"default"),B4=()=>n(($)=>$.config.config?.models??NY),C8=()=>n(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),I8=()=>n(($)=>$.config.config?.currentModelId),A0=()=>n(($)=>{return r0.getTheme()}),w4=()=>n(($)=>$.config.config?.codeTheme??"default"),e0=()=>n(($)=>$.focus.currentFocus),b4=()=>n(($)=>$.focus.actions),s1=()=>n(($)=>$.command.isProcessing),A4=()=>n(($)=>$.command.actions),T8=()=>n(($)=>$.command.pendingCommands),P4=()=>n(($)=>$.command.recoveredSteeringCount),k8=()=>n(($)=>$.app.thinkingModeEnabled),f8=()=>n(($)=>$.app.reasoningEffort),S8=()=>n(($)=>$.app.serviceTier),v8=()=>n(($)=>$.app.responseVerbosity),D8=()=>n(($)=>$.app.communicationStyle),R4=()=>n(($)=>$.session.currentThinkingContent),y4=()=>n(($)=>$.session.thinkingExpanded),M4=()=>n(($)=>$.session.currentStreamingMessageId),C4=()=>n(_Y(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),I4=()=>n(($)=>$.session.finalizingStreamingMessageId),T4=()=>n(($)=>$.session.historyExpanded),k4=()=>n(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as d8,useRef as n4}from"react";function FY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function HY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function WY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function V8($){let Q=HY($),Y=WY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=FY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as LY,mkdirSync as BY,writeFileSync as wY}from"node:fs";import bY from"node:os";import E2 from"node:path";var f4=null;function AY(){let $=process.env.BLADE_STORAGE_ROOT||E2.join(bY.homedir(),".blade");return E2.join($,"logs","stream-debug.log")}function PY($){if(f4===$)return;let Q=E2.dirname($);BY(Q,{recursive:!0,mode:493}),wY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as iJ,c as nJ,d as tJ}from"./chunk-z9absgab.js";import{j as XJ,k as GJ}from"./chunk-8vtyatd6.js";import{u as x8}from"./chunk-svj24r6g.js";import{$ as MJ,B as L6,D as UY,F as e2,G as o2,H as q6,N as j1,P as D4,Q as V4,V as Z8,W as PJ,X as RJ,_ as yJ,ea as T6,fa as k6,ga as OY,ha as l4,ja as d4,la as B6}from"./chunk-aw7w91f0.js";import{pa as j9,qa as h9,ra as E9,ua as qY}from"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import{Xa as t4,Ya as s4,lb as e4,ub as l2}from"./chunk-x3cyg9pe.js";import{Db as K8}from"./chunk-mrsc4a55.js";import{$b as S4,Ac as P0,Wb as r4,ec as v4,lc as E4,mc as u2,nc as g4,pc as j8,xc as Y8}from"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{ad as aJ}from"./chunk-v9tzhe90.js";import{bd as q8,cd as u8,ed as T1}from"./chunk-cf2541w5.js";import"./chunk-fk4wbmv6.js";import{Bd as x4,Id as m0,id as I$,jd as r0,kd as Q$,ld as MQ,md as D$,nd as h8,od as Z9,pd as dQ,qd as t9,rd as X9,sd as f$,td as $1,ud as GY,vd as a0,wd as rJ,xd as R2,yd as X8}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import{Vd as rQ}from"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import{ee as M6,he as hJ,ne as AJ,te as KY}from"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import{He as TQ,Je as O1}from"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import{Lf as ZY,Qf as bJ,Rf as XY}from"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import{$f as kQ,Zf as V$,_f as E8}from"./chunk-j7edwwg1.js";import{dg as l0}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Bg as YY,Eg as e1}from"./chunk-fhnkyqfb.js";import{Gg as JJ,Hg as YJ,Kg as h1}from"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Wg as r9}from"./chunk-j0k3mbkd.js";import{Xg as $4}from"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as IQ}from"./chunk-hfrcwkc8.js";import{useMemoizedFn as D2}from"ahooks";import{useEffect as xX,useState as V2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as jX,useRef as f2}from"react";import{useShallow as _Y}from"zustand/react/shallow";import{useStore as zY}from"zustand";function n($){return zY(f$,$)}var NY=[],S$=()=>n(($)=>$.session.sessionId),I1=()=>n(($)=>$.session.workspaceRoot),Q4=()=>n(($)=>$.session.messages),J4=()=>n(($)=>$.session.clearCount),Y4=()=>n(($)=>$.session.isCompacting),Z4=()=>n(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>n(($)=>$.session.providerCircuit),G4=()=>n(($)=>$.session.providerAdmission),K4=()=>n(($)=>$.session.providerRetry),q4=()=>n(($)=>$.session.providerStall),U4=()=>n(($)=>$.session.actionStationarity),n1=()=>n(($)=>$.session.actions),O4=()=>n(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),z4=()=>n(($)=>$.app.initializationStatus),_4=()=>n(($)=>$.app.initializationError),y8=()=>n(($)=>$.app.activeModal),N4=()=>n(($)=>$.app.tasks),F4=()=>n(($)=>$.app.modelEditorTarget),H4=()=>n(($)=>$.app.sessionSelectorData),W4=()=>n(($)=>$.app.awaitingSecondCtrlC),t1=()=>n(($)=>$.app.actions),M8=()=>n(($)=>$.app.initializationStatus==="ready"),L4=()=>n(($)=>$.app.tasks.length>0),v$=()=>n(($)=>$.config.config?.permissionMode||"default"),B4=()=>n(($)=>$.config.config?.models??NY),C8=()=>n(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),I8=()=>n(($)=>$.config.config?.currentModelId),A0=()=>n(($)=>{return r0.getTheme()}),w4=()=>n(($)=>$.config.config?.codeTheme??"default"),e0=()=>n(($)=>$.focus.currentFocus),b4=()=>n(($)=>$.focus.actions),s1=()=>n(($)=>$.command.isProcessing),A4=()=>n(($)=>$.command.actions),T8=()=>n(($)=>$.command.pendingCommands),P4=()=>n(($)=>$.command.recoveredSteeringCount),k8=()=>n(($)=>$.app.thinkingModeEnabled),f8=()=>n(($)=>$.app.reasoningEffort),S8=()=>n(($)=>$.app.serviceTier),v8=()=>n(($)=>$.app.responseVerbosity),D8=()=>n(($)=>$.app.communicationStyle),R4=()=>n(($)=>$.session.currentThinkingContent),y4=()=>n(($)=>$.session.thinkingExpanded),M4=()=>n(($)=>$.session.currentStreamingMessageId),C4=()=>n(_Y(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),I4=()=>n(($)=>$.session.finalizingStreamingMessageId),T4=()=>n(($)=>$.session.historyExpanded),k4=()=>n(($)=>$.session.expandedMessageCount);import{useMemoizedFn as h$}from"ahooks";import{useEffect as d8,useRef as n4}from"react";function FY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let G=JSON.parse(J.responseBody)?.error?.message;if(G){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${G}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function HY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function WY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function V8($){let Q=HY($),Y=WY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=FY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as LY,mkdirSync as BY,writeFileSync as wY}from"node:fs";import bY from"node:os";import E2 from"node:path";var f4=null;function AY(){let $=process.env.BLADE_STORAGE_ROOT||E2.join(bY.homedir(),".blade");return E2.join($,"logs","stream-debug.log")}function PY($){if(f4===$)return;let Q=E2.dirname($);BY(Q,{recursive:!0,mode:493}),wY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),f4=$}function g2($,Q,Y){try{let J=AY();PY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",G=`[${Z}] [${$}] ${Q}${X}
3
3
  `;LY(J,G)}catch{}}var J8=e1("UI");function j4($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,g2("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),J8.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),g2("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),G=$.getStreamingMessageId();if(G){if(Z)D$(G,Z);h8(G)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;if(J8.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),G=D4(Z.function.name,X);$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:G,params:X})}catch(X){J8.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",G=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(G,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:G,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===j8)break;J8.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=v4(V4(Z.function.name,J.result),S4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":J8.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -1,4 +1,4 @@
1
- import{Db as Xt,Eb as bn,Fb as Tn,Gb as fn}from"./chunk-mrsc4a55.js";import{Ec as jt}from"./chunk-0qsssahq.js";import{Je as Bt}from"./chunk-e1vyznkn.js";import{$e as pn,Oe as xt,Pe as tn,Qe as en,Re as zt,Se as U,Te as rn,Ue as gt,Ve as mt,Xe as dn,Ye as En,Ze as B,_e as on,af as cn,bf as lt,cf as un,df as Mn,ef as wn,gf as S,jf as yn,kf as Ht,lf as Ut,mf as h,nf as qt}from"./chunk-6ch7a6xf.js";import{Tf as X,Vf as x}from"./chunk-m8ss9rmx.js";import{dg as vt}from"./chunk-kfpzrmq7.js";import{Sg as nn,Tg as sn}from"./chunk-vbpykrxd.js";import{hh as ss}from"./chunk-hfrcwkc8.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Db as Xt,Eb as bn,Fb as Tn,Gb as fn}from"./chunk-mrsc4a55.js";import{Ec as jt}from"./chunk-0qsssahq.js";import{Je as Bt}from"./chunk-706zda55.js";import{$e as pn,Oe as xt,Pe as tn,Qe as en,Re as zt,Se as U,Te as rn,Ue as gt,Ve as mt,Xe as dn,Ye as En,Ze as B,_e as on,af as cn,bf as lt,cf as un,df as Mn,ef as wn,gf as S,jf as yn,kf as Ht,lf as Ut,mf as h,nf as qt}from"./chunk-wx5nj2s2.js";import{Tf as X,Vf as x}from"./chunk-m8ss9rmx.js";import{dg as vt}from"./chunk-kfpzrmq7.js";import{Sg as nn,Tg as sn}from"./chunk-j0k3mbkd.js";import{hh as ss}from"./chunk-hfrcwkc8.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1 +1 @@
1
- import{Ad as i,Bd as j,Cd as k,Dd as l,Ed as m,Fd as n,Gd as o,Hd as p,Id as q,sd as a,td as b,ud as c,vd as d,wd as e,xd as f,yd as g,zd as h}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.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{Ad as i,Bd as j,Cd as k,Dd as l,Ed as m,Fd as n,Gd as o,Hd as p,Id as q,sd as a,td as b,ud as c,vd as d,wd as e,xd as f,yd as g,zd as h}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.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{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-372mmzj3.js";import{N as M,V as y}from"./chunk-c8ddch38.js";import"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import{lb as h,ub as A}from"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import{Ac as U,mc as w}from"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{Xc as C}from"./chunk-t2r7tqn0.js";import{$c as v,Zc as I,_c as S}from"./chunk-nynfqgsj.js";import{ad as O}from"./chunk-v9tzhe90.js";import"./chunk-fk4wbmv6.js";import{xd as P}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import{Sf as F}from"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as z}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-s4denzh4.js";import{N as M,V as y}from"./chunk-aw7w91f0.js";import"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import{lb as h,ub as A}from"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import{Ac as U,mc as w}from"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{Xc as C}from"./chunk-1vydfzvy.js";import{$c as v,Zc as I,_c as S}from"./chunk-n4ywszmn.js";import{ad as O}from"./chunk-v9tzhe90.js";import"./chunk-fk4wbmv6.js";import{xd as P}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import{Sf as F}from"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as z}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -25,7 +25,7 @@ import{Ne as YO}from"./chunk-cxzx7j0p.js";import{Tf as qO,Vf as S,Yf as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-pyk2ey7y.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-qmcj20g2.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-619q1w65.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-t33njg4e.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1,2 +1,2 @@
1
- import{Qf as F}from"./chunk-6ch7a6xf.js";import{Jg as D,Kg as E}from"./chunk-26wse17p.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{Qf as F}from"./chunk-wx5nj2s2.js";import{Jg as D,Kg as E}from"./chunk-26wse17p.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as Yd,Q as Zd,T as _d};
@@ -1,4 +1,4 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-32g59k4p.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-qnxgzyyx.js";import"./chunk-x2vqgssm.js";import"./chunk-txkrtgcd.js";import"./chunk-c8ddch38.js";import"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as R}from"./chunk-yqy000kg.js";import"./chunk-fk4wbmv6.js";import{yd as Q}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Sg as M}from"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import m from"chalk";import K from"open";var A=`
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-fk0q25dp.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-p4egmgt6.js";import"./chunk-svj24r6g.js";import"./chunk-d18mw6d1.js";import"./chunk-aw7w91f0.js";import"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as R}from"./chunk-cf2541w5.js";import"./chunk-fk4wbmv6.js";import{yd as Q}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import{Sg as M}from"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-z9absgab.js";import"./chunk-j0k3mbkd.js";import"./chunk-hfrcwkc8.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +1 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-32g59k4p.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-qnxgzyyx.js";import"./chunk-x2vqgssm.js";import"./chunk-txkrtgcd.js";import"./chunk-c8ddch38.js";import"./chunk-7s5hw0gr.js";import"./chunk-y6tkxqjx.js";import"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as n}from"./chunk-yqy000kg.js";import"./chunk-fk4wbmv6.js";import{yd as s}from"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-jpz805fs.js";import"./chunk-yypnfmed.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{f as a,g as i,h as l,i as m}from"./chunk-fk0q25dp.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-p4egmgt6.js";import"./chunk-svj24r6g.js";import"./chunk-d18mw6d1.js";import"./chunk-aw7w91f0.js";import"./chunk-583kv07t.js";import"./chunk-y6tkxqjx.js";import"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as n}from"./chunk-cf2541w5.js";import"./chunk-fk4wbmv6.js";import{yd as s}from"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-74hcqcn7.js";import"./chunk-m1b6v1zn.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1 +1 @@
1
- import{$c as c,Zc as a,_c as b}from"./chunk-nynfqgsj.js";import"./chunk-v9tzhe90.js";import"./chunk-w5ayh9b8.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-sqd5ge5s.js";import"./chunk-6ch7a6xf.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{$c as c,Zc as a,_c as b}from"./chunk-n4ywszmn.js";import"./chunk-v9tzhe90.js";import"./chunk-r085zhqr.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-sqd5ge5s.js";import"./chunk-wx5nj2s2.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +1 @@
1
- import{Ab as p,Bb as q,Cb as r,cb as a,db as b,fb as c,jb as d,kb as e,lb as f,mb as g,nb as h,ob as i,pb as j,qb as k,vb as l,wb as m,xb as n,yb as o}from"./chunk-dcp5gg6q.js";import"./chunk-mrsc4a55.js";import"./chunk-ag5ea7ce.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-qp2z1r7y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-e1vyznkn.js";import"./chunk-cxzx7j0p.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-vbpykrxd.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.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{Ab as p,Bb as q,Cb as r,cb as a,db as b,fb as c,jb as d,kb as e,lb as f,mb as g,nb as h,ob as i,pb as j,qb as k,vb as l,wb as m,xb as n,yb as o}from"./chunk-x3cyg9pe.js";import"./chunk-mrsc4a55.js";import"./chunk-g96t2yrz.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-qp2z1r7y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-706zda55.js";import"./chunk-cxzx7j0p.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-j0k3mbkd.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.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,4 +1,4 @@
1
- import{ma as R,na as u0,sa as kJ,ta as F9,ua as g0}from"./chunk-7s5hw0gr.js";import{Oa as w3,va as q3,xa as D3,ya as m4}from"./chunk-y6tkxqjx.js";import{$a as J9,Cb as v9,Pa as E$,Qa as Q1,Ra as $9,Sa as l$,Ta as c8,Ua as t9,Ya as Q0,_a as x2,ab as Y9,bb as X9,eb as a2,gb as p6,hb as t2,ib as o2,lb as J$,rb as H5,sb as bJ,tb as i7,zb as k9}from"./chunk-dcp5gg6q.js";import{Ac as n,Ib as K0,Jb as L1,Kb as y$,Lb as U2,Mb as n4,Nb as r2,Ob as n2,Yb as Q5,Zb as _0,_b as o0,hc as a4,ic as m0,jc as V1,kc as UJ,lc as QJ,oc as CJ,sc as f9,xc as VJ,yc as GJ}from"./chunk-ag5ea7ce.js";import{Bc as h,Cc as $7,Dc as Z7,Ec as k2}from"./chunk-0qsssahq.js";import{Fc as E3,Ic as b3,Qc as N3,Wc as A3}from"./chunk-56qew7w0.js";import{fd as gZ,gd as xZ}from"./chunk-fk4wbmv6.js";import{Ad as M$,Bd as Y4,Cd as d$,Dd as P9,Id as W1,sd as s2,td as O0,ud as f,xd as B0,yd as h2,zd as z1}from"./chunk-w5ayh9b8.js";import{Jd as H$}from"./chunk-wwvb6znp.js";import{Nd as S9,Od as C9,Rd as FJ,Sd as g2}from"./chunk-egczvfsv.js";import{Ud as C0,Vd as I$}from"./chunk-7fqsgdee.js";import{Wd as AJ}from"./chunk-qp2z1r7y.js";import{Yd as ZJ,Zd as JJ,_d as YJ}from"./chunk-jpz805fs.js";import{$d as p2,ae as c2,ce as l2,de as i2,ee as f$,fe as U7,he as v0,ie as v3,je as y0,ke as r0,le as v5,me as V5,ne as Q$,oe as s$,pe as e$,qe as WJ,re as b4,te as W0,ue as u2,ve as KJ}from"./chunk-yypnfmed.js";import{Ae as T2,xe as K1,ze as Z$}from"./chunk-tpa75y39.js";import{Be as pJ,De as XJ,Ee as U5,Fe as uZ}from"./chunk-2yvte5a7.js";import{He as y4,Je as N0}from"./chunk-e1vyznkn.js";import{Ke as s1,Le as r4,Me as e1,Ne as Z1}from"./chunk-cxzx7j0p.js";import{$e as fJ,Bf as D9,Cf as w9,Df as L9,Ef as E9,Ff as Z4,Gf as b9,Hf as T$,If as N9,Jf as A9,Kf as j9,Mf as OZ,Of as HJ,Pe as AZ,Pf as $J,Qf as X0,Ue as jZ,We as S4,df as TZ,ff as o7,hf as s8,if as e8,of as r$,rf as r8}from"./chunk-6ch7a6xf.js";import{Tf as V2,Uf as P5,Vf as O,Wf as Q7,Xf as S,Yf as l}from"./chunk-m8ss9rmx.js";import{$f as l7,_f as c7}from"./chunk-j7edwwg1.js";import{bg as B2,dg as C}from"./chunk-kfpzrmq7.js";import{Eg as i}from"./chunk-fhnkyqfb.js";import{Jg as s7,Kg as e7}from"./chunk-26wse17p.js";import{Lg as lJ,Og as dJ}from"./chunk-hcm55r3d.js";import{Sg as aJ}from"./chunk-vbpykrxd.js";import{Xg as f0}from"./chunk-bvf9syb2.js";import{_g as W2,ah as A$,ch as t7,dh as QZ,fh as L0}from"./chunk-qb0sqh29.js";import{hh as W$}from"./chunk-hfrcwkc8.js";import{randomUUID as M5}from"crypto";import{randomUUID as d3}from"node:crypto";var y3=String.raw`
1
+ import{ma as R,na as u0,sa as kJ,ta as F9,ua as g0}from"./chunk-583kv07t.js";import{Oa as w3,va as q3,xa as D3,ya as m4}from"./chunk-y6tkxqjx.js";import{$a as J9,Cb as v9,Pa as E$,Qa as Q1,Ra as $9,Sa as l$,Ta as c8,Ua as t9,Ya as Q0,_a as x2,ab as Y9,bb as X9,eb as a2,gb as p6,hb as t2,ib as o2,lb as J$,rb as H5,sb as bJ,tb as i7,zb as k9}from"./chunk-x3cyg9pe.js";import{Ac as n,Ib as K0,Jb as L1,Kb as y$,Lb as U2,Mb as n4,Nb as r2,Ob as n2,Yb as Q5,Zb as _0,_b as o0,hc as a4,ic as m0,jc as V1,kc as UJ,lc as QJ,oc as CJ,sc as f9,xc as VJ,yc as GJ}from"./chunk-g96t2yrz.js";import{Bc as h,Cc as $7,Dc as Z7,Ec as k2}from"./chunk-0qsssahq.js";import{Fc as E3,Ic as b3,Qc as N3,Wc as A3}from"./chunk-56qew7w0.js";import{fd as gZ,gd as xZ}from"./chunk-fk4wbmv6.js";import{Ad as M$,Bd as Y4,Cd as d$,Dd as P9,Id as W1,sd as s2,td as O0,ud as f,xd as B0,yd as h2,zd as z1}from"./chunk-r085zhqr.js";import{Jd as H$}from"./chunk-wwvb6znp.js";import{Nd as S9,Od as C9,Rd as FJ,Sd as g2}from"./chunk-egczvfsv.js";import{Ud as C0,Vd as I$}from"./chunk-7fqsgdee.js";import{Wd as AJ}from"./chunk-qp2z1r7y.js";import{Yd as ZJ,Zd as JJ,_d as YJ}from"./chunk-74hcqcn7.js";import{$d as p2,ae as c2,ce as l2,de as i2,ee as f$,fe as U7,he as v0,ie as v3,je as y0,ke as r0,le as v5,me as V5,ne as Q$,oe as s$,pe as e$,qe as WJ,re as b4,te as W0,ue as u2,ve as KJ}from"./chunk-m1b6v1zn.js";import{Ae as T2,xe as K1,ze as Z$}from"./chunk-tpa75y39.js";import{Be as pJ,De as XJ,Ee as U5,Fe as uZ}from"./chunk-2yvte5a7.js";import{He as y4,Je as N0}from"./chunk-706zda55.js";import{Ke as s1,Le as r4,Me as e1,Ne as Z1}from"./chunk-cxzx7j0p.js";import{$e as fJ,Bf as D9,Cf as w9,Df as L9,Ef as E9,Ff as Z4,Gf as b9,Hf as T$,If as N9,Jf as A9,Kf as j9,Mf as OZ,Of as HJ,Pe as AZ,Pf as $J,Qf as X0,Ue as jZ,We as S4,df as TZ,ff as o7,hf as s8,if as e8,of as r$,rf as r8}from"./chunk-wx5nj2s2.js";import{Tf as V2,Uf as P5,Vf as O,Wf as Q7,Xf as S,Yf as l}from"./chunk-m8ss9rmx.js";import{$f as l7,_f as c7}from"./chunk-j7edwwg1.js";import{bg as B2,dg as C}from"./chunk-kfpzrmq7.js";import{Eg as i}from"./chunk-fhnkyqfb.js";import{Jg as s7,Kg as e7}from"./chunk-26wse17p.js";import{Lg as lJ,Og as dJ}from"./chunk-hcm55r3d.js";import{Sg as aJ}from"./chunk-j0k3mbkd.js";import{Xg as f0}from"./chunk-bvf9syb2.js";import{_g as W2,ah as A$,ch as t7,dh as QZ,fh as L0}from"./chunk-qb0sqh29.js";import{hh as W$}from"./chunk-hfrcwkc8.js";import{randomUUID as M5}from"crypto";import{randomUUID as d3}from"node:crypto";var y3=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -776,7 +776,7 @@ ${o}
776
776
  </approved-plan>
777
777
 
778
778
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")v=H+d;else v=[...H,{type:"text",text:d}]}P=yield*this.runLoop(v,B,{...j,inputMessageId:void 0})}if(!this.sessionRuntime||!N)return P;let I=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(I)yield{kind:"goal_updated",goal:I};if(!P.success||B.signal?.aborted){if(I=await this.sessionRuntime.pauseActiveGoal(B.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),I)yield{kind:"goal_updated",goal:I}}if(P.success&&!B.signal?.aborted&&E<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(N,B.signal);let $0=P.success&&!B.signal?.aborted&&E<20,k=UU(P);if(b=await this.sessionRuntime.finishTurn(N,{continuePending:$0,...k?{acknowledgeInput:!0}:{},outcome:P.success&&!B.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:B.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),b){E++,F=!0,_=!1,D=null,H="",w=void 0,q=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:M()};continue}if(!P.success||B.signal?.aborted)return P;if(I=await this.sessionRuntime.getGoal(),!I||I.status!=="active"&&I.status!=="verifying")return P;if(D=await this.sessionRuntime.beginGoalContinuation(),!D)return P;b=await this.sessionRuntime.beginTurn("goal"),F=!1,_=!0,H=W6(D),w=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:D,continuation:D.continuationCount},yield{kind:"goal_updated",goal:D}}}finally{if(this.sessionRuntime&&b)await this.sessionRuntime.finishTurn(b)}}let G=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
779
- `),z={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-m8a2qj5c.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await m$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=C1($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];X=$.map((Q)=>Q===U?{type:"text",text:C1(U.text)}:Q)}else X=[{type:"text",text:C1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await m$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return v9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,Q={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],G=k9(Y,Q);if(G)V.push(G);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await m$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await d2({sessionId:"default",configDir:y9.join(I9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await F2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=g0.createIsolated({artifactWriter:new M1(`legacy-${WU()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),p.debug(`MCP server "${W}" connected`)}catch(Q){p.warn(`Warning: MCP server "${W}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(k1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await W0(C());if(this.agentResources=u2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let W=X.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
779
+ `),z={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-agbyfdvw.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await m$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=C1($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];X=$.map((Q)=>Q===U?{type:"text",text:C1(U.text)}:Q)}else X=[{type:"text",text:C1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await m$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return v9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,Q={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],G=k9(Y,Q);if(G)V.push(G);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await m$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await d2({sessionId:"default",configDir:y9.join(I9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await F2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=g0.createIsolated({artifactWriter:new M1(`legacy-${WU()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),p.debug(`MCP server "${W}" connected`)}catch(Q){p.warn(`Warning: MCP server "${W}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(k1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await W0(C());if(this.agentResources=u2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let W=X.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
780
780
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(Y);if(!X)return $;return[...$,{type:"text",text:X}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let W=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${W?` range="${W}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let Y="";if(Z.length>0)Y+=`
781
781
 
782
782
  <system-reminder>
@@ -1574,7 +1574,7 @@ ${J}
1574
1574
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1575
1575
  `)}}case"create":{let Q=Az(W);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:U,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let G=await $.create(V),z=G.nextRunAt?new Date(G.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${G.id}\`
1576
1576
  ${m4(G.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${G.id} created`}}catch(G){let z=G instanceof Error?G.message:String(G);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let Q=W[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=W[0];if(!Q)return Y.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,X==="enable");return Y.sendMessage(V?`[OK] 已${X==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=W[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await jz(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let G=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${G}`),{success:!1,error:G}}}default:return Y.sendMessage(`未知子命令: ${X}
1577
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var L3=Tz();import*as D1 from"node:fs/promises";import*as w1 from"node:path";async function j3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:W}=Z,U=W??W2(X??C());if(!W){let H=await Mz($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await D1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>w1.join(U,B))}catch{return[]}let G=(await Promise.all(Q.map(async(H)=>{try{let B=await D1.stat(H);return{path:H,mtime:B.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,B)=>B.mtime-H.mtime).map((H)=>H.path),z=[],K=Y?$:$.toLowerCase();for(let H of G){if(z.length>=J)break;let B=w1.basename(H,".jsonl"),F=await Cz(H,K,Y,B);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function Mz($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-z1aqe7ms.js"),W=await N3();if(!W)return null;let{SessionService:U}=await import("./chunk-5wzjdfde.js");await X(W,U.projectionDeriverForSearch());let Q=w1.resolve(Z),V=A3(W,$,Q,J*4),G=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=p4(K.text,G,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)z.push(H);if(z.length>=J)break}return z}catch{return null}}async function Cz($,Z,J,Y){try{let X=await D1.readFile($,"utf8"),U=X.split(`
1577
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var L3=Tz();import*as D1 from"node:fs/promises";import*as w1 from"node:path";async function j3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:W}=Z,U=W??W2(X??C());if(!W){let H=await Mz($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await D1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>w1.join(U,B))}catch{return[]}let G=(await Promise.all(Q.map(async(H)=>{try{let B=await D1.stat(H);return{path:H,mtime:B.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,B)=>B.mtime-H.mtime).map((H)=>H.path),z=[],K=Y?$:$.toLowerCase();for(let H of G){if(z.length>=J)break;let B=w1.basename(H,".jsonl"),F=await Cz(H,K,Y,B);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function Mz($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-z1aqe7ms.js"),W=await N3();if(!W)return null;let{SessionService:U}=await import("./chunk-tzp486wc.js");await X(W,U.projectionDeriverForSearch());let Q=w1.resolve(Z),V=A3(W,$,Q,J*4),G=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=p4(K.text,G,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)z.push(H);if(z.length>=J)break}return z}catch{return null}}async function Cz($,Z,J,Y){try{let X=await D1.readFile($,"utf8"),U=X.split(`
1578
1578
  `).flatMap((K,H)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:H}]}catch{return[]}});if(!U.some(({event:K})=>K.type==="session_created"))return Rz(U,Z,J,Y);let V=new Map(U.flatMap(({event:K,index:H})=>typeof K.id==="string"?[[K.id,H+1]]:[])),G=E3(b3(X,$)),z=new Map;for(let K of G){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))z.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let H=z.get(K.data.messageId),B=K.data.payload.text;if(H&&typeof B==="string")H.content.push(B)}}return[...z.values()].flatMap((K)=>{let H=p4(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return H?[H]:[]})}catch{return[]}}function Rz($,Z,J,Y){return $.flatMap(({event:X,index:W})=>{if(X.type!=="message")return[];let U=X.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let Q=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((G)=>typeof G==="object"&&G!==null&&G.type==="text"&&typeof G.text==="string").map((G)=>G.text).join(" "):"",V=p4(Q,Z,J,Y,U.role,typeof X.timestamp==="string"?X.timestamp:void 0,W+1);return V?[V]:[]})}function p4($,Z,J,Y,X,W,U){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),G=Math.max(0,V-80),z=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:X,content:(G>0?"...":"")+$.slice(G,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:W,lineNumber:U}}function T3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1579
1579
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",X=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${X} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1580
1580
  `)}var Pz={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=x(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let X=await j3(Y,{maxResults:15,projectPath:Z.cwd}),W=T3(X);return J.sendMessage(W),{success:!0,message:`found ${X.length} results`,data:{matches:X.length}}}catch(X){let W=X instanceof Error?X.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},M3=Pz;var Sz={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await v0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),e$(Z.workspaceRoot??Z.cwd),await s$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},C3=Sz;import fz from"node:path";function L5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function R3($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function P3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function kz($,Z){let J=x(Z),Y=$[0],X=a.getInstance(),W=Z0.getInstance(),U=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:fz.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let B=$[1],F=$.slice(2).join(" ").trim();if(!B||!F)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let _=await Z.subagents.resume(B,F),q=`Resumed \`${B}\` as \`${_.session.id}\` (depth ${_.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:B,subagent:_.session}}}if(Y==="clean"){let B=W.cleanupExpiredSessionsForParent(Q??U,0);return J.sendMessage(`已清理 ${B} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${B} agent sessions`}}let V=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{td as N}from"./chunk-w5ayh9b8.js";import{Je as $}from"./chunk-e1vyznkn.js";import{dg as _}from"./chunk-kfpzrmq7.js";import{Cg as Y,Eg as Z}from"./chunk-fhnkyqfb.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{td as N}from"./chunk-r085zhqr.js";import{Je as $}from"./chunk-706zda55.js";import{dg as _}from"./chunk-kfpzrmq7.js";import{Cg as Y,Eg as Z}from"./chunk-fhnkyqfb.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as bd,y as cd,j as dd,C as ed};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-d5x5wknc.js";import"./chunk-vbpykrxd.js";import"./chunk-hfrcwkc8.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-z9absgab.js";import"./chunk-j0k3mbkd.js";import"./chunk-hfrcwkc8.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,2 +1,2 @@
1
- import{K as I}from"./chunk-c8ddch38.js";import{Ac as D}from"./chunk-ag5ea7ce.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
1
+ import{K as I}from"./chunk-aw7w91f0.js";import{Ac as D}from"./chunk-g96t2yrz.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
2
2
  export{z as v,N as w,Z as x,_ as y,c as z,F as A};
@@ -1,4 +1,4 @@
1
- import{j as Q4,k as X4}from"./chunk-8vtyatd6.js";import{l as o$}from"./chunk-f4sp074f.js";import{s as J$,t as y1}from"./chunk-qnxgzyyx.js";import{u as d0}from"./chunk-x2vqgssm.js";import{A as dO,v as j1,w as vO,x as uO,y as pO,z as r0}from"./chunk-txkrtgcd.js";import{$ as t1,C as B4,F as T1,G as X$,H as LO,I as l$,J as VO,K as q0,L as NO,M as e0,N as w$,Q as C$,R as j$,T as b1,U as q1,V as C1,W as c1,X as i1,Y as a1,Z as o1,_ as n1,aa as r1,ba as s1,ca as e1,da as Y4,ga as S4,la as L4}from"./chunk-c8ddch38.js";import{oa as $1,ua as U0}from"./chunk-7s5hw0gr.js";import{Aa as M4,Ba as I1,Ca as k1,Da as E4,Ea as wO,Fa as T4,Ga as i0,Ha as K4,Ia as V4,Ja as N4,Ka as P1,La as S1,Ma as f1,Na as mO,Oa as RO,wa as $O,za as A4}from"./chunk-y6tkxqjx.js";import{Va as S0,Wa as v,Ya as q,Za as R1,lb as KO,ub as l0}from"./chunk-dcp5gg6q.js";import{Db as B1}from"./chunk-mrsc4a55.js";import{Ac as j,Wb as L1,Yb as c$,cc as b$,dc as UO,ec as q$,gc as w1,mc as A1,nc as M1,pc as x$,sc as QO,xc as E1,yc as XO,zc as zO}from"./chunk-ag5ea7ce.js";import{Bd as x1,Id as w0,xd as J0}from"./chunk-w5ayh9b8.js";import{Jd as YO}from"./chunk-wwvb6znp.js";import{Xd as H1}from"./chunk-qp2z1r7y.js";import{Zd as d$}from"./chunk-jpz805fs.js";import{ge as U4,he as F4,ke as l1,oe as B$,pe as L$,te as _0}from"./chunk-yypnfmed.js";import{De as Y1,Ee as _1}from"./chunk-2yvte5a7.js";import{Ie as tO,Je as $$}from"./chunk-e1vyznkn.js";import{$e as eO,Lf as rO,Qf as _$,tf as U1,wf as F1,yf as D1}from"./chunk-6ch7a6xf.js";import{Tf as g,Vf as F,Yf as W0}from"./chunk-m8ss9rmx.js";import{_f as i$}from"./chunk-j7edwwg1.js";import{dg as i}from"./chunk-kfpzrmq7.js";import{Eg as a}from"./chunk-fhnkyqfb.js";import{Kg as p0}from"./chunk-26wse17p.js";import{Mg as J1,Ng as G1,Pg as Z1,Qg as W1}from"./chunk-hcm55r3d.js";import{Sg as s0}from"./chunk-vbpykrxd.js";import{Xg as TO}from"./chunk-bvf9syb2.js";import{ah as v$,eh as cO}from"./chunk-qb0sqh29.js";import{hh as AO}from"./chunk-hfrcwkc8.js";var v5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function u5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as bO,readFileSync as P$}from"node:fs";import{createServer as H5}from"node:http";import{networkInterfaces as _5}from"node:os";import{dirname as B5,extname as L5,join as h0}from"node:path";import{fileURLToPath as w5}from"node:url";import{brotliCompressSync as A5,gzipSync as M5,constants as E5}from"node:zlib";import{Hono as T5}from"hono";import{cors as R5}from"hono/cors";import{WebSocketServer as b5}from"ws";var t0=a("Service"),d4=30000,l4=new Set(["completed","failed","cancelled","interrupted"]);class OO{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??mO.getInstance(),this.tickMs=$.tickMs??d4}start(){if(this.timer)return;t0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=q.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!l4.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,t0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){t0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),t0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let x=await this.dispatch({prompt:$.prompt,title:$.title??c4($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:$O($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:x.session.sessionId,lastStatus:x.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),q.publish({sessionId:x.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:x.session.sessionId,runId:x.runId,status:x.status}),t0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${x.session.sessionId} (${x.status})`)}catch(x){let z=x instanceof Error?x.message:String(x);t0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,x);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:$O($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let x=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!x)return;await this.store.update(x.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function c4($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor($,O,J=500,Z){super(O);this.code=$;this.statusCode=J;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class m extends Z0{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class L extends Z0{constructor($){super("BAD_REQUEST",$,400)}}class C extends Z0{constructor($){super("CONFLICT",$,409)}}class v0 extends Z0{constructor($,O){super("TOO_MANY_REQUESTS",$,429,O)}}class u0 extends Z0{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class L0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class e extends Z0{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var n5=F.Object({error:F.Object({code:F.String(),message:F.String(),details:F.Optional(F.Record(F.String(),F.Unknown()))})});import{Hono as i4}from"hono";var JO=a("Service"),a4=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(W0(["local","project","global"])),immediate:F.Optional(F.Boolean())}))});function o4($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks,maxQueuedTaskBytes:$.maxQueuedTaskBytes,maxResidentSessionRuntimes:$.maxResidentSessionRuntimes,sessionRuntimeIdleMs:$.sessionRuntimeIdleMs}}var hO=()=>{let $=new i4;return $.get("/",async(O)=>{try{let J=J0();return O.json(J?o4(J):{})}catch(J){return JO.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=g(a4,J);if(!Z.success)throw new L("Invalid config update format");let{updates:x,options:z}=Z.data;return await w0().updateConfig(x,z),O.json({success:!0,updates:x})}catch(J){throw JO.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=J0();return O.json(J?.permissions||{})}catch(J){return JO.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as n4}from"hono";import{streamSSE as t4}from"hono/streaming";function gO($){let O="";if($.id!==void 0)O+=`id: ${$.id}
1
+ import{j as Q4,k as X4}from"./chunk-8vtyatd6.js";import{l as o$}from"./chunk-f4sp074f.js";import{s as J$,t as y1}from"./chunk-p4egmgt6.js";import{u as d0}from"./chunk-svj24r6g.js";import{A as dO,v as j1,w as vO,x as uO,y as pO,z as r0}from"./chunk-d18mw6d1.js";import{$ as t1,C as B4,F as T1,G as X$,H as LO,I as l$,J as VO,K as q0,L as NO,M as e0,N as w$,Q as C$,R as j$,T as b1,U as q1,V as C1,W as c1,X as i1,Y as a1,Z as o1,_ as n1,aa as r1,ba as s1,ca as e1,da as Y4,ga as S4,la as L4}from"./chunk-aw7w91f0.js";import{oa as $1,ua as U0}from"./chunk-583kv07t.js";import{Aa as M4,Ba as I1,Ca as k1,Da as E4,Ea as wO,Fa as T4,Ga as i0,Ha as K4,Ia as V4,Ja as N4,Ka as P1,La as S1,Ma as f1,Na as mO,Oa as RO,wa as $O,za as A4}from"./chunk-y6tkxqjx.js";import{Va as S0,Wa as v,Ya as q,Za as R1,lb as KO,ub as l0}from"./chunk-x3cyg9pe.js";import{Db as B1}from"./chunk-mrsc4a55.js";import{Ac as j,Wb as L1,Yb as c$,cc as b$,dc as UO,ec as q$,gc as w1,mc as A1,nc as M1,pc as x$,sc as QO,xc as E1,yc as XO,zc as zO}from"./chunk-g96t2yrz.js";import{Bd as x1,Id as w0,xd as J0}from"./chunk-r085zhqr.js";import{Jd as YO}from"./chunk-wwvb6znp.js";import{Xd as H1}from"./chunk-qp2z1r7y.js";import{Zd as d$}from"./chunk-74hcqcn7.js";import{ge as U4,he as F4,ke as l1,oe as B$,pe as L$,te as _0}from"./chunk-m1b6v1zn.js";import{De as Y1,Ee as _1}from"./chunk-2yvte5a7.js";import{Ie as tO,Je as $$}from"./chunk-706zda55.js";import{$e as eO,Lf as rO,Qf as _$,tf as U1,wf as F1,yf as D1}from"./chunk-wx5nj2s2.js";import{Tf as g,Vf as F,Yf as W0}from"./chunk-m8ss9rmx.js";import{_f as i$}from"./chunk-j7edwwg1.js";import{dg as i}from"./chunk-kfpzrmq7.js";import{Eg as a}from"./chunk-fhnkyqfb.js";import{Kg as p0}from"./chunk-26wse17p.js";import{Mg as J1,Ng as G1,Pg as Z1,Qg as W1}from"./chunk-hcm55r3d.js";import{Sg as s0}from"./chunk-j0k3mbkd.js";import{Xg as TO}from"./chunk-bvf9syb2.js";import{ah as v$,eh as cO}from"./chunk-qb0sqh29.js";import{hh as AO}from"./chunk-hfrcwkc8.js";var v5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function u5($){return{port:$.port??0,hostname:$.hostname??"127.0.0.1",cors:$.cors??[]}}import{existsSync as bO,readFileSync as P$}from"node:fs";import{createServer as H5}from"node:http";import{networkInterfaces as _5}from"node:os";import{dirname as B5,extname as L5,join as h0}from"node:path";import{fileURLToPath as w5}from"node:url";import{brotliCompressSync as A5,gzipSync as M5,constants as E5}from"node:zlib";import{Hono as T5}from"hono";import{cors as R5}from"hono/cors";import{WebSocketServer as b5}from"ws";var t0=a("Service"),d4=30000,l4=new Set(["completed","failed","cancelled","interrupted"]);class OO{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor($){this.dispatch=$.dispatch,this.store=$.store??mO.getInstance(),this.tickMs=$.tickMs??d4}start(){if(this.timer)return;t0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=q.subscribe(($)=>{if($.type!=="task.status")return;let O=$.properties.taskStatus;if(typeof O!=="string"||!l4.has(O))return;this.recordTerminalStatus($.sessionId,O,typeof $.properties.taskStatusReason==="string"?$.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,t0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick($=new Date){if(this.ticking)return;this.ticking=!0;try{let O=await this.store.list();for(let J of O)await this.evaluate(J,$)}catch(O){t0.warn("[TaskScheduler] Tick failed:",O)}finally{this.ticking=!1}}async evaluate($,O){if(!$.enabled)return;if(this.inFlight.has($.id))return;if($.expiresAt&&new Date($.expiresAt).getTime()<=O.getTime()){await this.store.update($.id,{enabled:!1,nextRunAt:null}),t0.info(`[TaskScheduler] Schedule ${$.id} expired; disabled`);return}if(!$.nextRunAt)return;if(!(new Date($.nextRunAt).getTime()<=O.getTime()))return;await this.fire($,O)}async fire($,O=new Date,J={}){if(this.inFlight.has($.id))throw Error(`Schedule ${$.id} is already dispatching`);this.inFlight.add($.id);let Z=O.toISOString();try{let x=await this.dispatch({prompt:$.prompt,title:$.title??c4($),sourceProjectPath:$.projectPath,isolation:$.dispatch.isolation??"worktree",permissionMode:$.dispatch.permissionMode??"default",modelId:$.dispatch.modelId,reasoningEffort:$.dispatch.reasoningEffort,serviceTier:$.dispatch.serviceTier,responseVerbosity:$.dispatch.responseVerbosity,communicationStyle:$.dispatch.communicationStyle}),z=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:$O($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastRunSessionId:x.session.sessionId,lastStatus:x.status,lastError:void 0,runCount:$.runCount+1,nextRunAt:z?z.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled}),q.publish({sessionId:x.session.sessionId,projectPath:$.projectPath},"schedule.fired",{scheduleId:$.id,firedAt:Z,sessionId:x.session.sessionId,runId:x.runId,status:x.status}),t0.info(`[TaskScheduler] Fired schedule ${$.id} -> session ${x.session.sessionId} (${x.status})`)}catch(x){let z=x instanceof Error?x.message:String(x);t0.warn(`[TaskScheduler] Schedule ${$.id} dispatch failed:`,x);let X=$.trigger.kind==="once"?null:J.manual?$.nextRunAt?new Date($.nextRunAt):null:$O($.trigger,O,O);await this.store.update($.id,{lastRunAt:Z,lastStatus:"error",lastError:z,nextRunAt:X?X.toISOString():null,enabled:$.trigger.kind==="once"?!1:$.enabled})}finally{this.inFlight.delete($.id)}}async recordTerminalStatus($,O,J){let x=(await this.store.list()).find((z)=>z.lastRunSessionId===$);if(!x)return;await this.store.update(x.id,{lastStatus:O,...J?{lastError:J}:{lastError:void 0}})}}function c4($){return`Scheduled: ${$.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor($,O,J=500,Z){super(O);this.code=$;this.statusCode=J;this.details=Z;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class m extends Z0{constructor($,O){super("NOT_FOUND",O?`${$} not found: ${O}`:`${$} not found`,404)}}class L extends Z0{constructor($){super("BAD_REQUEST",$,400)}}class C extends Z0{constructor($){super("CONFLICT",$,409)}}class v0 extends Z0{constructor($,O){super("TOO_MANY_REQUESTS",$,429,O)}}class u0 extends Z0{constructor($="Server is shutting down"){super("SERVICE_UNAVAILABLE",$,503)}}class L0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class e extends Z0{constructor($="Internal server error"){super("INTERNAL_ERROR",$,500)}}var n5=F.Object({error:F.Object({code:F.String(),message:F.String(),details:F.Optional(F.Record(F.String(),F.Unknown()))})});import{Hono as i4}from"hono";var JO=a("Service"),a4=F.Object({updates:F.Record(F.String(),F.Any()),options:F.Optional(F.Object({scope:F.Optional(W0(["local","project","global"])),immediate:F.Optional(F.Boolean())}))});function o4($){return{currentModelId:$.currentModelId,permissionMode:$.permissionMode,language:$.language,codeTheme:$.codeTheme,uiTheme:$.uiTheme,autoSaveSessions:$.autoSaveSessions,notifyBuild:$.notifyBuild,notifyErrors:$.notifyErrors,notifySounds:$.notifySounds,privacyTelemetry:$.privacyTelemetry,privacyCrash:$.privacyCrash,communicationStyle:$.communicationStyle,maxConcurrentTasks:$.maxConcurrentTasks,maxQueuedTasks:$.maxQueuedTasks,maxQueuedTaskBytes:$.maxQueuedTaskBytes,maxResidentSessionRuntimes:$.maxResidentSessionRuntimes,sessionRuntimeIdleMs:$.sessionRuntimeIdleMs}}var hO=()=>{let $=new i4;return $.get("/",async(O)=>{try{let J=J0();return O.json(J?o4(J):{})}catch(J){return JO.error("[ConfigRoutes] Failed to get config:",J),O.json({})}}),$.put("/",async(O)=>{try{let J=await O.req.json(),Z=g(a4,J);if(!Z.success)throw new L("Invalid config update format");let{updates:x,options:z}=Z.data;return await w0().updateConfig(x,z),O.json({success:!0,updates:x})}catch(J){throw JO.error("[ConfigRoutes] Failed to update config:",J),J}}),$.get("/permissions",async(O)=>{try{let J=J0();return O.json(J?.permissions||{})}catch(J){return JO.error("[ConfigRoutes] Failed to get permissions:",J),O.json({})}}),$};import{Hono as n4}from"hono";import{streamSSE as t4}from"hono/streaming";function gO($){let O="";if($.id!==void 0)O+=`id: ${$.id}
2
2
  `;if($.event!==void 0)O+=`event: ${$.event}
3
3
  `;for(let J of $.data.split(/\r\n|\r|\n/))O+=`data: ${J}
4
4
  `;if($.retry!==void 0)O+=`retry: ${$.retry}