blade-code 0.10.27 → 0.10.28

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 (107) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-03633tsz.js +10 -0
  3. package/dist/{chunk-0vsaphkr.js → chunk-0pbvrw1c.js} +1 -1
  4. package/dist/{chunk-z3kc23wz.js → chunk-0pcwv1h8.js} +1 -1
  5. package/dist/{chunk-1c4j6q7j.js → chunk-0xhd2mzm.js} +2 -2
  6. package/dist/{chunk-kahzw9qn.js → chunk-1e9cpchh.js} +39 -39
  7. package/dist/chunk-1kxz32m6.js +1 -0
  8. package/dist/chunk-1sregjyz.js +1 -0
  9. package/dist/{chunk-eeg6jn2c.js → chunk-1ycv8b9t.js} +1 -1
  10. package/dist/{chunk-99h83wjf.js → chunk-287fabvz.js} +2 -2
  11. package/dist/chunk-2byq2qja.js +1 -0
  12. package/dist/{chunk-z4d3t2bb.js → chunk-2gre3vrn.js} +2 -2
  13. package/dist/{chunk-sp1j3ng5.js → chunk-2ycs4wce.js} +1 -1
  14. package/dist/chunk-3t5gqr9e.js +1 -0
  15. package/dist/{chunk-gwxwpwqk.js → chunk-4y6pjd2n.js} +1 -1
  16. package/dist/{chunk-76fnqb4r.js → chunk-5wkv5g4v.js} +1 -1
  17. package/dist/{chunk-cx5daedg.js → chunk-69r9j0ms.js} +1 -1
  18. package/dist/{chunk-czs2rxyr.js → chunk-6qdwp1t3.js} +1 -1
  19. package/dist/{chunk-bmxzx4xg.js → chunk-6vfctcqp.js} +1 -1
  20. package/dist/chunk-6znn1a5v.js +1 -0
  21. package/dist/{chunk-k6gsac91.js → chunk-70kccy7a.js} +1 -1
  22. package/dist/{chunk-jvg2vnc3.js → chunk-78bknnzt.js} +2 -2
  23. package/dist/chunk-7hjz5jjn.js +9 -0
  24. package/dist/{chunk-7v0w3625.js → chunk-8djaj8m7.js} +2 -2
  25. package/dist/chunk-8k9ark1n.js +1 -0
  26. package/dist/chunk-98rbxm1y.js +22 -0
  27. package/dist/{chunk-9reqa9g1.js → chunk-9ev9k5bd.js} +2 -2
  28. package/dist/{chunk-y0c3knp9.js → chunk-a1a4351m.js} +2 -2
  29. package/dist/{chunk-ezarz0ye.js → chunk-a1ftc84p.js} +1 -1
  30. package/dist/{chunk-erwmqhkw.js → chunk-ae7f5mh9.js} +1 -1
  31. package/dist/{chunk-a09g8k55.js → chunk-apq6qqjg.js} +2 -2
  32. package/dist/{chunk-1thq2kns.js → chunk-axcaxcgk.js} +2 -2
  33. package/dist/chunk-br9230a2.js +2 -0
  34. package/dist/chunk-cbyewxx4.js +3 -0
  35. package/dist/{chunk-hxb7wg07.js → chunk-d6a4qw1m.js} +1 -1
  36. package/dist/{chunk-e1r2zqv3.js → chunk-djzy4zgc.js} +2 -2
  37. package/dist/chunk-dny4h2gz.js +4 -0
  38. package/dist/{chunk-yh81njxg.js → chunk-dx5996qr.js} +1 -1
  39. package/dist/{chunk-y4fj9way.js → chunk-ecvk8npm.js} +1 -1
  40. package/dist/{chunk-5wemkcp3.js → chunk-gbmnbckj.js} +2 -2
  41. package/dist/{chunk-y2ra5akr.js → chunk-gpa4y0xk.js} +1 -1
  42. package/dist/chunk-hb9yjfja.js +1 -0
  43. package/dist/{chunk-17k72zar.js → chunk-hbhcj665.js} +2 -2
  44. package/dist/{chunk-18ck4nnw.js → chunk-j9djsqqy.js} +2 -2
  45. package/dist/chunk-jk66yar2.js +1 -0
  46. package/dist/chunk-jvtzyba4.js +2 -0
  47. package/dist/{chunk-j4gvwm9w.js → chunk-k3wmp1xm.js} +1 -1
  48. package/dist/chunk-k52a3bq6.js +1 -0
  49. package/dist/chunk-n1qmwjmc.js +1 -0
  50. package/dist/chunk-p2j0wcca.js +111 -0
  51. package/dist/{chunk-kvgrg5p2.js → chunk-p2yb40zk.js} +1 -1
  52. package/dist/{chunk-d893y03w.js → chunk-p4hf7agx.js} +2 -2
  53. package/dist/chunk-q4fy74fz.js +2 -0
  54. package/dist/chunk-qewf02br.js +1 -0
  55. package/dist/chunk-qsj712zc.js +1 -0
  56. package/dist/{chunk-14hspehn.js → chunk-rf3jf275.js} +3 -3
  57. package/dist/{chunk-00ta2sme.js → chunk-rqvejn8x.js} +2 -2
  58. package/dist/chunk-ry7226b5.js +6 -0
  59. package/dist/{chunk-ymgnh4an.js → chunk-sh2kjand.js} +1 -1
  60. package/dist/{chunk-1zsz19bn.js → chunk-sjbqm4be.js} +1 -1
  61. package/dist/{chunk-39yvdt2g.js → chunk-stmsk0kz.js} +2 -2
  62. package/dist/{chunk-emwawshv.js → chunk-t0n90d7w.js} +1 -1
  63. package/dist/{chunk-v1kac601.js → chunk-taj3qfn3.js} +1 -1
  64. package/dist/{chunk-q24xmkqy.js → chunk-tct2ybbh.js} +2 -2
  65. package/dist/{chunk-h79p49hc.js → chunk-tdevyej4.js} +1 -1
  66. package/dist/{chunk-z2kfx8g0.js → chunk-wn60hv0w.js} +358 -350
  67. package/dist/chunk-x1a5wv45.js +1 -0
  68. package/dist/{chunk-600hfjag.js → chunk-x3dche8v.js} +2 -2
  69. package/dist/{chunk-b9akah7k.js → chunk-xqapcfw3.js} +1 -1
  70. package/dist/{chunk-77y8cb2q.js → chunk-yv2sdpxk.js} +1 -1
  71. package/dist/chunk-z516a7nx.js +1 -0
  72. package/dist/web/assets/ChatView-BtSSERlQ.js +18 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-B8-o1K2L.js → CodeBlockHighlighter-CAuanOO0.js} +1 -1
  74. package/dist/web/assets/{FilePreview-BvUxzULZ.js → FilePreview-BKQ-EBj3.js} +1 -1
  75. package/dist/web/assets/{MarkdownRenderer-C-X3g9Ky.js → MarkdownRenderer-BdYjJ_NM.js} +3 -3
  76. package/dist/web/assets/{SettingsModal-Dhjw1__j.js → SettingsModal-CB6hM8fT.js} +1 -1
  77. package/dist/web/assets/{TaskSwitcher-BAHVGLmL.js → TaskSwitcher-sSD4B7C_.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-D3cC-lXf.js → TerminalPanel-ZnEoQU6o.js} +1 -1
  79. package/dist/web/assets/{index-D88fYWls.js → index-DtOztVFd.js} +7 -7
  80. package/dist/web/assets/session-events-C2PMff2v.js +22 -0
  81. package/dist/web/index.html +2 -2
  82. package/package.json +4 -1
  83. package/dist/chunk-1pjvzcrj.js +0 -2
  84. package/dist/chunk-2rdk9rzv.js +0 -1
  85. package/dist/chunk-4dnvydyv.js +0 -4
  86. package/dist/chunk-4qk4v6aw.js +0 -1
  87. package/dist/chunk-7kfnsts1.js +0 -1
  88. package/dist/chunk-awz9bn56.js +0 -1
  89. package/dist/chunk-cpk6vwyh.js +0 -1
  90. package/dist/chunk-dyf9jrds.js +0 -9
  91. package/dist/chunk-fgczbyhy.js +0 -1
  92. package/dist/chunk-g11e47n1.js +0 -1
  93. package/dist/chunk-hszqdsn3.js +0 -1
  94. package/dist/chunk-kbpg9amg.js +0 -100
  95. package/dist/chunk-m6crkryd.js +0 -6
  96. package/dist/chunk-pvf84eht.js +0 -1
  97. package/dist/chunk-rtct70pm.js +0 -3
  98. package/dist/chunk-rvz8yka7.js +0 -1
  99. package/dist/chunk-t3hahveb.js +0 -1
  100. package/dist/chunk-v874kevz.js +0 -22
  101. package/dist/chunk-wa33kkb2.js +0 -1
  102. package/dist/chunk-wawmjv8r.js +0 -10
  103. package/dist/chunk-wzxkfpec.js +0 -2
  104. package/dist/chunk-xg9fzft1.js +0 -1
  105. package/dist/chunk-yc8rrjsr.js +0 -1
  106. package/dist/web/assets/ChatView-B4Le8nGL.js +0 -7
  107. package/dist/web/assets/session-events-BoJrjSZ2.js +0 -22
@@ -1,2 +1,2 @@
1
- import{Kf as d,Mf as h}from"./chunk-1pjvzcrj.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
- export{q as Cc,w as Dc};
1
+ import{Rf as d,Tf as h}from"./chunk-q4fy74fz.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
+ export{q as Jc,w as Kc};
@@ -1,4 +1,4 @@
1
- import{G as P}from"./chunk-z2kfx8g0.js";import{Oa as K}from"./chunk-a09g8k55.js";import{Jb as G,Kb as N,Lb as S,Mb as O,Nb as s,jc as B}from"./chunk-kbpg9amg.js";import{oc as j}from"./chunk-600hfjag.js";import{od as q}from"./chunk-ymgnh4an.js";import{Gd as v}from"./chunk-q24xmkqy.js";import{Vf as z}from"./chunk-00ta2sme.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{G as P}from"./chunk-wn60hv0w.js";import{Oa as K}from"./chunk-apq6qqjg.js";import{Gb as G,Hb as N,Ib as S,Jb as O,Kb as s,nc as B}from"./chunk-p2j0wcca.js";import{vc as j}from"./chunk-x3dche8v.js";import{vd as q}from"./chunk-sh2kjand.js";import{Nd as v}from"./chunk-tct2ybbh.js";import{ag as z}from"./chunk-rqvejn8x.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-v1kac601.js";import{sf as s}from"./chunk-sp1j3ng5.js";import"./chunk-00ta2sme.js";import"./chunk-z3kc23wz.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-taj3qfn3.js";import{zf as s}from"./chunk-2ycs4wce.js";import"./chunk-rqvejn8x.js";import"./chunk-0pcwv1h8.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1,4 +1,4 @@
1
- import{xb as lJ}from"./chunk-4dnvydyv.js";import{Fb as XJ,Gb as zJ,Hb as l1,Ib as r1,Pb as n2,Rb as T$,_b as F0,ac as z2,bc as t$,cc as Q2,jc as A$,yb as u0}from"./chunk-kbpg9amg.js";import{kc as w0,nc as JJ,oc as G0}from"./chunk-600hfjag.js";import{od as dJ}from"./chunk-ymgnh4an.js";import{pd as uJ,qd as x0,rd as vJ,sd as cJ,td as X2,vd as r2}from"./chunk-17k72zar.js";import{$d as h0,ae as A0,de as iJ}from"./chunk-0vsaphkr.js";import{me as e0}from"./chunk-14hspehn.js";import{sf as o}from"./chunk-sp1j3ng5.js";import{wf as O0}from"./chunk-d893y03w.js";import{Kf as HJ}from"./chunk-1pjvzcrj.js";import{Sf as Z$,Uf as p2,Vf as X0,Wf as s$,Yf as YJ,_f as KJ}from"./chunk-00ta2sme.js";import{$f as V8}from"./chunk-z3kc23wz.js";function s0($){return $.role==="system"&&Array.isArray($.content)}function a0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class m${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(s0);if(this._contextualSystemMessages=$.messages.filter(a0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!s0(W)&&!a0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!a0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(s0);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!s0(J)&&!a0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(a0),this._history=$.filter((J)=>!s0(J)&&!a0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function P2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function _2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function f2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import d0 from"node:path";var Z6=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),W6=/^(LD_.+|DYLD_.+|PATH)$/,A2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function P$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(A2);if(!K)break;let H=K[1];if(!Z6.has(H))break;J=Y}return J}function b5($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(A2);if(!K)break;let H=K[1];if(W6.test(H))break;J=Y}return J}var Y6=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function k1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y6){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function d$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function N2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function _$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let z=$[H+1];if(z&&'$`"\\'.includes(z))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K6=new Set(["npm","pnpm","yarn","bun"]),b2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H6=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function X6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Q6($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=_$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=d0.isAbsolute(K)?d0.resolve(K):d0.resolve(Z,K);if(!u0.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function t0($,J){let Z=P$(z6($)),W=d$(Z);if(!W||N2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:Q6(Z,W,J);if(!Y)return!1;let K=_$(Y);if(K.length===0||K.some((Q)=>[...H6].some((V)=>Q===V||Q.startsWith(`${V}=`))))return!1;let[H,X,z]=K;if(K6.has(H??""))return X6(X==="run"?z:X)||X==="--test";if((H==="npx"||H==="bunx")&&b2.has(X??""))return!0;if(b2.has(H??""))return!0;if(H==="node"&&X==="--test")return!0;if(H==="go"&&["build","test","vet"].includes(X??""))return!0;return H==="cargo"&&["build","check","clippy","test"].includes(X??"")}function x5($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!d0.isAbsolute($);let Z=d0.isAbsolute($)?d0.resolve($):d0.resolve(J,$);return u0.isWithinWorkspace(Z,J)}var x1=O0("Agent"),B6=3;function M1($,J,Z){if($!=="length")return{action:"none"};if(J>=B6)return{action:"truncated"};if(P2(Z)==="stop")return x1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var V6=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],D6=/```[\s\S]{50,}```/,S2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",j6=2;function h1($,J,Z=!0){if(!$||J>=j6)return{action:"none"};if(!Z&&D6.test($))return{action:"retry",prompt:S2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(V6.some((H)=>H.test(W)))return{action:"retry",prompt:S2};return{action:"none"}}var w6=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],E2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},L6={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},q6="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",O6="Required verification did not run successfully before the retry limit.",G6=3;function k2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&t0(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&t0(K,W))$.add(K)}function R1($,J,Z){if(!$||!w6.some((z)=>z.test($)))return{action:"none"};let W=Object.keys(E2).filter((z)=>E2[z].test($)),Y=[...J],K=W.filter((z)=>!Y.some((Q)=>L6[z].test(Q)));if(W.length>0?K.length===0:Y.some((z)=>t0(z)))return{action:"none"};if(Z>=G6)return{action:"fail",message:O6};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${q6}${X}`}}var y6=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],x2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function M2($){return typeof $==="string"&&x2.some((J)=>J.test($))}var F6=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],U6=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function P6($){if(typeof $!=="string")return;if(U6.some((J)=>J.test($)))return"multiple-allowed";return F6.some((J)=>J.test($))?"required":void 0}function c$($){for(let J of $){let Z=P6(J);if(Z!==void 0)return Z==="required"}return!1}var _6="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",f6="Required delegation did not complete before the retry limit.",A6=3;function h2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=c$(W),K=!1;if(!Y)for(let H of W){if(x2.some((X)=>X.test(H)))break;if(y6.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=A6)return{action:"fail",message:f6};return{action:"retry",prompt:_6}}var N6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],b6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],S6=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function R2($){return S6.reduce((J,Z)=>J.replace(Z," "),$)}function i$($){if(typeof $!=="string")return!1;let J=R2($);return N6.some((Z)=>Z.test(J))}var E6="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",T6="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",k6="Required worktree lifecycle did not complete before the retry limit.",x6=3;function v2($,J,Z){if(!$)return{action:"none"};let W=R2($);if(!i$(W))return{action:"none"};let Y=b6.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=x6)return{action:"fail",message:k6};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?E6:T6}}var T2=30000;async function v1($){try{let Z=e0.getInstance().executeStopHooks({projectDir:$.workspaceRoot??o(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),T2)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return x1.warn(`[Loop] Stop hook 超时 (${T2}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M6($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var h6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function R6($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function v6($){let J=$;for(let z of h6)J=J.replace(z," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function C2($){return v6(R6($))}import{EventEmitter as C6}from"events";import I2 from"node:path";function C1($){if(p2($.sessionId),!I2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:I2.resolve($.projectPath)}}function c5($){let J=C1($);return JSON.stringify([J.projectPath,J.sessionId])}class $$ extends C6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!$$.instance)$$.instance=new $$;return $$.instance}publish($,J,Z,W){let Y=C1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var f$=$$.getInstance();var E0=O0("Agent"),l$=new Set;async function I6($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(l$.has(Z))return;if(l$.size>=5000)l$.clear();l$.add(Z);try{let W=$.workspaceRoot,Y=await A$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=C2(J);if(!K)return;await A$.updateSessionMetadata(Z,Y.projectPath,{title:K}),f$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){E0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var I1=`<turn_aborted>
1
+ import{ub as lJ}from"./chunk-dny4h2gz.js";import{Cb as XJ,Db as zJ,Eb as l1,Fb as r1,Mb as n2,Ub as T$,cc as F0,ec as z2,fc as t$,gc as Q2,nc as A$,vb as u0}from"./chunk-p2j0wcca.js";import{rc as w0,uc as JJ,vc as G0}from"./chunk-x3dche8v.js";import{vd as dJ}from"./chunk-sh2kjand.js";import{Ad as X2,Cd as r2,wd as uJ,xd as x0,yd as vJ,zd as cJ}from"./chunk-hbhcj665.js";import{ge as h0,he as A0,ke as iJ}from"./chunk-0pbvrw1c.js";import{te as e0}from"./chunk-rf3jf275.js";import{zf as o}from"./chunk-2ycs4wce.js";import{Df as O0}from"./chunk-p4hf7agx.js";import{Rf as HJ}from"./chunk-q4fy74fz.js";import{$f as p2,Zf as Z$,ag as X0,bg as s$,dg as YJ,fg as KJ}from"./chunk-rqvejn8x.js";import{gg as V8}from"./chunk-0pcwv1h8.js";function s0($){return $.role==="system"&&Array.isArray($.content)}function a0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class m${systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,J){this.context=$;let Z=$.messages.find(s0);if(this._contextualSystemMessages=$.messages.filter(a0),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!s0(W)&&!a0(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!a0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(s0);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!s0(J)&&!a0(J))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(a0),this._history=$.filter((J)=>!s0(J)&&!a0(J)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function P2($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function _2($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function f2($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import d0 from"node:path";var Z6=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),W6=/^(LD_.+|DYLD_.+|PATH)$/,A2=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function P$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(A2);if(!K)break;let H=K[1];if(!Z6.has(H))break;J=Y}return J}function b5($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],K=W.match(A2);if(!K)break;let H=K[1];if(W6.test(H))break;J=Y}return J}var Y6=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function k1($){let J=$,Z=!0;while(Z){Z=!1;for(let W of Y6){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function d$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){Z+=X,K=!0;continue}if(X==="'"&&!Y){W=!W,Z+=X;continue}if(X==='"'&&!W){Y=!Y,Z+=X;continue}if(W||Y){Z+=X;continue}if(X==="|"){if(H+1<$.length&&$[H+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}return null}if(X===">"||X==="<")return null;if(X==="&"&&H+1<$.length&&$[H+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",H++;continue}if(X==="&")return null;if(X===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=X}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function N2($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!J){W=!0;continue}if(K==="'"&&!Z){J=!J;continue}if(K==='"'&&!J){Z=!Z;continue}if(J)continue;if(K==="$"){let H=$[Y+1];if(H&&/[A-Za-z_@*#?!$0-9({]/.test(H))return!0}if(K==="`")return!0;if(Z)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let H=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(H)||/^\{[^}]*\.\.[^}]*\}/.test(H))return!0}}return!1}function _$($){let J=[],Z="",W=!1,Y=!1,K=!1;for(let H=0;H<$.length;H++){let X=$[H];if(K){Z+=X,K=!1;continue}if(X==="\\"&&!W){if(K=!0,Y){let z=$[H+1];if(z&&'$`"\\'.includes(z))continue;Z+=X,K=!1}continue}if(X==="'"&&!Y){W=!W;continue}if(X==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(X)){if(Z)J.push(Z),Z="";continue}Z+=X}if(Z)J.push(Z);return J}var K6=new Set(["npm","pnpm","yarn","bun"]),b2=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),H6=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function X6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function Q6($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=_$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let H=d0.isAbsolute(K)?d0.resolve(K):d0.resolve(Z,K);if(!u0.isWithinWorkspace(H,Z))return;return W[2]?.trim()||void 0}function t0($,J){let Z=P$(z6($)),W=d$(Z);if(!W||N2(Z)||/[\r\n]/.test(Z))return!1;let Y=W.length===1?W[0]:Q6(Z,W,J);if(!Y)return!1;let K=_$(Y);if(K.length===0||K.some((Q)=>[...H6].some((V)=>Q===V||Q.startsWith(`${V}=`))))return!1;let[H,X,z]=K;if(K6.has(H??""))return X6(X==="run"?z:X)||X==="--test";if((H==="npx"||H==="bunx")&&b2.has(X??""))return!0;if(b2.has(H??""))return!0;if(H==="node"&&X==="--test")return!0;if(H==="go"&&["build","test","vet"].includes(X??""))return!0;return H==="cargo"&&["build","check","clippy","test"].includes(X??"")}function x5($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!d0.isAbsolute($);let Z=d0.isAbsolute($)?d0.resolve($):d0.resolve(J,$);return u0.isWithinWorkspace(Z,J)}var x1=O0("Agent"),B6=3;function M1($,J,Z){if($!=="length")return{action:"none"};if(J>=B6)return{action:"truncated"};if(P2(Z)==="stop")return x1.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var V6=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],D6=/```[\s\S]{50,}```/,S2="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",j6=2;function h1($,J,Z=!0){if(!$||J>=j6)return{action:"none"};if(!Z&&D6.test($))return{action:"retry",prompt:S2};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(V6.some((H)=>H.test(W)))return{action:"retry",prompt:S2};return{action:"none"}}var w6=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],E2={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},L6={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},q6="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",O6="Required verification did not run successfully before the retry limit.",G6=3;function k2($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&t0(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&t0(K,W))$.add(K)}function R1($,J,Z){if(!$||!w6.some((z)=>z.test($)))return{action:"none"};let W=Object.keys(E2).filter((z)=>E2[z].test($)),Y=[...J],K=W.filter((z)=>!Y.some((Q)=>L6[z].test(Q)));if(W.length>0?K.length===0:Y.some((z)=>t0(z)))return{action:"none"};if(Z>=G6)return{action:"fail",message:O6};let X=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${q6}${X}`}}var y6=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],x2=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function M2($){return typeof $==="string"&&x2.some((J)=>J.test($))}var F6=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],U6=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function P6($){if(typeof $!=="string")return;if(U6.some((J)=>J.test($)))return"multiple-allowed";return F6.some((J)=>J.test($))?"required":void 0}function c$($){for(let J of $){let Z=P6(J);if(Z!==void 0)return Z==="required"}return!1}var _6="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",f6="Required delegation did not complete before the retry limit.",A6=3;function h2($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((H)=>H.trim()).filter(Boolean),Y=c$(W),K=!1;if(!Y)for(let H of W){if(x2.some((X)=>X.test(H)))break;if(y6.some((X)=>X.test(H))){K=!0;break}}if(W.length===0||!Y&&!K||J.has("Task"))return{action:"none"};if(Z>=A6)return{action:"fail",message:f6};return{action:"retry",prompt:_6}}var N6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],b6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],S6=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function R2($){return S6.reduce((J,Z)=>J.replace(Z," "),$)}function i$($){if(typeof $!=="string")return!1;let J=R2($);return N6.some((Z)=>Z.test(J))}var E6="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",T6="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",k6="Required worktree lifecycle did not complete before the retry limit.",x6=3;function v2($,J,Z){if(!$)return{action:"none"};let W=R2($);if(!i$(W))return{action:"none"};let Y=b6.some((H)=>H.test(W));if(J.has("TaskWorktree"))return{action:"none"};let K=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(Z>=x6)return{action:"fail",message:k6};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?E6:T6}}var T2=30000;async function v1($){try{let Z=e0.getInstance().executeStopHooks({projectDir:$.workspaceRoot??o(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),T2)});try{let K=await Promise.race([Z,Y]);if(K==="timeout")return x1.warn(`[Loop] Stop hook 超时 (${T2}ms),按 shouldStop: true 处理`),{action:"stop"};let H=K;if(!H.shouldStop)return{action:"continue",reason:H.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return x1.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function M6($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var h6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function R6($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function v6($){let J=$;for(let z of h6)J=J.replace(z," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),H=K.lastIndexOf(" ");return`${(H>36?K.slice(0,H):K).trimEnd()}…`}function C2($){return v6(R6($))}import{EventEmitter as C6}from"events";import I2 from"node:path";function C1($){if(p2($.sessionId),!I2.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:I2.resolve($.projectPath)}}function c5($){let J=C1($);return JSON.stringify([J.projectPath,J.sessionId])}class $$ extends C6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!$$.instance)$$.instance=new $$;return $$.instance}publish($,J,Z,W){let Y=C1($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var f$=$$.getInstance();var E0=O0("Agent"),l$=new Set;async function I6($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(l$.has(Z))return;if(l$.size>=5000)l$.clear();l$.add(Z);try{let W=$.workspaceRoot,Y=await A$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=C2(J);if(!K)return;await A$.updateSessionMetadata(Z,Y.projectPath,{title:K}),f$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){E0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var I1=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,c0="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",g2="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class J$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function i0($){return $.executionEngine?.getContextManager()}async function J0($,J,Z,W=null,Y,K={}){let H=K.required??$.executionEngine!==void 0;try{let X=i0($),z=typeof Z==="string"?Z.trim()!=="":Z.some((Q)=>Q.type==="text"?Q.text.trim()!=="":!0);if(X&&J.sessionId&&z){let Q=await X.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(H&&!Q)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)I6(J,Z);return Q}if(H&&J.sessionId&&z)throw Error("Durable user-message storage is unavailable")}catch(X){if(E0.warn("[Loop] 保存用户消息失败:",X),H)throw new J$("user_message",{cause:X})}return null}async function I($,J,Z,W,Y,K,H={}){let X=H.required??$.executionEngine!==void 0;try{let z=i0($),Q=Boolean(Z.trim()||Y?.trim());if(z&&J.sessionId&&Q){let V=await z.saveMessage(J.sessionId,"assistant",Z,W,K,J.subagentInfo,Y);if(X&&!V)throw Error("Durable assistant-message commit returned no identity");return V}if(X&&J.sessionId&&Q)throw Error("Durable assistant-message storage is unavailable")}catch(z){if(E0.warn("[Loop] 保存助手消息失败:",z),X)throw new J$("assistant_message",{cause:z})}return null}async function m2($,J,Z){try{let W=i0($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",I1,Z,void 0,J.subagentInfo)}catch(W){E0.warn("[Loop] 保存中断边界失败:",W)}return null}async function d2($,J,Z,W,Y){try{let K=i0($);if(!K||!J.sessionId||Z.length===0)return null;return await K.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((H)=>({...H})))),triggerPaths:[...W]},J.subagentInfo)}catch(K){E0.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function p1($,J,Z,W,Y,K={}){try{let H=i0($);if(H&&J.sessionId){let X=await H.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo);if(K.required&&!X)throw Error("Durable tool-use commit returned no identity");return X}if(K.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(H){if(E0.warn("[Loop] 保存工具调用失败:",H),K.required)throw H}return null}async function r$($,J,Z,W,Y,K,H,X,z,Q={}){try{let V=i0($);if(V&&J.sessionId){let w=await V.saveToolResult(J.sessionId,Z,W,Y,K,H,J.subagentInfo,X,z);if(Q.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(Q.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(V){if(E0.warn("[Loop] 保存工具结果失败:",V),Q.required)throw V}return null}async function N$($,J,Z,W,Y={}){try{let K=i0($);if(K&&J.sessionId){let H=await K.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!H)throw Error("Compaction checkpoint commit returned no identity");return H||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if(E0.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}import{createHash as H5}from"node:crypto";import{promises as n6}from"node:fs";import o6 from"node:path";import{nanoid as k0}from"nanoid";import*as d from"node:fs/promises";import*as l0 from"node:path";var u2={enabled:!0,maxIndexLines:200};var p6="memory",c2="MEMORY.md";class g1{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=Z$($);this.memoryDir=l0.join(W,p6)}this.config={...u2,...J}}async initialize(){if(this.initialized)return;await d.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=l0.join(this.memoryDir,c2);try{let J=await d.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -118,7 +118,7 @@ Full output saved to: ${X}`}catch{return`${J}
118
118
 
119
119
  ${Y}`}}import{Mutex as y8}from"async-mutex";import{nanoid as F8}from"nanoid";import*as j0 from"node:fs/promises";import*as ZJ from"node:path";import{Mutex as H8}from"async-mutex";import X8 from"write-file-atomic";var a$=1,$J=8388608;function c1($,J){return $ instanceof Error&&"code"in $&&$.code===J}function z8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function Q8($,J,Z){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==a$||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!z8(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let H="outputSchema"in K&&K.outputSchema!==void 0?t$(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},...H?{outputSchema:H}:{}}});return{version:a$,sessionId:Z,messages:Y}}function B8($){return new Set($.flatMap((J)=>J.type==="inbox_acknowledged"?J.data.messageIds:[]))}class e${workspaceRoot;sessionId;filePath;mutex=new H8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new e$($,J,s$($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}];return await this.persist(Z),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:a$,sessionId:this.sessionId,messages:[]};try{if((await j0.stat(this.filePath)).size>$J)throw Error(`Steering inbox exceeds ${$J} bytes: ${this.filePath}`);await j0.chmod(this.filePath,384),$=Q8(await j0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!c1(Y,"ENOENT"))throw Y}let J=X0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=B8(JJ(await j0.readFile(J,"utf8"),J))}catch(Y){if(!c1(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($){if(await j0.mkdir(ZJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await j0.unlink(this.filePath).catch((Z)=>{if(!c1(Z,"ENOENT"))throw Z});return}let J={version:a$,sessionId:this.sessionId,messages:$.map(({recovered:Z,...W})=>W)};await X8(this.filePath,`${JSON.stringify(J)}
120
120
  `,{encoding:"utf8",mode:384,fsync:!0})}}import*as y0 from"node:fs/promises";import*as QJ from"node:path";import{nanoid as z0}from"nanoid";class r0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new G0(X0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=r0.instances.get(Z);if(!W)W=new r0($,J),r0.instances.set(Z,W);return W}static release($,J){r0.instances.delete(`${J}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);f$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z)$.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let J of this.subscribers)J.onCommitted($);f$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function E$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class f0 extends Error{}var D8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",j8=20,w8=1e4,L8=1e5,q8=2592000000;function O8($,J){let Z=w0($),W=Z.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(W<0)return;for(let Y=Z.length-1;Y>W;Y--){let K=Z[Y];if(K?.type!=="message_created")continue;let H=K.data.metadata;if(!H||typeof H!=="object"||Array.isArray(H))continue;let X=H.turnFinalization;if(!X||typeof X!=="object"||Array.isArray(X))continue;let{inputMessageIds:z,turnsCount:Q,toolCallsCount:V,durationMs:w}=X,q=Array.isArray(z)?z.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=128):[];if(X.turnId!==J||J.length===0||J.length>128||!Array.isArray(z)||z.length>j8||q.length!==z.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>w8||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>L8||typeof w!=="number"||!Number.isSafeInteger(w)||w<0||w>q8)continue;return{turnId:J,inputMessageIds:[...new Set(q)],turnsCount:Q,toolCallsCount:V,durationMs:w}}return}function WJ($,J){let Z=w0($),W=J?Z.findLastIndex((z)=>z.type==="turn_started"&&z.data.turnId===J):-1;if(J&&W<0)return{all:[],orphaned:[]};let Y=new Map,K=new Set,H=new Set;for(let z of Z.slice(W+1)){if(z.type==="interaction_requested"){H.add(z.data.toolCallId);continue}if(z.type!=="part_created")continue;let Q=z.data.payload&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)?z.data.payload:{},V=typeof Q.toolCallId==="string"?Q.toolCallId:z.data.partId;if(z.data.partType==="tool_call")Y.set(V,{toolCallId:V,toolName:typeof Q.toolName==="string"?Q.toolName:"unknown"});else if(z.data.partType==="tool_result")K.add(V),K.add(z.data.partId),K.add(z.data.messageId)}let X=[...Y.values()];return{all:X,orphaned:X.filter((z)=>!K.has(z.toolCallId)&&!H.has(z.toolCallId))}}class M0{projectPath;maxSessions;version;constructor($=o(),J=100,Z=HJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:z0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:YJ(this.projectPath),version:this.version,data:Z}}log($){return r0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=X0(this.projectPath,$);if((await new G0(Z).readAll()).length>0)return;let K=new Date().toISOString(),H={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:K,updatedAt:K},X=this.createEvent("session_created",$,H);await this.log($).commit(X)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=XJ;return J}async initialize(){try{let $=Z$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,K,H){try{await this.ensureSessionCreated($,K);let X=new Date().toISOString(),z=z0(),Q={messageId:z,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:X,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},V=this.createEvent("message_created",$,Q),w=J==="assistant"&&H?.trim()?[this.createEvent("part_created",$,{partId:z0(),messageId:z,partType:"reasoning",payload:{text:H},createdAt:X})]:[],q=typeof Z==="string"?[this.createEvent("part_created",$,{partId:z0(),messageId:z,partType:"text",payload:{text:Z},createdAt:X})]:Z.map((j)=>this.createEvent("part_created",$,{partId:z0(),messageId:z,partType:j.type==="text"?"text":"image",payload:j.type==="text"?{text:j.text}:{mimeType:G8(j.image_url.url)??"image/png",dataUrl:j.image_url.url},createdAt:X}));return await this.log($).commitBatch([V,...w,...q]),z}catch(X){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,X),X}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=w0(Z);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===J.turnId))throw new f0;let Y=E$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof f0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=w0(W),K=new Set(Y.flatMap((Q)=>Q.type==="inbox_acknowledged"?Q.data.messageIds:[])),H=[...new Set(Z)].filter((Q)=>!K.has(Q)),X=Y.findLast((Q)=>(Q.type==="turn_completed"||Q.type==="turn_aborted")&&Q.data.turnId===J.turnId);if(X){if(X.type==="turn_aborted"||H.length===0)throw new f0;return[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]}let z=E$(Y).active;if(!z||z.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...H.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:H,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof f0))throw W}}async saveTurnAbort($,J){await this.saveTurnTerminal($,"turn_aborted",J)}async recoverInterruptedTurn($){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((Z)=>{let W=w0(Z),Y=E$(W).active,K=WJ(W);if(!Y&&K.orphaned.length===0)throw new f0;let H=Y?O8(W,Y.turnId):void 0;if(Y&&H&&K.orphaned.length===0){J={turnId:Y.turnId,outcome:"completed"};let w=new Set(W.flatMap((k)=>k.type==="inbox_acknowledged"?k.data.messageIds:[])),q=H.inputMessageIds.filter((k)=>!w.has(k)),j=new Date().toISOString();return[...q.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:q,acknowledgedAt:j})]:[],this.createEvent("turn_completed",$,{turnId:Y.turnId,completedAt:j,turnsCount:H.turnsCount,toolCallsCount:H.toolCallsCount,durationMs:H.durationMs})]}J=Y?{turnId:Y.turnId,outcome:"aborted"}:void 0;let X=Y?WJ(W,Y.turnId).all.length:0,z=new Date().toISOString(),Q=Y?Date.parse(Y.startedAt):Number.NaN,V=K.orphaned.map((w)=>this.createEvent("part_created",$,{partId:w.toolCallId,messageId:w.toolCallId,partType:"tool_result",payload:{toolCallId:w.toolCallId,toolName:w.toolName,output:null,error:D8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:z}));return Y?[...V,this.createEvent("turn_aborted",$,{turnId:Y.turnId,cause:"process_restart",abortedAt:z,turnsCount:0,toolCallsCount:X,durationMs:Number.isFinite(Q)?Math.max(0,Date.now()-Q):0})]:V})}catch(Z){if(!(Z instanceof f0))throw Z}return J}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_requested"&&K.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="interaction_responded"&&K.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_started"&&!Z.some((H)=>H.type==="review_completed"&&H.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((K)=>K.type==="review_started"&&K.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y){try{await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),H=W??z0(),X=[];if(!W){let V={messageId:H,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,V))}let z=z0(),Q={partId:z,messageId:H,partType:"tool_call",payload:{toolCallId:z,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,Q)),J==="Task"&&Z&&typeof Z==="object"){let V=Z,w=typeof V.subagent_session_id==="string"?V.subagent_session_id:void 0,q=typeof V.subagent_type==="string"?V.subagent_type:void 0;if(w&&q){let j={partId:z0(),messageId:H,partType:"subtask_ref",payload:{childSessionId:w,agentType:q,status:"running",summary:typeof V.description==="string"?V.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,j))}}return await this.log($).commitBatch(X),z}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,K,H,X,z){try{await this.ensureSessionCreated($,H);let Q=new Date().toISOString(),V=Y??z0(),w=[];if(!Y){let j={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:Q};w.push(this.createEvent("message_created",$,j))}let q={partId:J,messageId:V,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:K??null,...z===void 0?{}:{metadata:z}},createdAt:Q};if(w.push(this.createEvent("part_created",$,q)),X){let j=X.subagentStatus==="running"?null:Q,k={partId:z0(),messageId:V,partType:"subtask_ref",payload:{childSessionId:X.subagentSessionId,agentType:X.subagentType,description:X.subagentDescription??"",status:X.subagentStatus,summary:X.subagentSummary??"",resumedFrom:X.subagentResumedFrom??null,rootAgentId:X.subagentRootId??X.subagentSessionId,resumeDepth:X.subagentResumeDepth??0,verificationVerdict:X.verificationVerdict??null,startedAt:Q,finishedAt:j},createdAt:Q};w.push(this.createEvent("part_created",$,k))}return await this.log($).commitBatch(w),J}catch(Q){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,Q),Q}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=z0(),H={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},X=this.buildCompactionMetadata(Z),z={partId:z0(),messageId:K,partType:"summary",payload:{text:J,metadata:X,...Z.replacementMessages?{replacementMessages:zJ(Z.replacementMessages)}:{}},createdAt:Y},Q=[this.createEvent("message_created",$,H),this.createEvent("part_created",$,z)];return await this.log($).commitBatch(Q),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=X0(this.projectPath,$),W=await new G0(J).readAll();return W.length>0?w0(W):null}catch{return null}}async loadSession($){try{let J=X0(this.projectPath,$),Z=new G0(J),W=w0(await Z.readAll());if(W.length===0)return null;let Y=W.find((K)=>K.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=X0(this.projectPath,$),Z=new G0(J),W=w0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let z of W){if(z.type==="message_created")Y.set(z.data.messageId,{id:z.data.messageId,role:z.data.role,content:"",timestamp:new Date(z.timestamp).getTime()});if(z.type==="part_created"&&z.data.partType==="text"){let Q=Y.get(z.data.messageId);if(Q){let V=z.data.payload;Q.content=V.text??""}}if(z.type==="part_created"&&z.data.partType==="image"){let Q=Y.get(z.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
121
- [Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=Z$(this.projectPath);return(await y0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=X0(this.projectPath,$),Z=new G0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=w0(Y),H=Y[Y.length-1],X=K.filter((z)=>z.type==="message_created"&&["user","assistant"].includes(z.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=X0(this.projectPath,$);await new G0(J).delete(),await y0.unlink(s$(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-xg9fzft1.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=w0(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new f0;let H=E$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof f0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=X0(this.projectPath,Z),K=await new G0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=Z$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493});let J=QJ.join($,".health-check");return await y0.writeFile(J,"test","utf-8"),await y0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return KJ()}}function G8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var BJ=131072,VJ=new Map;function i1($,J){let Z=`${$}\x00${J}`,W=VJ.get(Z);if(!W)W=new y8,VJ.set(Z,W);return W}function n1($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>BJ)throw Error(`${J} exceeds ${BJ} bytes`);return JSON.parse(Z)}function DJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function U8($,J){return JSON.stringify($)===JSON.stringify(J)}function P8($,J){if($.request.interactionType!=="elicitation")return n1(J,"Interaction response");return n1({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function jJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function _8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function f8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
121
+ [Image]`:"[Image]"}}let K=Array.from(Y.values()),H=W[W.length-1],X=new Date(H.timestamp).getTime();return{messages:K,topics:[],lastActivity:X}}catch{return null}}async listSessions(){try{let $=Z$(this.projectPath);return(await y0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=X0(this.projectPath,$),Z=new G0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let K=w0(Y),H=Y[Y.length-1],X=K.filter((z)=>z.type==="message_created"&&["user","assistant"].includes(z.data.role)).length;return{sessionId:$,lastActivity:new Date(H.timestamp).getTime(),messageCount:X,topics:[]}}catch{return null}}async deleteSession($){try{let J=X0(this.projectPath,$);await new G0(J).delete(),await y0.unlink(s$(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-x1a5wv45.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,K)=>K.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,J,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let Y=w0(W);if(Y.some((X)=>(X.type==="turn_completed"||X.type==="turn_aborted")&&X.data.turnId===Z.turnId))throw new f0;let H=E$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return J==="turn_completed"?this.createEvent("turn_completed",$,Z):this.createEvent("turn_aborted",$,Z)})}catch(W){if(!(W instanceof f0))throw W}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=X0(this.projectPath,Z),K=await new G0(W).getStats();J+=K.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=Z$(this.projectPath);await y0.mkdir($,{recursive:!0,mode:493});let J=QJ.join($,".health-check");return await y0.writeFile(J,"test","utf-8"),await y0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return KJ()}}function G8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var BJ=131072,VJ=new Map;function i1($,J){let Z=`${$}\x00${J}`,W=VJ.get(Z);if(!W)W=new y8,VJ.set(Z,W);return W}function n1($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>BJ)throw Error(`${J} exceeds ${BJ} bytes`);return JSON.parse(Z)}function DJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function U8($,J){return JSON.stringify($)===JSON.stringify(J)}function P8($,J){if($.request.interactionType!=="elicitation")return n1(J,"Interaction response");return n1({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function jJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function _8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function f8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
122
122
  `)}function A8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let H=f8(J);return{toolOutput:`User answers:
123
123
  ${H}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
124
124
  ${H}
@@ -1,6 +1,6 @@
1
- import{Hc as I}from"./chunk-99h83wjf.js";import{_c as E}from"./chunk-7v0w3625.js";import{$e as w,Ue as f,Ze as y,_e as T,af as M,df as k,ef as N}from"./chunk-z4d3t2bb.js";import{ff as c}from"./chunk-b9akah7k.js";import{gf as S,if as n,lf as m}from"./chunk-j4gvwm9w.js";import{qf as O}from"./chunk-sp1j3ng5.js";import{wf as h}from"./chunk-d893y03w.js";import{promises as R}from"node:fs";import A from"node:path";var C=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],U=new Set([...Object.keys(f),...C]),p=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:m(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(p),timeout:n.Optional(p),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(p),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(p),codeTheme:n.Optional(n.String()),uiTheme:n.Optional(m(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(p),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1})),maxConcurrentTasks:n.Optional(n.Integer({minimum:y,maximum:T})),maxQueuedTasks:n.Optional(n.Integer({minimum:w,maximum:M})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(m(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(m(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),x=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!U.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function P(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=A.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of x){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),V=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},Y=async(o)=>{let i=await P(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=N(l,o);if(E().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
1
+ import{Oc as I}from"./chunk-287fabvz.js";import{fd as E}from"./chunk-8djaj8m7.js";import{$e as f,ef as y,ff as T,gf as w,hf as M,kf as k,lf as N}from"./chunk-2gre3vrn.js";import{mf as c}from"./chunk-xqapcfw3.js";import{nf as S,pf as n,sf as m}from"./chunk-k3wmp1xm.js";import{xf as O}from"./chunk-2ycs4wce.js";import{Df as h}from"./chunk-p4hf7agx.js";import{promises as R}from"node:fs";import A from"node:path";var C=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],U=new Set([...Object.keys(f),...C]),p=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:m(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(p),timeout:n.Optional(p),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(p),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(p),codeTheme:n.Optional(n.String()),uiTheme:n.Optional(m(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(p),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1})),maxConcurrentTasks:n.Optional(n.Integer({minimum:y,maximum:T})),maxQueuedTasks:n.Optional(n.Integer({minimum:w,maximum:M})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(m(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(m(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),x=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!U.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function P(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=A.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of x){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),V=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},Y=async(o)=>{let i=await P(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=N(l,o);if(E().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
5
  `),process.exit(1)}};function F(o){if(o.continue&&o.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(o.forkSession&&!o.continue&&!o.resume)throw Error("--fork-session requires --resume or --continue");if(o.sessionId&&(o.continue||o.resume)&&!o.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Z=(o)=>{if(o.jsonSchema&&o.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((o.jsonSchema||o.outputSchema)&&!o.print&&!o.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(o.outputFormat&&o.outputFormat!=="text"&&!o.print&&!o.headless)throw Error("--output-format can only be used with --print or --headless");if(o.headless&&o.outputFormat&&!["text","jsonl"].includes(o.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${o.outputFormat}". Use --print for json|stream-json support.`);if(o.print&&o.outputFormat&&!["text","json","stream-json"].includes(o.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${o.outputFormat}". Use --headless for jsonl support.`);if(o.inputFormat==="stream-json"&&o.print)u.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{V as Ec,Y as Fc,Z as Gc};
6
+ export{V as Lc,Y as Mc,Z as Nc};
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as tf,T as uf,A as vf};