blade-code 0.7.2 → 0.7.3

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 (63) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-k18bq4mn.js → chunk-06awrjgg.js} +2 -2
  3. package/dist/chunk-1vngdr7p.js +1 -0
  4. package/dist/{chunk-8xdqtspw.js → chunk-29pqj0tb.js} +1 -1
  5. package/dist/{chunk-275gt6q1.js → chunk-373pmz70.js} +1 -1
  6. package/dist/{chunk-1w719wd9.js → chunk-38h3yh6z.js} +1 -1
  7. package/dist/{chunk-rmtcqc8q.js → chunk-5n7h04jg.js} +1 -1
  8. package/dist/{chunk-wc2xb6ge.js → chunk-5smacbk0.js} +2 -2
  9. package/dist/{chunk-cadngkwr.js → chunk-63dzf6hr.js} +1 -1
  10. package/dist/{chunk-67zx7ymj.js → chunk-87gff8b7.js} +1 -1
  11. package/dist/{chunk-g0h3rans.js → chunk-98fvxsvc.js} +1 -1
  12. package/dist/{chunk-m4a480k7.js → chunk-98jpdmgc.js} +2 -2
  13. package/dist/chunk-aevyre2t.js +1 -0
  14. package/dist/chunk-avebc3bj.js +2 -0
  15. package/dist/chunk-b4hmtjec.js +1 -0
  16. package/dist/{chunk-xa8szzc6.js → chunk-bmcc85nj.js} +1 -1
  17. package/dist/chunk-cqrg2pp7.js +1 -0
  18. package/dist/{chunk-m2k4h3bs.js → chunk-cw125vv3.js} +1 -1
  19. package/dist/{chunk-wcm0nc84.js → chunk-cyxb6fxe.js} +1 -1
  20. package/dist/{chunk-1mge0pzv.js → chunk-d0fata6n.js} +1 -1
  21. package/dist/{chunk-z0qxaky4.js → chunk-e21htmg4.js} +1 -1
  22. package/dist/{chunk-ztpseq3n.js → chunk-e9kfbbpm.js} +1 -1
  23. package/dist/{chunk-z72cp8f5.js → chunk-eady1q1w.js} +43 -43
  24. package/dist/{chunk-zcreym5g.js → chunk-gb0x14v5.js} +21 -21
  25. package/dist/{chunk-9zwf87ne.js → chunk-gjf2d2yg.js} +1 -1
  26. package/dist/{chunk-p9pthxkm.js → chunk-hs4j2fcr.js} +1 -1
  27. package/dist/{chunk-p6d7k1x6.js → chunk-jf48kahn.js} +3 -3
  28. package/dist/{chunk-cqrkeq20.js → chunk-k4behavv.js} +1 -1
  29. package/dist/chunk-k63hr1eg.js +7 -0
  30. package/dist/{chunk-cfrbsnfb.js → chunk-kfg3vx5z.js} +1 -1
  31. package/dist/{chunk-rr62k3ar.js → chunk-pvxp2gzr.js} +1 -1
  32. package/dist/{chunk-f9b8h03c.js → chunk-qxvp127d.js} +1 -1
  33. package/dist/{chunk-b6mxeey0.js → chunk-rkhhzc4r.js} +2 -2
  34. package/dist/{chunk-22gxb9qs.js → chunk-rtn0rb16.js} +2 -2
  35. package/dist/chunk-txjvy8qp.js +1 -0
  36. package/dist/{chunk-qw2wy4jc.js → chunk-vw3f4mbt.js} +1 -1
  37. package/dist/chunk-w1zb8zac.js +3 -0
  38. package/dist/chunk-wev2rke6.js +1 -0
  39. package/dist/{chunk-t6y57501.js → chunk-wp67n9q7.js} +335 -334
  40. package/dist/{chunk-t3pyakvc.js → chunk-y50fy1gq.js} +2 -2
  41. package/dist/web/assets/{FilePreview-DXDzoFFc.js → FilePreview-IDRQBiWa.js} +1 -1
  42. package/dist/web/assets/{MarkdownRenderer-BVPOLK1b.js → MarkdownRenderer-BgDKGD2u.js} +1 -1
  43. package/dist/web/assets/{McpModal-DeTf34Fw.js → McpModal-CJ2l7j-5.js} +1 -1
  44. package/dist/web/assets/{SettingsModal-CDLkPyL-.js → SettingsModal-BWpbIioU.js} +1 -1
  45. package/dist/web/assets/{SettingsStore-DYKvNeV_.js → SettingsStore-BZjkLZcL.js} +1 -1
  46. package/dist/web/assets/{SkillsModal-D784AUrt.js → SkillsModal-CRuRJrN-.js} +1 -1
  47. package/dist/web/assets/{TerminalPanel-BosJuIct.js → TerminalPanel-BnZPkS19.js} +1 -1
  48. package/dist/web/assets/{dialog-CgyS_4Eo.js → dialog-DYRMhlp_.js} +1 -1
  49. package/dist/web/assets/index-Bu13aXyE.css +1 -0
  50. package/dist/web/assets/index-D4CAglTd.js +10 -0
  51. package/dist/web/index.html +2 -2
  52. package/package.json +1 -1
  53. package/dist/chunk-108p1xw7.js +0 -1
  54. package/dist/chunk-42q476bq.js +0 -1
  55. package/dist/chunk-4hk7wfat.js +0 -3
  56. package/dist/chunk-7d1pn8a1.js +0 -2
  57. package/dist/chunk-abpvdaq2.js +0 -6
  58. package/dist/chunk-hv0bzn31.js +0 -1
  59. package/dist/chunk-j3k2c6tm.js +0 -1
  60. package/dist/chunk-je6r01h4.js +0 -1
  61. package/dist/chunk-nh37erd3.js +0 -1
  62. package/dist/web/assets/index-Abieffcr.js +0 -10
  63. package/dist/web/assets/index-CQ3JnuUf.css +0 -1
@@ -1,6 +1,6 @@
1
- import{qb as N0}from"./chunk-p6d7k1x6.js";import{wb as g}from"./chunk-cadngkwr.js";import{Ab as YZ,Bb as Q0,Cb as WZ,Db as hQ}from"./chunk-m4a480k7.js";import{Fb as PQ,Nb as C}from"./chunk-4hk7wfat.js";function L0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class _0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(L0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!L0(J))}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(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!L0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function jZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function DQ(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function bQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function FQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var r0=C("Agent"),qZ=3;function s0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=qZ)return{action:"truncated"};if(DQ($)==="stop")return r0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var DZ=[/:\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],bZ=/```[\s\S]{50,}```/,OQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",FZ=2;function t0(Q,Z,$=!0){if(!Q||Z>=FZ)return{action:"none"};if(!$&&bZ.test(Q))return{action:"retry",prompt:OQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(DZ.some((G)=>G.test(J)))return{action:"retry",prompt:OQ};return{action:"none"}}var OZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],wZ=/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test|tsc)\b/i,wQ={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},LZ={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},_Z="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.",NZ="Required verification did not run successfully before the retry limit.",vZ=3;function o0(Q){return wZ.test(Q)}function _Q(Q,Z,$){if(!$.success)return;if(["Edit","Write","NotebookEdit"].includes(Z)){Q.clear();return}if(Z==="Bash"&&typeof $.metadata?.command==="string"&&$.metadata.exit_code===0&&o0($.metadata.command)){Q.add($.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let J=$.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let z of J)if(typeof z==="string"&&o0(z))Q.add(z)}function e0(Q,Z,$){if(!Q||!OZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(wQ).filter((Y)=>wQ[Y].test(Q)),z=[...Z],W=J.filter((Y)=>!z.some((B)=>LZ[Y].test(B)));if(J.length>0?W.length===0:z.some(o0))return{action:"none"};if($>=vZ)return{action:"fail",message:NZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${_Z}${V}`}}var IZ=[/\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|子代理|子智能体)/],EZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],SZ="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.",UZ="Required delegation did not complete before the retry limit.",yZ=3;function NQ(Q,Z,$){if(!Q||EZ.some((J)=>J.test(Q))||!IZ.some((J)=>J.test(Q))||Z.has("Task"))return{action:"none"};if($>=yZ)return{action:"fail",message:UZ};return{action:"retry",prompt:SZ}}var AZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],PZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i];function v0(Q){return typeof Q==="string"&&AZ.some((Z)=>Z.test(Q))}var MZ="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.",fZ="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.",hZ="Required worktree lifecycle did not complete before the retry limit.",kZ=3;function vQ(Q,Z,$){if(!Q||!v0(Q))return{action:"none"};let J=PZ.some((W)=>W.test(Q));if(Z.has("TaskWorktree"))return{action:"none"};let z=!Z.has("EnterWorktree")?"EnterWorktree":J&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if($>=kZ)return{action:"fail",message:hZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?MZ:fZ}}var LQ=30000;async function QQ(Q){try{let $=N0.getInstance().executeStopHooks({projectDir:g(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((W)=>{J=setTimeout(()=>W("timeout"),LQ)});try{let W=await Promise.race([$,z]);if(W==="timeout")return r0.warn(`[Loop] Stop hook 超时 (${LQ}ms),按 shouldStop: true 处理`),{action:"stop"};let G=W;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return r0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var $0=C("Agent"),ZQ=`<turn_aborted>
1
+ import{nb as N0}from"./chunk-jf48kahn.js";import{tb as g}from"./chunk-63dzf6hr.js";import{Ab as hQ,xb as YZ,yb as Q0,zb as WZ}from"./chunk-98jpdmgc.js";import{Cb as PQ,Lb as p}from"./chunk-w1zb8zac.js";function L0(Q){return Q.role==="system"&&Array.isArray(Q.content)}class _0{systemMessages;_history;_pending=[];context;constructor(Q,Z){this.context=Q;let $=Q.messages.find(L0);if($)this.systemMessages=[$];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]}];else this.systemMessages=[];this._history=Q.messages.filter((J)=>!L0(J))}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(Q){this._pending.push(Q)}appendUser(Q){this._pending.push(Q)}appendAssistant(Q){this._pending.push(Q)}appendToolResult(Q){this._pending.push(Q)}appendControl(Q,Z){if(Q==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory(Q){this._history.push(Q)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory(Q){this._history=Q.filter((Z)=>!L0(Z))}writeback(){this.commitPending(),this.context.messages=this._history}get hasSystemPrompt(){return this.systemMessages.length>0}}async function jZ(Q,Z){let $;while(!($=await Q.next()).done)if(Z)await Z($.value);return $.value}function DQ(Q){if(Q.isSubagent)return"continue";if(!Q.budget||Q.budget<=0)return"continue";if(Q.consecutiveContinuations>=3&&Q.lastOutputDelta<500)return"stop";if(Q.usage/Q.budget>=0.9)return"stop";return"continue"}function bQ(Q){return{budget:Q.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:Q.isSubagent??!1}}function FQ(Q,Z,$){return{...Q,usage:Q.usage+Z,lastOutputDelta:Z,consecutiveContinuations:$?Q.consecutiveContinuations+1:0}}var r0=p("Agent"),qZ=3;function s0(Q,Z,$){if(Q!=="length")return{action:"none"};if(Z>=qZ)return{action:"truncated"};if(DQ($)==="stop")return r0.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var DZ=[/:\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],bZ=/```[\s\S]{50,}```/,OQ="请执行你提到的操作,不要只是描述。使用 Edit/Write/Bash 工具来实际修改文件。",FZ=2;function t0(Q,Z,$=!0){if(!Q||Z>=FZ)return{action:"none"};if(!$&&bZ.test(Q))return{action:"retry",prompt:OQ};let J=Q.slice(-200),z=J.match(/```/g);if(z&&z.length%2!==0)return{action:"none"};if(DZ.some((G)=>G.test(J)))return{action:"retry",prompt:OQ};return{action:"none"}}var OZ=[/\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}(?:测试|单测|集成测试|检查|构建)/],wZ=/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test|tsc)\b/i,wQ={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},LZ={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},_Z="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.",NZ="Required verification did not run successfully before the retry limit.",vZ=3;function o0(Q){return wZ.test(Q)}function _Q(Q,Z,$){if(!$.success)return;if(["Edit","Write","NotebookEdit"].includes(Z)){Q.clear();return}if(Z==="Bash"&&typeof $.metadata?.command==="string"&&$.metadata.exit_code===0&&o0($.metadata.command)){Q.add($.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let J=$.metadata?.verificationCommands;if(!Array.isArray(J))return;for(let z of J)if(typeof z==="string"&&o0(z))Q.add(z)}function e0(Q,Z,$){if(!Q||!OZ.some((Y)=>Y.test(Q)))return{action:"none"};let J=Object.keys(wQ).filter((Y)=>wQ[Y].test(Q)),z=[...Z],W=J.filter((Y)=>!z.some((B)=>LZ[Y].test(B)));if(J.length>0?W.length===0:z.some(o0))return{action:"none"};if($>=vZ)return{action:"fail",message:NZ};let V=J.length>1&&W.length>0?` Missing successful verification categories: ${W.join(", ")}.`:"";return{action:"retry",prompt:`${_Z}${V}`}}var IZ=[/\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|子代理|子智能体)/],EZ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/],SZ="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.",UZ="Required delegation did not complete before the retry limit.",yZ=3;function NQ(Q,Z,$){if(!Q||EZ.some((J)=>J.test(Q))||!IZ.some((J)=>J.test(Q))||Z.has("Task"))return{action:"none"};if($>=yZ)return{action:"fail",message:UZ};return{action:"retry",prompt:SZ}}var AZ=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],PZ=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i];function v0(Q){return typeof Q==="string"&&AZ.some((Z)=>Z.test(Q))}var MZ="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.",fZ="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.",hZ="Required worktree lifecycle did not complete before the retry limit.",kZ=3;function vQ(Q,Z,$){if(!Q||!v0(Q))return{action:"none"};let J=PZ.some((W)=>W.test(Q));if(Z.has("TaskWorktree"))return{action:"none"};let z=!Z.has("EnterWorktree")?"EnterWorktree":J&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!z)return{action:"none"};if($>=kZ)return{action:"fail",message:hZ};return{action:"retry",tool:z,prompt:z==="EnterWorktree"?MZ:fZ}}var LQ=30000;async function QQ(Q){try{let $=N0.getInstance().executeStopHooks({projectDir:g(),sessionId:Q.sessionId,permissionMode:Q.permissionMode,reason:Q.reason,abortSignal:Q.abortSignal}),J,z=new Promise((W)=>{J=setTimeout(()=>W("timeout"),LQ)});try{let W=await Promise.race([$,z]);if(W==="timeout")return r0.warn(`[Loop] Stop hook 超时 (${LQ}ms),按 shouldStop: true 处理`),{action:"stop"};let G=W;if(!G.shouldStop)return{action:"continue",reason:G.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return r0.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}var $0=p("Agent"),ZQ=`<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
- </turn_aborted>`;function J0(Q){return Q.executionEngine?.getContextManager()}async function u(Q,Z,$,J=null){try{let z=J0(Q),W=typeof $==="string"?$.trim()!=="":$.some((G)=>G.type==="text"?G.text.trim()!=="":!0);if(z&&Z.sessionId&&W)return await z.saveMessage(Z.sessionId,"user",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存用户消息失败:",z)}return null}async function h(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存助手消息失败:",z)}return null}async function IQ(Q,Z,$){try{let J=J0(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",ZQ,$,void 0,Z.subagentInfo)}catch(J){$0.warn("[Loop] 保存中断边界失败:",J)}return null}async function $Q(Q,Z,$,J,z){try{let W=J0(Q);if(W&&Z.sessionId)return await W.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(W){$0.warn("[Loop] 保存工具调用失败:",W)}return null}async function JQ(Q,Z,$,J,z,W,G,V){try{let Y=J0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,W,G,Z.subagentInfo,V)}catch(Y){$0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function I0(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){$0.warn("[Loop] 保存压缩数据失败:",z)}return null}function EQ(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function SQ(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function UQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function xZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,$.worktreeActive=J?.workspaceTransition==="enter",z}function RZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",W=$.subagentStatus;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:$.subagentSummary};if(W==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:G}}return null}async function zQ(Q,Z,$,J){let z=EQ(Q,Z),W=RZ(Q,Z);SQ(Q,Z,$);let G=UQ(Z);if(G)await $.onModelSwitch?.(G);if(J)xZ(Q,Z,J);return W||z}import{nanoid as D2}from"nanoid";import{promises as uZ}from"node:fs";import{nanoid as s}from"nanoid";import*as U from"node:fs/promises";import*as e from"node:path";var yQ={enabled:!0,maxIndexLines:200};var TZ="memory",AQ="MEMORY.md";class WQ{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=PQ(Q);this.memoryDir=e.join(J,TZ)}this.config={...yQ,...Z}}async initialize(){if(this.initialized)return;await U.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=e.join(this.memoryDir,AQ);try{let Z=await U.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
3
+ </turn_aborted>`;function J0(Q){return Q.executionEngine?.getContextManager()}async function i(Q,Z,$,J=null,z){try{let W=J0(Q),G=typeof $==="string"?$.trim()!=="":$.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(W&&Z.sessionId&&G)return await W.saveMessage(Z.sessionId,"user",$,J,z,Z.subagentInfo)}catch(W){$0.warn("[Loop] 保存用户消息失败:",W)}return null}async function h(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId&&$.trim())return await z.saveMessage(Z.sessionId,"assistant",$,J,void 0,Z.subagentInfo)}catch(z){$0.warn("[Loop] 保存助手消息失败:",z)}return null}async function IQ(Q,Z,$){try{let J=J0(Q);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",ZQ,$,void 0,Z.subagentInfo)}catch(J){$0.warn("[Loop] 保存中断边界失败:",J)}return null}async function $Q(Q,Z,$,J,z){try{let W=J0(Q);if(W&&Z.sessionId)return await W.saveToolUse(Z.sessionId,$,J,z,Z.subagentInfo)}catch(W){$0.warn("[Loop] 保存工具调用失败:",W)}return null}async function JQ(Q,Z,$,J,z,W,G,V){try{let Y=J0(Q);if(Y&&Z.sessionId)return await Y.saveToolResult(Z.sessionId,$,J,z,W,G,Z.subagentInfo,V)}catch(Y){$0.warn("[Loop] 保存工具结果失败:",Y)}return null}async function I0(Q,Z,$,J){try{let z=J0(Q);if(z&&Z.sessionId)return await z.saveCompaction(Z.sessionId,$,J,null)}catch(z){$0.warn("[Loop] 保存压缩数据失败:",z)}return null}function EQ(Q,Z){if(!["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name)||!Z.success||!Z.llmContent&&!Z.metadata)return null;let $=typeof Z.llmContent==="object"?Z.llmContent:{};return{kind:"task_update",tasks:Z.metadata?.tasks||$.tasks||[]}}function SQ(Q,Z,$){if(Q.function.name!=="Skill"||!Z.success||!Z.metadata)return;let J=Z.metadata;if(J.skillName)$.onSkillActivated?.({skillName:J.skillName,allowedTools:J.allowedTools,basePath:J.basePath||""})}function UQ(Q){let Z=Q.metadata;if(!Z)return;return Z.modelId?.toString().trim()||Z.model?.toString().trim()||void 0||void 0}function xZ(Q,Z,$){if(!["EnterWorktree","ExitWorktree"].includes(Q.function.name)||!Z.success)return;let J=Z.metadata,z=J?.workspaceRoot;if(!["enter","exit"].includes(String(J?.workspaceTransition))||typeof z!=="string"||z.trim()==="")return;return $.workspaceRoot=z,$.worktreeActive=J?.workspaceTransition==="enter",z}function RZ(Q,Z){if(Q.function.name!=="Task")return null;let $=Z.metadata;if(!$?.subagentSessionId)return null;let J=$.subagentSessionId,z=$.subagentType||"Task",W=$.subagentStatus;if(W==="completed"||W==="failed"||W==="cancelled")return{kind:"subagent_completed",sessionId:J,success:W==="completed",summary:$.subagentSummary};if(W==="running"){let G="";try{G=JSON.parse(Q.function.arguments).prompt||""}catch{}return{kind:"subagent_spawned",sessionId:J,type:z,prompt:G}}return null}async function zQ(Q,Z,$,J){let z=EQ(Q,Z),W=RZ(Q,Z);SQ(Q,Z,$);let G=UQ(Z);if(G)await $.onModelSwitch?.(G);if(J)xZ(Q,Z,J);return W||z}import{nanoid as D2}from"nanoid";import{promises as uZ}from"node:fs";import{nanoid as s}from"nanoid";import*as U from"node:fs/promises";import*as e from"node:path";var yQ={enabled:!0,maxIndexLines:200};var TZ="memory",AQ="MEMORY.md";class WQ{memoryDir;config;initialized=!1;constructor(Q,Z,$){if($)this.memoryDir=$;else{let J=PQ(Q);this.memoryDir=e.join(J,TZ)}this.config={...yQ,...Z}}async initialize(){if(this.initialized)return;await U.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let Q=e.join(this.memoryDir,AQ);try{let Z=await U.readFile(Q,"utf-8");if(!Z.trim())return null;let $=Z.split(`
4
4
  `),z=$.slice(0,this.config.maxIndexLines).join(`
5
5
  `).trim();if($.length>this.config.maxIndexLines)return z+`
6
6
 
@@ -8,14 +8,14 @@ The previous turn was interrupted. Commands or tool calls may have partially com
8
8
  `)?`
9
9
  `:"";await U.writeFile(J,z+W+Z,"utf-8")}else await U.writeFile(J,Z,"utf-8")}async updateIndex(Q,Z="overwrite"){await this.initialize();let $=e.join(this.memoryDir,AQ);if(Z==="append"){let J="";try{J=await U.readFile($,"utf-8")}catch{}let z=J&&!J.endsWith(`
10
10
  `)?`
11
- `:"";await U.writeFile($,J+z+Q,"utf-8")}else await U.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await U.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=e.join(this.memoryDir,$.name),z=await U.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await U.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=e.join(this.memoryDir,`${$.name}.md`);try{await U.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=e.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var CZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],pZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,dZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function gZ(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:W}of CZ){let G=J.match(z);if(G?.[1]){let V=Z.get(W)??[];V.push(G[1].trim()),Z.set(W,V)}}if($.role==="assistant"){let z=J.match(pZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let W=Z.get("debugging")??[];W.push(z[1].trim()),Z.set("debugging",W)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(dZ);if(z?.[1]&&z[1].length>10){let W=Z.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",W)}}}return Z}async function MQ(Q){let Z=gZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new WQ(g());await $.initialize();let J=[],z=0;for(let[W,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=G.map((B)=>`- [${V}] ${B}`).join(`
11
+ `:"";await U.writeFile($,J+z+Q,"utf-8")}else await U.writeFile($,Q,"utf-8")}async listTopics(){await this.initialize();try{let Q=await U.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let $ of Q){if(!$.isFile()||!$.name.endsWith(".md"))continue;let J=e.join(this.memoryDir,$.name),z=await U.stat(J);Z.push({name:$.name.replace(/\.md$/,""),size:z.size,lastModified:z.mtime})}return Z.sort(($,J)=>J.lastModified.getTime()-$.lastModified.getTime())}catch{return[]}}async deleteTopic(Q){let Z=this.resolveTopicPath(Q);try{return await U.unlink(Z),!0}catch{return!1}}async clearAll(){let Q=await this.listTopics(),Z=0;for(let $ of Q){let J=e.join(this.memoryDir,`${$.name}.md`);try{await U.unlink(J),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath(Q){let Z=Q.replace(/[/\\:*?"<>|]/g,"-"),$=Z.endsWith(".md")?Z:`${Z}.md`,J=e.join(this.memoryDir,$);if(!J.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${Q}`);return J}}var CZ=[{pattern:/(?:记住|remember|note|备注)[::](.+)/i,topic:"preferences"},{pattern:/(?:convention|约定|规范)[::](.+)/i,topic:"conventions"},{pattern:/(?:lesson|教训|踩坑)[::](.+)/i,topic:"lessons"}],pZ=/(?:fix|修复|解决|resolved)[::]\s*(.+?)(?:\n|$)/i,dZ=/(?:Error|FAIL|错误)[::]\s*(.+?)(?:\n|$)/i;function mZ(Q){let Z=new Map;for(let $ of Q){if(!$.content||typeof $.content!=="string")continue;let J=$.content;if($.role==="user")for(let{pattern:z,topic:W}of CZ){let G=J.match(z);if(G?.[1]){let V=Z.get(W)??[];V.push(G[1].trim()),Z.set(W,V)}}if($.role==="assistant"){let z=J.match(pZ);if(z?.[1]&&z[1].length>20&&z[1].length<200){let W=Z.get("debugging")??[];W.push(z[1].trim()),Z.set("debugging",W)}}if($.role==="tool"&&$.content?.includes("Error")){let z=J.match(dZ);if(z?.[1]&&z[1].length>10){let W=Z.get("debugging")??[];if(W.length<5)W.push(`Tool error pattern: ${z[1].trim().slice(0,150)}`),Z.set("debugging",W)}}}return Z}async function MQ(Q){let Z=mZ(Q);if(Z.size===0)return{extracted:0,topics:[]};try{let $=new WQ(g());await $.initialize();let J=[],z=0;for(let[W,G]of Z){if(G.length===0)continue;let V=new Date().toISOString().split("T")[0],Y=G.map((B)=>`- [${V}] ${B}`).join(`
12
12
  `);await $.writeTopic(W,Y+`
13
- `,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as E0}from"node:fs";var B0=C("Tool");class o{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}async recordFileRead(Q,Z){try{let $=await E0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),B0.debug(`记录文件读取: ${Q}`)}catch($){B0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await E0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),B0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){B0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await E0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await E0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){o.instance=null}}import{readFile as mZ}from"node:fs/promises";import{basename as cZ}from"node:path";class S0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,z)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
14
- `);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((b)=>{this.updateFileReference(Z,b,z,q)})})}),Array.from(Z.values()).sort((J,z)=>{if(J.wasModified!==z.wasModified)return J.wasModified?-1:1;if(J.mentions!==z.mentions)return z.mentions-J.mentions;return z.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await mZ($,"utf-8"),z=J.split(`
13
+ `,"append"),J.push(W),z+=G.length}return{extracted:z,topics:J}}catch{return{extracted:0,topics:[]}}}import{promises as E0}from"node:fs";var B0=p("Tool");class o{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}async recordFileRead(Q,Z){try{let $=await E0.stat(Q),J={filePath:Q,accessTime:Date.now(),mtime:$.mtimeMs,sessionId:Z,lastOperation:"read"};this.accessedFiles.set(Q,J),B0.debug(`记录文件读取: ${Q}`)}catch($){B0.warn(`记录文件读取失败: ${Q}`,$)}}async recordFileEdit(Q,Z,$="edit"){try{let J=await E0.stat(Q),z={filePath:Q,accessTime:Date.now(),mtime:J.mtimeMs,sessionId:Z,lastOperation:$};this.accessedFiles.set(Q,z),B0.debug(`记录文件${$==="edit"?"编辑":"写入"}: ${Q}`)}catch(J){B0.warn(`记录文件${$==="edit"?"编辑":"写入"}失败: ${Q}`,J)}}hasFileBeenRead(Q,Z){let $=this.accessedFiles.get(Q);if(!$)return!1;if(Z&&$.sessionId!==Z)return!1;return!0}async checkFileModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{modified:!1,message:"文件未被跟踪"};try{let $=await E0.stat(Q);if(Math.abs($.mtimeMs-Z.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Z.accessTime).toISOString()}, 当前修改时间: ${$.mtime.toISOString()})`};return{modified:!1}}catch($){let J=$;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification(Q){let Z=this.accessedFiles.get(Q);if(!Z)return{isExternal:!1,message:"文件未被跟踪"};try{let $=await E0.stat(Q);if($.mtimeMs-Z.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Z.accessTime).toISOString()} (${Z.lastOperation}) 之后被外部程序修改(当前修改时间: ${$.mtime.toISOString()})`};return{isExternal:!1}}catch($){let J=$;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${Q}`,$),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord(Q){return this.accessedFiles.get(Q)}clearFileRecord(Q){this.accessedFiles.delete(Q)}clearAll(){this.accessedFiles.clear()}clearSession(Q){for(let[Z,$]of this.accessedFiles.entries())if($.sessionId===Q)this.accessedFiles.delete(Z)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){o.instance=null}}import{readFile as gZ}from"node:fs/promises";import{basename as cZ}from"node:path";class S0{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles(Q){let Z=new Map;return Q.forEach((J,z)=>{let W=typeof J.content==="string"?J.content:(J.content||[]).filter((V)=>V.type==="text").map((V)=>V.text).join(`
14
+ `);if(this.extractFilePathsFromContent(W).forEach((V)=>{this.updateFileReference(Z,V,z,!1)}),J.tool_calls&&Array.isArray(J.tool_calls))J.tool_calls.forEach((V)=>{let Y=this.extractFilePathsFromToolCall(V),B=V.type==="function"&&"function"in V?V.function?.name:"",q=["Write","Edit"].includes(B||"");Y.forEach((b)=>{this.updateFileReference(Z,b,z,q)})})}),Array.from(Z.values()).sort((J,z)=>{if(J.wasModified!==z.wasModified)return J.wasModified?-1:1;if(J.mentions!==z.mentions)return z.mentions-J.mentions;return z.lastMentioned-J.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent(Q){let Z=[];for(let $ of Q)try{let J=await gZ($,"utf-8"),z=J.split(`
15
15
  `),W=z.length,G=J,V=!1,Y=W;if(W>this.MAX_LINES_PER_FILE)G=z.slice(0,this.MAX_LINES_PER_FILE).join(`
16
16
  `),G+=`
17
17
 
18
- ... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=cZ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as fQ}from"js-tiktoken";class j0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),W=Math.floor($*J);return z>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=fQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=fQ("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}var P=C("Context"),U0=new Map,iZ=3;class z0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??j0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";P.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await N0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:g(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return P.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)P.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){P.warn("[CompactionService] Compaction hook execution failed:",G)}let z=Z.sessionId??"_default",W=U0.get(z)??0;if(W>=iZ)return P.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${z}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{P.debug("[CompactionService] 开始压缩,消息数:",Q.length),P.debug("[CompactionService] 压缩前 tokens:",$);let V=S0.analyzeFiles(Q).map((x)=>x.path);P.debug("[CompactionService] 提取重点文件:",V);let Y=await S0.readFilesContent(V);P.debug("[CompactionService] 成功读取文件:",Y.length);let B=await this.generateSummary(Q,Y,Z);P.debug("[CompactionService] 生成总结,长度:",B.length);let q=Math.ceil(Q.length*this.RETAIN_PERCENT),b=Q.slice(-q),X=new Set;for(let x of b)if(x.role==="assistant"&&x.tool_calls)for(let m of x.tool_calls)X.add(m.id);let L=b.filter((x)=>{if(x.role==="tool"&&x.tool_call_id)return X.has(x.tool_call_id);return!0});P.debug("[CompactionService] 保留消息数:",q),P.debug("[CompactionService] 过滤后保留消息数:",L.length);let k=s(),A=this.createBoundaryMessage(k,Z.trigger,$),F=s(),N=this.createSummaryMessage(F,B),j=[N,...L],G0=await this.buildFileRestorationMessage();if(G0)j.push(G0);let n=this.buildActiveTaskMessage(Z.activeTask);if(n)j.push(n);let Y0=j0.countTokens(j,Z.modelName);P.debug("[CompactionService] 压缩完成!"),P.debug("[CompactionService] Token 变化:",$,"->",Y0,`(-${((1-Y0/$)*100).toFixed(1)}%)`),U0.delete(z);let V0=Q.slice(0,Q.length-q);return MQ(V0).catch((x)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:Y0,filesIncluded:V,compactedMessages:j,boundaryMessage:A,summaryMessage:N}}catch(G){if(Q0(G))throw G;return U0.set(z,(U0.get(z)??0)+1),P.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(P.debug("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await hQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return P.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((W,G)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),B=5000,q=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${G+1}] ${V}: ${q}`}).join(`
18
+ ... (truncated ${W-this.MAX_LINES_PER_FILE} lines)`,V=!0,Y=this.MAX_LINES_PER_FILE;Z.push({path:$,content:G,truncated:V,lines:W,includedLines:Y})}catch(J){console.warn(`[FileAnalyzer] 无法读取文件: ${$}`,J)}return Z}static extractFilePathsFromContent(Q){let Z=new Set,$=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,J=Array.from(Q.matchAll($));for(let W of J){let G=W[1];this.extractPathsFromText(G).forEach((Y)=>Z.add(Y))}return this.extractPathsFromText(Q).forEach((W)=>Z.add(W)),Array.from(Z)}static extractPathsFromText(Q){let Z=[],$=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let J of $){let z=Array.from(Q.matchAll(J));for(let W of z){let G=W[0];if(G=G.replace(/[,。;:!?""''()【】《》]$/g,""),G=G.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(G))Z.push(G)}}return Z}static extractFilePathsFromToolCall(Q){let Z=[];if(Q.type!=="function"||!Q.function)return Z;try{let $=Q.function.name,J=JSON.parse(Q.function.arguments||"{}");if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes($)){let W=["file_path","path","notebook_path","filePath"];for(let G of W)if(J[G]&&typeof J[G]==="string")Z.push(J[G])}}catch{}return Z}static updateFileReference(Q,Z,$,J){let z=Q.get(Z);if(z)z.mentions++,z.lastMentioned=$,z.wasModified=z.wasModified||J;else Q.set(Z,{path:Z,mentions:1,lastMentioned:$,wasModified:J})}static isValidFilePath(Q){if(!Q.includes("/"))return!1;let Z=cZ(Q);if(!Z.includes("."))return!1;let $=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],J=Z.split(".").pop()?.toLowerCase();if(!J||!$.includes(J))return!1;return!0}}import{encodingForModel as fQ}from"js-tiktoken";class j0{static encodingCache=new Map;static countTokens(Q,Z){let $=this.getEncoding(Z),J=0;for(let z of Q){if(J+=4,z.role)J+=$.encode(z.role).length;if(z.content)if(typeof z.content==="string")J+=$.encode(z.content).length;else J+=$.encode(JSON.stringify(z.content)).length;if(z.tool_calls&&Array.isArray(z.tool_calls))J+=this.countToolCallTokens(z.tool_calls,$);if(z.name)J+=$.encode(z.name).length}return J}static getTokenLimit(Q){return Q}static shouldCompact(Q,Z,$,J=0.8){let z=this.countTokens(Q,Z),W=Math.floor($*J);return z>=W}static getEncoding(Q){if(!this.encodingCache.has(Q))try{let Z=fQ(Q);this.encodingCache.set(Q,Z)}catch{try{let Z=fQ("gpt-4");this.encodingCache.set(Q,Z)}catch{console.warn(`[TokenCounter] 无法为模型 ${Q} 获取 encoding,使用粗略估算`),this.encodingCache.set(Q,{encode:(Z)=>{return Array(Math.ceil(Z.length/4))}})}}return this.encodingCache.get(Q)}static countToolCallTokens(Q,Z){let $=0;for(let J of Q){if($+=4,J.type==="function"&&J.function?.name)$+=Z.encode(J.function.name).length;if(J.type==="function"&&J.function?.arguments)$+=Z.encode(J.function.arguments).length;if(J.id)$+=Z.encode(J.id).length}return $}static clearCache(){this.encodingCache.clear()}static estimateTokens(Q){let Z=(Q.match(/[\u4e00-\u9fa5]/g)||[]).length,$=Q.length-Z;return Math.ceil(Z/1.5+$/4)}}var P=p("Context"),U0=new Map,iZ=3;class z0{static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static ACTIVE_TASK_MAX_CHARS=6000;static async compact(Q,Z){if(Z.signal?.aborted)throw new DOMException("Aborted","AbortError");let $=Z.actualPreTokens??j0.countTokens(Q,Z.modelName),J=Z.actualPreTokens?"actual (from LLM usage)":"estimated";P.debug(`[CompactionService] preTokens source: ${J}`);try{let V=await N0.getInstance().executeCompactionHooks(Z.trigger,{projectDir:g(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",messagesBefore:Q.length,tokensBefore:$});if(V.blockCompaction)return P.debug(`[CompactionService] Compaction hook 阻止压缩: ${V.blockReason||"(无原因)"}`),{success:!1,summary:"",preTokens:$,postTokens:$,filesIncluded:[],compactedMessages:Q,boundaryMessage:{role:"system",content:""},summaryMessage:{role:"user",content:""},error:V.blockReason||"Compaction blocked by hook"};if(V.warning)P.warn(`[CompactionService] Compaction hook warning: ${V.warning}`)}catch(G){P.warn("[CompactionService] Compaction hook execution failed:",G)}let z=Z.sessionId??"_default",W=U0.get(z)??0;if(W>=iZ)return P.warn(`[CompactionService] Circuit breaker open (${W} consecutive failures for session ${z}), using fallback`),this.fallbackCompact(Q,Z,$,Error("Circuit breaker open"));try{P.debug("[CompactionService] 开始压缩,消息数:",Q.length),P.debug("[CompactionService] 压缩前 tokens:",$);let V=S0.analyzeFiles(Q).map((x)=>x.path);P.debug("[CompactionService] 提取重点文件:",V);let Y=await S0.readFilesContent(V);P.debug("[CompactionService] 成功读取文件:",Y.length);let B=await this.generateSummary(Q,Y,Z);P.debug("[CompactionService] 生成总结,长度:",B.length);let q=Math.ceil(Q.length*this.RETAIN_PERCENT),b=Q.slice(-q),X=new Set;for(let x of b)if(x.role==="assistant"&&x.tool_calls)for(let c of x.tool_calls)X.add(c.id);let L=b.filter((x)=>{if(x.role==="tool"&&x.tool_call_id)return X.has(x.tool_call_id);return!0});P.debug("[CompactionService] 保留消息数:",q),P.debug("[CompactionService] 过滤后保留消息数:",L.length);let k=s(),A=this.createBoundaryMessage(k,Z.trigger,$),F=s(),N=this.createSummaryMessage(F,B),j=[N,...L],G0=await this.buildFileRestorationMessage();if(G0)j.push(G0);let l=this.buildActiveTaskMessage(Z.activeTask);if(l)j.push(l);let Y0=j0.countTokens(j,Z.modelName);P.debug("[CompactionService] 压缩完成!"),P.debug("[CompactionService] Token 变化:",$,"->",Y0,`(-${((1-Y0/$)*100).toFixed(1)}%)`),U0.delete(z);let V0=Q.slice(0,Q.length-q);return MQ(V0).catch((x)=>{return}),{success:!0,summary:B,preTokens:$,postTokens:Y0,filesIncluded:V,compactedMessages:j,boundaryMessage:A,summaryMessage:N}}catch(G){if(Q0(G))throw G;return U0.set(z,(U0.get(z)??0)+1),P.error("[CompactionService] 压缩失败,使用降级策略",G),this.fallbackCompact(Q,Z,$,G)}}static async generateSummary(Q,Z,$){let J=this.buildCompactionPrompt(Q,Z);if(P.debug("[CompactionService] 使用压缩模型:",$.modelName),$.signal?.aborted)throw new DOMException("Aborted","AbortError");let G=(await(await hQ({apiKey:$.apiKey||process.env.BLADE_API_KEY||"",baseUrl:$.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:$.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"})).chat([{role:"user",content:J}],[],$.signal)).content||"",V=G.match(/<summary>([\s\S]*?)<\/summary>/);if(!V)return P.warn("[CompactionService] 总结格式不正确,使用完整响应"),G;return V[1].trim()}static buildCompactionPrompt(Q,Z){let $=Q.map((W,G)=>{let V=W.role||"unknown",Y=typeof W.content==="string"?W.content:JSON.stringify(W.content),B=5000,q=Y.length>5000?Y.substring(0,5000)+"...":Y;return`[${G+1}] ${V}: ${q}`}).join(`
19
19
 
20
20
  `),J=Z.map((W)=>{return`### ${W.path}
21
21
  \`\`\`
@@ -116,7 +116,7 @@ ${q}
116
116
  ${z}
117
117
  Full output saved to: ${V}`}catch{return`${Z}
118
118
 
119
- ${z}`}}import*as h0 from"node:fs/promises";import{homedir as rQ}from"node:os";import*as i from"node:path";var y0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function pQ(){return{metadata:y0,instructions:`# Skill Creator
119
+ ${z}`}}import*as h0 from"node:fs/promises";import{homedir as rQ}from"node:os";import*as n from"node:path";var y0={name:"skill-creator",description:"Create new Skills interactively. Use when the user wants to create a new Skill, define a custom workflow, or add a specialized capability to Blade.",allowedTools:["Read","Write","Glob","Bash","AskUserQuestion"],version:"1.0.0",argumentHint:void 0,userInvocable:!0,disableModelInvocation:!1,model:void 0,whenToUse:"User wants to create a new skill, define a custom workflow, or add a specialized capability.",path:"builtin://skill-creator",basePath:"",source:"builtin"};function pQ(){return{metadata:y0,instructions:`# Skill Creator
120
120
 
121
121
  帮助用户创建新的 Blade Skills。
122
122
 
@@ -572,11 +572,11 @@ ConfigTool({
572
572
  2. **permissions 字段使用 replace 策略**:设置 permissions 会完全替换现有值。如果只想添加规则,先 GET 当前值,合并后再 SET
573
573
  3. **env 字段使用 deep-merge 策略**:可以逐个添加环境变量
574
574
  4. **scope 默认值**:不指定 scope 时,根据字段路由表决定(hooks/permissions/env 默认 local,temperature/theme 等默认 global)
575
- `}}import{exec as eZ}from"node:child_process";import*as w from"node:fs/promises";import{homedir as Q2}from"node:os";import*as E from"node:path";import{promisify as Z2}from"node:util";var P0=Z2(eZ),I=C("General"),HQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class gQ{skillsDir;constructor(Q){this.skillsDir=Q||E.join(Q2(),".blade","skills")}async isInstalled(Q){let Z=E.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await P0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=HQ,J=E.join(this.skillsDir,Q),z=E.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let W=E.join(z,"skills",Q);try{await w.access(W)}catch{return I.warn(`Skill ${Q} not found in official repository`),await w.rm(z,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(W,J,{recursive:!0}),await w.rm(z,{recursive:!0,force:!0}),I.info(`Successfully installed: ${Q}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of HQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=E.join(this.skillsDir,$),z=E.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let W=E.join(z,"SKILL.md");try{await w.access(W)}catch{return I.warn(`No SKILL.md found in repository ${Q}`),await w.rm(z,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(z,J);try{await w.rm(E.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||E.basename(Q),z=E.join(this.skillsDir,J);try{let W=E.resolve(Q);try{await w.access(W)}catch{return I.warn(`Local path does not exist: ${W}`),!1}let G=E.join(W,"SKILL.md");try{await w.access(G)}catch{return I.warn(`No SKILL.md found in local path: ${W}`),!1}if(I.info(`Installing skill from local path: ${W}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(z,{recursive:!0,force:!0}),$)await w.symlink(W,z,"dir"),I.info(`Created symlink for skill: ${J}`);else await w.cp(W,z,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(W){return I.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=HQ,$=E.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await P0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let W=E.join($,"skills"),G=await w.readdir(W,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let Y=V.name,B=E.join(W,Y),q=E.join(this.skillsDir,Y);try{await w.access(E.join(B,"SKILL.md")),await w.rm(q,{recursive:!0,force:!0}),await w.cp(B,q,{recursive:!0}),I.info(`Installed: ${Y}`),J.push(Y)}catch(b){I.warn(`Failed to install ${Y}`),z.push(Y)}}await w.rm($,{recursive:!0,force:!0})}catch(W){try{await w.rm($,{recursive:!0,force:!0})}catch{}I.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:z}}}var XQ=null;function mQ(Q){if(!XQ)XQ=new gQ(Q);return XQ}import*as b0 from"node:fs/promises";import*as M0 from"node:path";import{parse as $2}from"yaml";var J2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,z2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,cQ=1024;function W2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function uQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function G2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!z2.test(Q.name))return{valid:!1,error:`Invalid name "${Q.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!Q.description)return{valid:!1,error:"Missing required field: description"};if(Q.description.length>cQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${cQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:W2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:uQ(Q["user-invocable"]),disableModelInvocation:uQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function iQ(Q,Z,$){let J=Q.match(J2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,W]=J,G;try{G=$2(z)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=G2(G,Z);if(!V.valid)return{success:!1,error:V.error};let Y=M0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:W.trim()}}}async function nQ(Q,Z){try{let $=await b0.readFile(Q,"utf-8");return iQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function lQ(Q){try{let Z=await b0.readFile(Q.path,"utf-8"),$=iQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function aQ(Q){try{return await b0.access(M0.join(Q,"SKILL.md")),!0}catch{return!1}}var Y2={userSkillsDir:i.join(rQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:i.join(rQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},f0=null;class KQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...Y2,cwd:g(),...Q}}static getInstance(Q){if(!f0)f0=new KQ(Q);return f0}static resetInstance(){f0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await mQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let z=i.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:i.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(z,"project");Z.push(...W.skills),Q.push(...W.errors);let G=i.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:i.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(y0.name,y0),this.skills.set(A0.name,A0)}async scanDirectory(Q,Z){let $=[],J=[];try{await h0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await h0.readdir(Q,{withFileTypes:!0});for(let W of z){if(!W.isDirectory())continue;let G=i.join(Q,W.name),V=i.join(G,"SKILL.md");if(!await aQ(G))continue;let Y=await nQ(V,Z);if(Y.success&&Y.content)$.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(z){J.push({path:Q,error:`Failed to scan directory: ${z instanceof Error?z.message:String(z)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return lQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return pQ();case"update-config":return dQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
575
+ `}}import{exec as eZ}from"node:child_process";import*as w from"node:fs/promises";import{homedir as Q2}from"node:os";import*as E from"node:path";import{promisify as Z2}from"node:util";var P0=Z2(eZ),I=p("General"),HQ={url:"https://github.com/anthropics/skills.git",branch:"main",defaultSkills:["skill-creator"]};class mQ{skillsDir;constructor(Q){this.skillsDir=Q||E.join(Q2(),".blade","skills")}async isInstalled(Q){let Z=E.join(this.skillsDir,Q,"SKILL.md");try{return await w.access(Z),!0}catch{return!1}}async isGitAvailable(){try{return await P0("git --version"),!0}catch{return!1}}async installOfficialSkill(Q){let{url:Z,branch:$}=HQ,J=E.join(this.skillsDir,Q),z=E.join(this.skillsDir,`.tmp-${Q}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),!1;I.info(`Installing official skill: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 --branch ${$} --single-branch ${Z} "${z}"`,{timeout:30000});let W=E.join(z,"skills",Q);try{await w.access(W)}catch{return I.warn(`Skill ${Q} not found in official repository`),await w.rm(z,{recursive:!0,force:!0}),!1}try{await w.rm(J,{recursive:!0,force:!0})}catch{}return await w.cp(W,J,{recursive:!0}),await w.rm(z,{recursive:!0,force:!0}),I.info(`Successfully installed: ${Q}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async ensureDefaultSkillsInstalled(){await w.mkdir(this.skillsDir,{recursive:!0,mode:493});for(let Q of HQ.defaultSkills)if(!await this.isInstalled(Q))await this.installOfficialSkill(Q)}async installFromRepo(Q,Z){let $=Z||this.extractRepoName(Q),J=E.join(this.skillsDir,$),z=E.join(this.skillsDir,`.tmp-repo-${$}-${Date.now()}`);try{if(!await this.isGitAvailable())return I.warn("Git not available, cannot install from repo"),!1;I.info(`Installing skill from repo: ${Q}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await P0(`git clone --depth 1 "${Q}" "${z}"`,{timeout:60000});let W=E.join(z,"SKILL.md");try{await w.access(W)}catch{return I.warn(`No SKILL.md found in repository ${Q}`),await w.rm(z,{recursive:!0,force:!0}),!1}await w.rm(J,{recursive:!0,force:!0}),await w.rename(z,J);try{await w.rm(E.join(J,".git"),{recursive:!0,force:!0})}catch{}return I.info(`Successfully installed skill from repo: ${$}`),!0}catch(W){try{await w.rm(z,{recursive:!0,force:!0})}catch{}return I.warn(`Failed to install from repo ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}async installFromLocal(Q,Z,$=!0){let J=Z||E.basename(Q),z=E.join(this.skillsDir,J);try{let W=E.resolve(Q);try{await w.access(W)}catch{return I.warn(`Local path does not exist: ${W}`),!1}let G=E.join(W,"SKILL.md");try{await w.access(G)}catch{return I.warn(`No SKILL.md found in local path: ${W}`),!1}if(I.info(`Installing skill from local path: ${W}...`),await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),await w.rm(z,{recursive:!0,force:!0}),$)await w.symlink(W,z,"dir"),I.info(`Created symlink for skill: ${J}`);else await w.cp(W,z,{recursive:!0}),I.info(`Copied skill to: ${J}`);return!0}catch(W){return I.warn(`Failed to install from local path ${Q}: ${W instanceof Error?W.message:"Unknown error"}`),!1}}extractRepoName(Q){return Q.match(/\/([^/]+?)(\.git)?$/)?.[1]||"unknown-skill"}async installAllOfficialSkills(){let{url:Q,branch:Z}=HQ,$=E.join(this.skillsDir,`.tmp-all-${Date.now()}`),J=[],z=[];try{if(!await this.isGitAvailable())return I.warn("Git not available, skipping skill installation"),{installed:J,failed:z};await w.mkdir(this.skillsDir,{recursive:!0,mode:493}),I.info("Cloning official skills repository..."),await P0(`git clone --depth 1 --branch ${Z} --single-branch ${Q} "${$}"`,{timeout:60000});let W=E.join($,"skills"),G=await w.readdir(W,{withFileTypes:!0});for(let V of G){if(!V.isDirectory())continue;let Y=V.name,B=E.join(W,Y),q=E.join(this.skillsDir,Y);try{await w.access(E.join(B,"SKILL.md")),await w.rm(q,{recursive:!0,force:!0}),await w.cp(B,q,{recursive:!0}),I.info(`Installed: ${Y}`),J.push(Y)}catch(b){I.warn(`Failed to install ${Y}`),z.push(Y)}}await w.rm($,{recursive:!0,force:!0})}catch(W){try{await w.rm($,{recursive:!0,force:!0})}catch{}I.warn(`Failed to install skills: ${W instanceof Error?W.message:"Unknown error"}`)}return{installed:J,failed:z}}}var XQ=null;function gQ(Q){if(!XQ)XQ=new mQ(Q);return XQ}import*as b0 from"node:fs/promises";import*as M0 from"node:path";import{parse as $2}from"yaml";var J2=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,z2=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/,cQ=1024;function W2(Q){if(!Q)return;if(typeof Q==="string")return Q.split(",").map((Z)=>Z.trim()).filter(Boolean);if(Array.isArray(Q))return Q.map((Z)=>String(Z).trim()).filter(Boolean);return}function uQ(Q){if(Q===void 0)return;if(typeof Q==="boolean")return Q;if(typeof Q==="string"){let Z=Q.toLowerCase().trim();if(Z==="true"||Z==="yes"||Z==="1")return!0;if(Z==="false"||Z==="no"||Z==="0")return!1}return}function G2(Q,Z){if(!Q.name)return{valid:!1,error:"Missing required field: name"};if(!z2.test(Q.name))return{valid:!1,error:`Invalid name "${Q.name}": must be lowercase letters, numbers, and hyphens only, 1-64 characters`};if(!Q.description)return{valid:!1,error:"Missing required field: description"};if(Q.description.length>cQ)return{valid:!1,error:`Description too long: ${Q.description.length} characters (max ${cQ})`};let $;if(Q.model)$=Q.model==="inherit"?"inherit":Q.model;return{valid:!0,metadata:{name:Q.name,description:Q.description.trim(),allowedTools:W2(Q["allowed-tools"]),version:Q.version,argumentHint:Q["argument-hint"]?.trim(),userInvocable:uQ(Q["user-invocable"]),disableModelInvocation:uQ(Q["disable-model-invocation"]),model:$,whenToUse:Q.when_to_use?.trim()}}}function iQ(Q,Z,$){let J=Q.match(J2);if(!J)return{success:!1,error:"Invalid SKILL.md format: missing YAML frontmatter (must start with ---)"};let[,z,W]=J,G;try{G=$2(z)}catch(B){return{success:!1,error:`Failed to parse YAML frontmatter: ${B instanceof Error?B.message:String(B)}`}}let V=G2(G,Z);if(!V.valid)return{success:!1,error:V.error};let Y=M0.dirname(Z);return{success:!0,content:{metadata:{...V.metadata,path:Z,basePath:Y,source:$},instructions:W.trim()}}}async function nQ(Q,Z){try{let $=await b0.readFile(Q,"utf-8");return iQ($,Q,Z)}catch($){if($.code==="ENOENT")return{success:!1,error:`File not found: ${Q}`};return{success:!1,error:`Failed to read file: ${$ instanceof Error?$.message:String($)}`}}}async function lQ(Q){try{let Z=await b0.readFile(Q.path,"utf-8"),$=iQ(Z,Q.path,Q.source);return $.success?$.content:null}catch{return null}}async function aQ(Q){try{return await b0.access(M0.join(Q,"SKILL.md")),!0}catch{return!1}}var Y2={userSkillsDir:n.join(rQ(),".blade","skills"),projectSkillsDir:".blade/skills",claudeUserSkillsDir:n.join(rQ(),".claude","skills"),claudeProjectSkillsDir:".claude/skills"},f0=null;class KQ{skills=new Map;pluginSkills=new Map;config;initialized=!1;constructor(Q){this.config={...Y2,cwd:g(),...Q}}static getInstance(Q){if(!f0)f0=new KQ(Q);return f0}static resetInstance(){f0=null}async initialize(){if(this.initialized)return{skills:Array.from(this.skills.values()),errors:[]};let Q=[],Z=[];try{await gQ(this.config.userSkillsDir).ensureDefaultSkillsInstalled()}catch(Y){Q.push({path:"SkillInstaller",error:`Failed to install default skills: ${Y instanceof Error?Y.message:"Unknown error"}`})}this.loadBuiltinSkills();let $=await this.scanDirectory(this.config.claudeUserSkillsDir,"user");Z.push(...$.skills),Q.push(...$.errors);let J=await this.scanDirectory(this.config.userSkillsDir,"user");Z.push(...J.skills),Q.push(...J.errors);let z=n.isAbsolute(this.config.claudeProjectSkillsDir)?this.config.claudeProjectSkillsDir:n.join(this.config.cwd,this.config.claudeProjectSkillsDir),W=await this.scanDirectory(z,"project");Z.push(...W.skills),Q.push(...W.errors);let G=n.isAbsolute(this.config.projectSkillsDir)?this.config.projectSkillsDir:n.join(this.config.cwd,this.config.projectSkillsDir),V=await this.scanDirectory(G,"project");Z.push(...V.skills),Q.push(...V.errors);for(let Y of Z)this.skills.set(Y.name,Y);return this.initialized=!0,{skills:Array.from(this.skills.values()),errors:Q}}loadBuiltinSkills(){this.skills.set(y0.name,y0),this.skills.set(A0.name,A0)}async scanDirectory(Q,Z){let $=[],J=[];try{await h0.access(Q)}catch{return{skills:$,errors:J}}try{let z=await h0.readdir(Q,{withFileTypes:!0});for(let W of z){if(!W.isDirectory())continue;let G=n.join(Q,W.name),V=n.join(G,"SKILL.md");if(!await aQ(G))continue;let Y=await nQ(V,Z);if(Y.success&&Y.content)$.push(Y.content.metadata);else J.push({path:V,error:Y.error||"Unknown error"})}}catch(z){J.push({path:Q,error:`Failed to scan directory: ${z instanceof Error?z.message:String(z)}`})}return{skills:$,errors:J}}getAll(){return Array.from(this.skills.values())}get(Q){return this.skills.get(Q)}has(Q){return this.skills.has(Q)}async loadContent(Q){let Z=this.skills.get(Q);if(!Z)return null;if(Z.source==="builtin")return this.loadBuiltinContent(Q);return lQ(Z)}loadBuiltinContent(Q){switch(Q){case"skill-creator":return pQ();case"update-config":return dQ();default:return null}}getModelInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>!Q.disableModelInvocation)}getUserInvocableSkills(){return Array.from(this.skills.values()).filter((Q)=>Q.userInvocable===!0)}generateAvailableSkillsList(){let Q=this.getModelInvocableSkills();if(Q.length===0)return"";let Z=[];for(let $ of Q){let J=$.description.length>100?`${$.description.substring(0,97)}...`:$.description,z=$.argumentHint?`${$.name} ${$.argumentHint}`:$.name;Z.push(`- ${z}: ${J}`)}return Z.join(`
576
576
  `)}get size(){return this.skills.size}async refresh(){return this.skills.clear(),this.pluginSkills.clear(),this.initialized=!1,this.initialize()}registerPluginSkill(Q){this.pluginSkills.set(Q.namespacedName,Q),this.skills.set(Q.namespacedName,Q.metadata)}findPluginSkill(Q){let Z=this.pluginSkills.get(Q);if(Z)return Z;let $=[];for(let J of this.pluginSkills.values())if(J.originalName===Q)$.push(J);if($.length===1)return $[0];return}getAllPluginSkills(){return Array.from(this.pluginSkills.values())}clearPluginSkills(){for(let Q of this.pluginSkills.values())this.skills.delete(Q.namespacedName);this.pluginSkills.clear()}getPluginSkillCount(){return this.pluginSkills.size}}function k0(Q){return KQ.getInstance(Q)}async function V2(Q){return k0(Q).initialize()}var H2="Skill",X2=/<available_skills>\s*<\/available_skills>/;function BQ(Q){let $=k0().generateAvailableSkillsList();if(!$)return Q;return Q.map((J)=>{if(J.name!==H2)return J;let z=J.description.replace(X2,`<available_skills>
577
577
  ${$}
578
578
  </available_skills>`);if(z===J.description)return J;return{...J,description:z}})}function oQ(){return{consecutiveFailures:new Map,totalFailures:0,lastFailedTool:null}}function sQ(Q,Z){Q.consecutiveFailures.set(Z,0),Q.lastFailedTool=null}function tQ(Q,Z){let $=(Q.consecutiveFailures.get(Z)??0)+1;Q.consecutiveFailures.set(Z,$),Q.totalFailures++,Q.lastFailedTool=Z}function K2(Q,Z){return(Q.consecutiveFailures.get(Z)??0)>=3}function eQ(Q,Z){if(!K2(Q,Z))return;let $=Q.consecutiveFailures.get(Z)??0;return`WARNING: ${Z} has failed ${$} consecutive times. Consider a different approach: use a different tool, verify your parameters, or break the task into smaller steps.`}function QZ(Q){return Q>0&&Q%5===0}function ZZ(Q,Z){let $=[`[Self-check at turn ${Q}]`,"Before continuing, briefly assess:","1. Are you making progress toward the goal?","2. Have any approaches failed repeatedly that you should abandon?","3. Is there a simpler path you haven't tried?"];if(Z>3)$.push(`Note: ${Z} tool failures so far. Consider whether your current strategy needs adjustment.`);return $.join(`
579
- `)}function $Z(){return{recentOutputHashes:[]}}function B2(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function JZ(Q,Z){let $=B2(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),z=J.every((W)=>W===J[0]);if(z)Q.recentOutputHashes=[];return z}function zZ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var t=C("Agent"),q2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class x0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,z,W,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=W;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){t.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),q2.has(Q.function.name)){t.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else t.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){t.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),t.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let z=this.abortController.signal;try{if(z.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(X){t.warn("[StreamingToolExecutor] 保存工具调用失败:",X)}let G=[z,J.signal],V=this.execContext.signal;if(V)G.push(V);let Y=WZ(...G),B={...this.execContext,signal:Y},q=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return t.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let b={toolCall:Q,result:q,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,b);return b}catch(W){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");t.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let G={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var y=C("Agent"),b2=0.1,F2=8192,O2=32768,R0=100,w2=`
579
+ `)}function $Z(){return{recentOutputHashes:[]}}function B2(Q){let Z=Q.trim().slice(0,500),$=0;for(let J=0;J<Z.length;J++)$=($<<5)-$+Z.charCodeAt(J)|0;return $.toString(36)}function JZ(Q,Z){let $=B2(Z);if(Q.recentOutputHashes.push($),Q.recentOutputHashes.length>4)Q.recentOutputHashes.shift();if(Q.recentOutputHashes.length<3)return!1;let J=Q.recentOutputHashes.slice(-3),z=J.every((W)=>W===J[0]);if(z)Q.recentOutputHashes=[];return z}function zZ(){return"WARNING: You appear to be repeating the same output. Stop and try a fundamentally different approach. If the task cannot be completed, explain why and stop."}var t=p("Agent"),q2=new Set(["Read","Glob","Grep","WebFetch","WebSearch","MemoryRead","GetSpecContext","ValidateSpec","TaskOutput"]);class x0{pipeline;execContext;registry;contextMgr;sessionId;lastMessageUuid;subagentInfo;pending=new Map;completed=new Map;queued=[];order=[];dispatched=new Set;abortController=new AbortController;epoch=0;activeAborts=new Map;constructor(Q,Z,$,J,z,W,G){this.pipeline=Q;this.execContext=Z;this.registry=$;this.contextMgr=J;this.sessionId=z;this.lastMessageUuid=W;this.subagentInfo=G}addTool(Q,Z){if(this.dispatched.has(Q.id)){t.debug(`[StreamingToolExecutor] 跳过已分发工具: ${Q.function.name} (${Q.id})`);return}if(this.dispatched.add(Q.id),this.order.push(Q.id),q2.has(Q.function.name)){t.debug(`[StreamingToolExecutor] 立即执行预启动工具: ${Q.function.name}`);let J=this.executeOne(Q,Z);this.pending.set(Q.id,J)}else t.debug(`[StreamingToolExecutor] 排队非预启动工具: ${Q.function.name}`),this.queued.push({toolCall:Q,params:Z})}async*getRemainingResults(){for(let Q of this.order){if(this.completed.has(Q)){yield this.completed.get(Q),this.completed.delete(Q);continue}if(this.pending.has(Q)){let $=await this.pending.get(Q);this.pending.delete(Q),yield $;continue}let Z=this.queued.findIndex(($)=>$.toolCall.id===Q);if(Z!==-1){let{toolCall:$,params:J}=this.queued[Z];if(this.queued.splice(Z,1),this.execContext.signal?.aborted){t.debug(`[StreamingToolExecutor] Signal aborted, 跳过排队工具: ${$.function.name} (${$.id})`),yield this.makeAbortResult($,"Tool execution skipped: task aborted before launch");continue}yield await this.executeOne($,J)}}}getCompletedResults(){let Q=Array.from(this.completed.values());return this.completed.clear(),Q}discard(){this.epoch++,this.abortController.abort(),this.abortController=new AbortController;for(let[,Q]of this.activeAborts)Q.abort();this.activeAborts.clear(),this.queued=[],this.order=[],this.dispatched.clear(),this.completed.clear(),this.pending.clear(),t.debug(`[StreamingToolExecutor] 已丢弃所有挂起工作并重置状态 (epoch=${this.epoch})`)}hasTools(){return this.order.length>0}getEpoch(){return this.epoch}makeAbortResult(Q,Z){return{toolCall:Q,result:{success:!1,llmContent:"",error:{type:"execution_error",message:Z},metadata:{abortedBeforeLaunch:!0}},toolUseUuid:null}}async executeOne(Q,Z){let $=this.epoch,J=new AbortController;this.activeAborts.set(Q.id,J);let z=this.abortController.signal;try{if(z.aborted||J.signal.aborted)return this.makeAbortResult(Q,"Tool execution aborted due to discard");let W=null;try{if(this.contextMgr&&this.sessionId)W=await this.contextMgr.saveToolUse(this.sessionId,Q.function.name,Z,this.lastMessageUuid??null,this.subagentInfo)}catch(X){t.warn("[StreamingToolExecutor] 保存工具调用失败:",X)}let G=[z,J.signal],V=this.execContext.signal;if(V)G.push(V);let Y=WZ(...G),B={...this.execContext,signal:Y},q=await this.pipeline.execute(Q.function.name,Z,B);if($!==this.epoch)return t.debug(`[StreamingToolExecutor] 丢弃旧世代工具结果: ${Q.function.name} (startEpoch=${$}, currentEpoch=${this.epoch})`),this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");let b={toolCall:Q,result:q,toolUseUuid:W};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,b);return b}catch(W){if($!==this.epoch)return this.makeAbortResult(Q,"Tool execution aborted due to epoch mismatch (discard)");t.error(`[StreamingToolExecutor] 工具执行失败: ${Q.function.name}`,W);let G={success:!1,llmContent:"",error:{type:"execution_error",message:W instanceof Error?W.message:"Unknown error"},metadata:void 0},V={toolCall:Q,result:G,toolUseUuid:null,error:W instanceof Error?W:Error("Unknown error")};if(this.pending.has(Q.id))this.pending.delete(Q.id),this.completed.set(Q.id,V);return V}finally{this.activeAborts.delete(Q.id)}}}var y=p("Agent"),b2=0.1,F2=8192,O2=32768,R0=100,w2=`
580
580
 
581
581
  # Task Execution Strategy
582
582
  When facing complex multi-step tasks:
@@ -585,22 +585,22 @@ When facing complex multi-step tasks:
585
585
  3. If a step fails, diagnose the root cause rather than repeating the same approach.
586
586
  4. When uncertain about file paths or project structure, use Grep/Glob/Read to gather facts first.
587
587
  5. Prefer the smallest change that achieves the goal — avoid unnecessary refactoring.`;function GZ(Q){let Z=Q.trim();if(Z=Z.replace(/,\s*([}\]])/g,"$1"),Z.startsWith("{")&&!Z.endsWith("}"))Z+="}";Z=Z.replace(/,\s*([}\]])/g,"$1");try{let $=JSON.parse(Z);if(typeof $==="object"&&$!==null&&!Array.isArray($))return $;return null}catch{return null}}function VZ(Q){let Z=GZ(Q);if(Z)return Z;try{let $=JSON.parse(Q);return typeof $==="string"?GZ($):null}catch{return null}}function L2(Q){if(typeof Q==="string")return Q;try{return JSON.parse(JSON.stringify(Q))}catch{return String(Q)}}function _2(Q){if(!(Q instanceof Error))return"未知错误";let J=Q.lastError??Q;if(J.responseBody)try{let V=JSON.parse(J.responseBody)?.error?.message;if(V){let Y=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${V}${Y}`}}catch{}let z=Q.message,W=z.match(/Last error:\s*(.+)$/);if(W)return W[1];return z}function N2(Q){if(!(Q instanceof Error))return!1;return["stream not supported","streaming is not available","sse not supported","does not support streaming"].some(($)=>Q.message.toLowerCase().includes($.toLowerCase()))}function v2(Q,Z){if(!Z)return"Tool execution failed (no details).";let $=[`Error: ${Z.message||"Unknown error"}`];if(Z.type==="validation_error")$.push("Hint: Check the tool parameters — a required field may be missing or have the wrong type.");else if(Z.type==="permission_denied")$.push("Hint: This operation requires user approval. Try a different approach or ask the user.");else if(Z.type==="timeout_error")$.push("Hint: The operation timed out. Consider breaking it into smaller steps or increasing timeout.");else if(Z.type==="execution_error"){let J=Z.message??"";if(J.includes("ENOENT")||J.includes("no such file"))$.push("Hint: File or directory not found. Use Glob or Grep to find the correct path first.");else if(J.includes("EACCES")||J.includes("permission"))$.push("Hint: Permission denied. The file may be read-only or owned by another user.");else if(J.includes("not found in file")||J.includes("old_string"))$.push(`Hint: The target text was not found. Use Read to view the current file content, then retry ${Q} with the exact text.`);else if(J.includes("ENOTDIR"))$.push("Hint: A path component is not a directory. Verify the full path with Glob.")}return $.join(`
588
- `)}function I2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function E2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function S2(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*U2(Q,Z,$,J,z){let W="",G="",V,Y,B=new Map;try{let q=Q.chatService.streamChat(Z,$,J),b=0;for await(let X of q){if(b++,J?.aborted)break;if(X.modelFallback){z?.discard(),W="",G="",V=void 0,Y=void 0,B.clear(),b=0,yield{kind:"model_fallback"};continue}if(X.content)W+=X.content,yield{kind:"content_delta",delta:X.content};if(X.reasoningContent)G+=X.reasoningContent,yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.usage)V=X.usage;if(X.toolCalls){for(let L of X.toolCalls)if(E2(B,L),z){let A=L.index??0,F=B.get(A);if(F&&F.id&&F.name)try{let N=VZ(F.arguments);if(N===null)continue;let j={id:F.id,type:"function",function:{name:F.name,arguments:F.arguments}},n=Q.toolExecutor.getRegistry().get(F.name)?.kind;z.addTool(j,N),yield{kind:"tool_start",toolCall:j,toolKind:n}}catch{}}}if(X.finishReason){Y=X.finishReason;break}}if(b===0&&!J?.aborted&&W.length===0&&B.size===0)return y.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:W,reasoningContent:G||void 0,toolCalls:S2(B),usage:V,finishReason:Y}}catch(q){if(N2(q))return y.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw q}}async function*HZ(Q,Z,$,J,z,W,G){if(J===void 0)return y.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let V=kQ(Z.messages,W);if(V)Z.messages=V.messages,y.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let Y=q0(Z.messages),B=!1;if(Y.snippedCount>0)B=!0,y.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${Y.snippedCount} 轮旧工具调用,释放约 ${Y.estimatedTokensFreed} tokens`);let q=Q.chatService.getConfig(),b=q.model,X=q.maxContextTokens??Q.config.maxContextTokens,L=q.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(X*b2),F2),O2),k=X-L,A=Math.floor(k*0.8);if(y.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:X,maxOutputTokens:L,availableForInput:k,threshold:A,shouldCompact:J>=A}),J<A){if(B)Z.messages=Y.messages;return B?"snipped":"none"}y.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let F=B?Y.messages:Z.messages,N=await z0.compact(F,{trigger:"auto",modelName:b,maxContextTokens:X,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:z,activeTask:G});if(Z.messages=N.compactedMessages,N.success)y.debug(`[Loop] [轮次 ${$}] 压缩完成: ${N.preTokens} -> ${N.postTokens} tokens`);else y.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${N.preTokens} -> ${N.postTokens} tokens`);return await I0(Q,Z,N.summary,{trigger:"auto",preTokens:N.preTokens,postTokens:N.postTokens,filesIncluded:N.filesIncluded}),"compacted"}catch(F){if(Q0(F))return y.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(B)Z.messages=Y.messages;return y.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,F),B?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function y2(Q,Z,$,J){let z=J?YZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(z==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:z}}}async function*A2(Q,Z,$,J,z){let W=Date.now(),G=0,V=[],Y=null,B=!1,q=(b,X,L)=>{return B=!0,y2(b,X,W,L)};try{let b=Q.toolExecutor.getRegistry(),X=$.permissionMode,L=b.getFunctionDeclarationsByMode(X);L=BQ(L);let k=Q.applySkillToolRestrictions(L),A=oQ(),F=$Z(),N=z;if(typeof b.getDeferredToolsListing==="function"){let p=b.getDeferredToolsListing();if(p&&N)N=`${N}
588
+ `)}function I2(Q){if(!(Q instanceof Error))return!1;let Z=Q.message.toLowerCase();return Z.includes("prompt_too_long")||Z.includes("prompt is too long")||Z.includes("maximum context length")||Z.includes("request too large")||Q.status===413}function E2(Q,Z){let $=Z,J=$.index??0;if(!Q.has(J))Q.set(J,{id:$.id||"",name:$.function?.name||"",arguments:""});let z=Q.get(J);if($.id&&!z.id)z.id=$.id;if($.function?.name&&!z.name)z.name=$.function.name;if($.function?.arguments)z.arguments+=$.function.arguments}function S2(Q){if(Q.size===0)return;return Array.from(Q.values()).filter((Z)=>Z.id&&Z.name).map((Z)=>({id:Z.id,type:"function",function:{name:Z.name,arguments:Z.arguments}}))}async function*U2(Q,Z,$,J,z){let W="",G="",V,Y,B=new Map;try{let q=Q.chatService.streamChat(Z,$,J),b=0;for await(let X of q){if(b++,J?.aborted)break;if(X.modelFallback){z?.discard(),W="",G="",V=void 0,Y=void 0,B.clear(),b=0,yield{kind:"model_fallback"};continue}if(X.content)W+=X.content,yield{kind:"content_delta",delta:X.content};if(X.reasoningContent)G+=X.reasoningContent,yield{kind:"thinking_delta",delta:X.reasoningContent};if(X.usage)V=X.usage;if(X.toolCalls){for(let L of X.toolCalls)if(E2(B,L),z){let A=L.index??0,F=B.get(A);if(F&&F.id&&F.name)try{let N=VZ(F.arguments);if(N===null)continue;let j={id:F.id,type:"function",function:{name:F.name,arguments:F.arguments}},l=Q.toolExecutor.getRegistry().get(F.name)?.kind;z.addTool(j,N),yield{kind:"tool_start",toolCall:j,toolKind:l}}catch{}}}if(X.finishReason){Y=X.finishReason;break}}if(b===0&&!J?.aborted&&W.length===0&&B.size===0)return y.warn("[Loop] 流式响应返回0个chunk,回退到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};return{content:W,reasoningContent:G||void 0,toolCalls:S2(B),usage:V,finishReason:Y}}catch(q){if(N2(q))return y.warn("[Loop] 流式请求失败,降级到非流式模式"),z?.discard(),{...await Q.chatService.chat(Z,$,J),_nonStreamingFallback:!0};throw q}}async function*HZ(Q,Z,$,J,z,W,G){if(J===void 0)return y.debug(`[Loop] [轮次 ${$}] 压缩检查: 跳过(无历史 usage 数据)`),"none";let V=kQ(Z.messages,W);if(V)Z.messages=V.messages,y.debug(`[Loop] [轮次 ${$}] MicroCompact: 清理 ${V.snippedCount} 轮旧工具结果(缓存已过期)`);let Y=q0(Z.messages),B=!1;if(Y.snippedCount>0)B=!0,y.debug(`[Loop] [轮次 ${$}] Snip 压缩: 移除 ${Y.snippedCount} 轮旧工具调用,释放约 ${Y.estimatedTokensFreed} tokens`);let q=Q.chatService.getConfig(),b=q.model,X=q.maxContextTokens??Q.config.maxContextTokens,L=q.maxOutputTokens??Q.config.maxOutputTokens??Math.min(Math.max(Math.floor(X*b2),F2),O2),k=X-L,A=Math.floor(k*0.8);if(y.debug(`[Loop] [轮次 ${$}] 压缩检查:`,{promptTokens:J,maxContextTokens:X,maxOutputTokens:L,availableForInput:k,threshold:A,shouldCompact:J>=A}),J<A){if(B)Z.messages=Y.messages;return B?"snipped":"none"}y.debug($===0?"[Loop] 触发自动压缩":`[Loop] [轮次 ${$}] 触发循环内自动压缩`),yield{kind:"compaction",phase:"start"};try{let F=B?Y.messages:Z.messages,N=await z0.compact(F,{trigger:"auto",modelName:b,maxContextTokens:X,apiKey:q.apiKey,baseURL:q.baseUrl,actualPreTokens:J,signal:z,activeTask:G});if(Z.messages=N.compactedMessages,N.success)y.debug(`[Loop] [轮次 ${$}] 压缩完成: ${N.preTokens} -> ${N.postTokens} tokens`);else y.warn(`[Loop] [轮次 ${$}] 压缩使用降级策略: ${N.preTokens} -> ${N.postTokens} tokens`);return await I0(Q,Z,N.summary,{trigger:"auto",preTokens:N.preTokens,postTokens:N.postTokens,filesIncluded:N.filesIncluded}),"compacted"}catch(F){if(Q0(F))return y.debug(`[Loop] [轮次 ${$}] 压缩被中止`),"none";if(B)Z.messages=Y.messages;return y.error(`[Loop] [轮次 ${$}] 压缩失败,继续执行`,F),B?"snipped":"none"}finally{yield{kind:"compaction",phase:"end"}}}function y2(Q,Z,$,J){let z=J?YZ(J):"user-cancel";return{success:!1,error:{type:"aborted",message:(z==="interrupt"?void 0:"任务已被用户中止")??"任务已中断"},metadata:{turnsCount:Q,toolCallsCount:Z,duration:Date.now()-$,abortReason:z}}}async function*A2(Q,Z,$,J,z){let W=Date.now(),G=0,V=[],Y=null,B=!1,q=(b,X,L)=>{return B=!0,y2(b,X,W,L)};try{let b=Q.toolExecutor.getRegistry(),X=$.permissionMode,L=b.getFunctionDeclarationsByMode(X);L=BQ(L);let k=Q.applySkillToolRestrictions(L),A=oQ(),F=$Z(),N=z;if(typeof b.getDeferredToolsListing==="function"){let T=b.getDeferredToolsListing();if(T&&N)N=`${N}
589
589
 
590
- ${p}`}if(N)N+=w2;let j=new _0($,N);j.appendUser({role:"user",content:Z}),Y=await u(Q,$,Z);let G0=$.permissionMode==="yolo",n=!!$.subagentInfo,Y0=Q.runtimeOptions.maxTurns!==void 0||J?.maxTurns!==void 0,V0=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(V0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let x=V0===-1?R0:Math.min(V0,R0),m=0,T0,jQ,H0=0,C0=0,p0=0,d0=0,g0=0,m0=new Set,R=new Set($.worktreeActive?["EnterWorktree"]:[]),c=typeof Z==="string"?Z:Z.filter((p)=>p.type==="text").map((p)=>p.text).join(`
591
- `),c0=[c,$.completionRequirements?.trim()].filter(Boolean).join(`
592
- `),F0=v0(c),u0=bQ({budget:Q.currentModelMaxContextTokens,isSubagent:n}),qQ=new GQ,i0=async(p)=>{for(let l of p){j.appendUser({role:"user",content:l.content});let X0=await u(Q,$,l.content,Y);if(X0)Y=X0;let H=typeof l.content==="string"?l.content:l.content.filter((a)=>a.type==="text").map((a)=>a.text).join(`
593
- `);if(H.trim())c=[c,H].join(`
594
- `),c0=[c,$.completionRequirements?.trim()].filter(Boolean).join(`
595
- `),F0=F0||v0(H)}return{messageIds:p.map((l)=>l.id),count:p.length}};try{while(!0){if(J?.signal?.aborted)return q(G,V.length,J.signal);let p=J?.turnSteering?.drain()??[];if(p.length>0)yield{kind:"steering_applied",...await i0(p)};if(j.writeback(),(yield*HZ(Q,$,G,T0,J?.signal,jQ,c))!=="none")j.replaceHistory($.messages);if(G++,qQ.reset(),yield{kind:"turn_start",turn:G,maxTurns:x},J?.signal?.aborted)return q(G-1,V.length,J.signal);if(QZ(G)&&G>1){let v=ZZ(G,A.totalFailures);j.appendControl("user",{role:"user",content:`
590
+ ${T}`}if(N)N+=w2;let j=new _0($,N);j.appendUser({role:"user",content:Z}),Y=await i(Q,$,Z);let G0=$.permissionMode==="yolo",l=!!$.subagentInfo,Y0=Q.runtimeOptions.maxTurns!==void 0||J?.maxTurns!==void 0,V0=Q.runtimeOptions.maxTurns??J?.maxTurns??Q.config.maxTurns??-1;if(V0===0)return{success:!1,error:{type:"chat_disabled",message:"对话功能已被禁用 (maxTurns=0)"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let x=V0===-1?R0:Math.min(V0,R0),c=0,T0,jQ,H0=0,C0=0,p0=0,d0=0,m0=0,g0=new Set,R=new Set($.worktreeActive?["EnterWorktree"]:[]),u=typeof Z==="string"?Z:Z.filter((T)=>T.type==="text").map((T)=>T.text).join(`
591
+ `),c0=[u,$.completionRequirements?.trim()].filter(Boolean).join(`
592
+ `),F0=v0(u),u0=bQ({budget:Q.currentModelMaxContextTokens,isSubagent:l}),qQ=new GQ,i0=async(T)=>{for(let d of T){let X0=await i(Q,$,d.content,Y,{inboxMessageId:d.id});if(!X0)throw Error(`Failed to persist steering message before applying it: ${d.id}`);Y=X0,await J?.turnSteering?.acknowledge([d.id]),j.appendUser({role:"user",content:d.content});let H=typeof d.content==="string"?d.content:d.content.filter((a)=>a.type==="text").map((a)=>a.text).join(`
593
+ `);if(H.trim())u=[u,H].join(`
594
+ `),c0=[u,$.completionRequirements?.trim()].filter(Boolean).join(`
595
+ `),F0=F0||v0(H)}return{messageIds:T.map((d)=>d.id),count:T.length,recovered:T.filter((d)=>d.recovered).length}};try{while(!0){if(J?.signal?.aborted)return q(G,V.length,J.signal);let T=J?.turnSteering?.drain()??[];if(T.length>0)yield{kind:"steering_applied",...await i0(T)};if(j.writeback(),(yield*HZ(Q,$,G,T0,J?.signal,jQ,u))!=="none")j.replaceHistory($.messages);if(G++,qQ.reset(),yield{kind:"turn_start",turn:G,maxTurns:x},J?.signal?.aborted)return q(G-1,V.length,J.signal);if(QZ(G)&&G>1){let v=ZZ(G,A.totalFailures);j.appendControl("user",{role:"user",content:`
596
596
 
597
597
  <system-reminder>
598
598
  ${v}
599
- </system-reminder>`})}let X0=J?.stream!==!1,H,a;try{if(X0)a=new x0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,Y,$.subagentInfo),H=yield*U2(Q,j.toLLMMessages(),k,J?.signal,a);else H=await Q.chatService.chat(j.toLLMMessages(),k,J?.signal)}catch(v){if(I2(v)){y.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),O=await qQ.tryReactiveCompact($.messages,{modelName:K.model,maxContextTokens:K.maxContextTokens??Q.config.maxContextTokens,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:c});if(O.success){$.messages=O.messages,j.replaceHistory($.messages),y.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw v}if(jQ=Date.now(),H.usage){if(H.usage.totalTokens)m+=H.usage.totalTokens;T0=H.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:H.usage.promptTokens??0,outputTokens:H.usage.completionTokens??0,totalTokens:H.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let XZ=H.usage?.completionTokens??0;if(u0=FQ(u0,XZ,H0>0),J?.signal?.aborted)return q(G-1,V.length,J.signal);if(!X0||!!H._nonStreamingFallback){if(H.reasoningContent&&H.reasoningContent.trim())yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.content&&H.content.trim())yield{kind:"content_delta",delta:H.content}}yield{kind:"stream_end"};let n0=s0(H.finishReason,H0,u0);if(n0.action==="recover"){H0++,y.warn(`[Loop] Max output tokens hit (recovery ${H0}/3)`);let v={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};j.appendToHistory(v);let K=await h(Q,$,H.content||"",Y);if(K)Y=K;let O={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};j.appendToHistory(O);let D=await u(Q,$,O.content,Y);if(D)Y=D;continue}if(n0.action==="truncated"||n0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let v=await h(Q,$,H.content||"",Y);if(v)Y=v;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m,outputTruncated:!0}}}if(H.finishReason!=="length")H0=0;if(!H.toolCalls||H.toolCalls.length===0){let v=J?.turnSteering?.drain()??[];if(v.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(v)};continue}if(H.content&&JZ(F,H.content)){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),j.appendControl("user",{role:"user",content:`
599
+ </system-reminder>`})}let X0=J?.stream!==!1,H,a;try{if(X0)a=new x0(Q.toolExecutor,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager},Q.toolExecutor.getRegistry(),Q.executionEngine?.getContextManager(),$.sessionId,Y,$.subagentInfo),H=yield*U2(Q,j.toLLMMessages(),k,J?.signal,a);else H=await Q.chatService.chat(j.toLLMMessages(),k,J?.signal)}catch(v){if(I2(v)){y.warn("[Loop] 检测到 prompt_too_long 错误,尝试反应式压缩");let K=Q.chatService.getConfig(),O=await qQ.tryReactiveCompact($.messages,{modelName:K.model,maxContextTokens:K.maxContextTokens??Q.config.maxContextTokens,apiKey:K.apiKey,baseURL:K.baseUrl,signal:J?.signal,activeTask:u});if(O.success){$.messages=O.messages,j.replaceHistory($.messages),y.info("[Loop] 反应式压缩成功,重试 LLM 调用"),G--;continue}}throw v}if(jQ=Date.now(),H.usage){if(H.usage.totalTokens)c+=H.usage.totalTokens;T0=H.usage.promptTokens,yield{kind:"token_usage",usage:{inputTokens:H.usage.promptTokens??0,outputTokens:H.usage.completionTokens??0,totalTokens:H.usage.totalTokens??0,maxContextTokens:Q.currentModelMaxContextTokens}}}let XZ=H.usage?.completionTokens??0;if(u0=FQ(u0,XZ,H0>0),J?.signal?.aborted)return q(G-1,V.length,J.signal);if(!X0||!!H._nonStreamingFallback){if(H.reasoningContent&&H.reasoningContent.trim())yield{kind:"thinking_delta",delta:H.reasoningContent};if(H.content&&H.content.trim())yield{kind:"content_delta",delta:H.content}}yield{kind:"stream_end"};let n0=s0(H.finishReason,H0,u0);if(n0.action==="recover"){H0++,y.warn(`[Loop] Max output tokens hit (recovery ${H0}/3)`);let v={role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls};j.appendToHistory(v);let K=await h(Q,$,H.content||"",Y);if(K)Y=K;let O={role:"user",content:"Output token limit hit. Resume directly — no apology, no recap. "+"Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces."};j.appendToHistory(O);let D=await i(Q,$,O.content,Y);if(D)Y=D;continue}if(n0.action==="truncated"||n0.action==="budget_stop"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});let v=await h(Q,$,H.content||"",Y);if(v)Y=v;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c,outputTruncated:!0}}}if(H.finishReason!=="length")H0=0;if(!H.toolCalls||H.toolCalls.length===0){let v=J?.turnSteering?.drain()??[];if(v.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(v)};continue}if(H.content&&JZ(F,H.content)){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent}),j.appendControl("user",{role:"user",content:`
600
600
 
601
601
  <system-reminder>
602
602
  ${zZ()}
603
- </system-reminder>`});continue}let K=t0(H.content,C0,!1);if(K.action==="retry"){C0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let T={role:"user",content:K.prompt};j.appendControl("user",T);let f=await u(Q,$,T.content,Y);if(f)Y=f;continue}C0=0;let O=NQ(c,R,p0);if(O.action==="retry"){p0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let T={role:"user",content:O.prompt};j.appendControl("user",T);let f=await u(Q,$,T.content,Y);if(f)Y=f;continue}if(O.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:O.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m}}}p0=0;let D=vQ(c,R,g0);if(D.action==="retry"){g0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let T={role:"user",content:D.prompt};j.appendControl("user",T);let f=await u(Q,$,T.content,Y);if(f)Y=f;continue}if(D.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:D.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m}}}g0=0;let d=e0(c0,m0,d0);if(d.action==="retry"){d0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let T={role:"user",content:d.prompt};j.appendControl("user",T);let f=await u(Q,$,T.content,Y);if(f)Y=f;continue}if(d.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:d.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m}}}d0=0;let S=await QQ({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(S.action==="continue"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let f={role:"user",content:S.reason?`
603
+ </system-reminder>`});continue}let K=t0(H.content,C0,!1);if(K.action==="retry"){C0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:K.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}C0=0;let O=NQ(u,R,p0);if(O.action==="retry"){p0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:O.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(O.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"delegation_protocol_failed",message:O.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}p0=0;let D=vQ(u,R,m0);if(D.action==="retry"){m0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:D.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(D.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"worktree_protocol_failed",message:D.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}m0=0;let m=e0(c0,g0,d0);if(m.action==="retry"){d0++,j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let C={role:"user",content:m.prompt};j.appendControl("user",C);let f=await i(Q,$,C.content,Y);if(f)Y=f;continue}if(m.action==="fail"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;return{success:!1,error:{type:"verification_failed",message:m.message},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}d0=0;let S=await QQ({sessionId:$.sessionId,permissionMode:$.permissionMode,reason:H.content,abortSignal:J?.signal});if(S.action==="continue"){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;let f={role:"user",content:S.reason?`
604
604
 
605
605
  <system-reminder>
606
606
  ${S.reason}
@@ -608,8 +608,8 @@ ${S.reason}
608
608
 
609
609
  <system-reminder>
610
610
  Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.
611
- </system-reminder>`};j.appendControl("user",f);let K0=await u(Q,$,f.content,Y);if(K0)Y=K0;continue}let r=J?.turnSteering?.drainOrSeal();if(r&&r.messages.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(r.messages)};continue}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let M=await h(Q,$,H.content||"",Y);if(M)Y=M;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:A.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let v=await h(Q,$,H.content||"",Y);if(v)Y=v}if(J?.signal?.aborted)return q(G,V.length,J.signal);let l0=H.toolCalls.filter((v)=>v.type==="function"),O0;if(a?.hasTools()){y.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${l0.length} 个工具结果`),O0=[];for await(let v of a.getRemainingResults())O0.push(v)}else{for(let K of l0){let D=b.get(K.function.name)?.kind;yield{kind:"tool_start",toolCall:K,toolKind:D}}let v=async(K)=>{try{let O=VZ(K.function.arguments);if(O===null)return{toolCall:K,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${K.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(K.function.name==="Task"&&(typeof O.subagent_session_id!=="string"||O.subagent_session_id.length===0))O.subagent_session_id=typeof O.resume==="string"&&O.resume.length>0?O.resume:D2();let D=null;if(D=await $Q(Q,$,K.function.name,O,Y),K.function.name==="ExitWorktree"&&R.has("EnterWorktree")&&!R.has("ExitWorktree")&&e0(c0,m0,0).action!=="none"){let r="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:K,result:{success:!1,llmContent:r,error:{type:"validation_error",message:r},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:D}}let S=await Q.toolExecutor.execute(K.function.name,O,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:K,result:S,toolUseUuid:D}}catch(O){return y.error(`Tool execution failed for ${K.function.name}:`,O),{toolCall:K,result:{success:!1,llmContent:"",error:{type:"execution_error",message:O instanceof Error?O.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:O instanceof Error?O:Error("Unknown error")}}};O0=await Promise.all(l0.map(v))}let KZ=new VQ;for(let{toolCall:v,result:K,toolUseUuid:O}of O0){let D=v;if(V.push(K),K.metadata?.abortedBeforeLaunch)return q(G,V.length,J?.signal);yield{kind:"tool_result",toolCall:D,result:K};{let M=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,T=((w0)=>w0==="running"||w0==="completed"||w0==="failed"||w0==="cancelled")(M?.subagentStatus)?M.subagentStatus:"completed",f=M&&typeof M.subagentSessionId==="string"?{subagentSessionId:M.subagentSessionId,subagentType:typeof M.subagentType==="string"?M.subagentType:D.function.name,subagentStatus:T,subagentSummary:typeof M.subagentSummary==="string"?M.subagentSummary:void 0}:void 0,K0=await JQ(Q,$,D.id,D.function.name,K.success?L2(K.llmContent):null,O,K.success?void 0:K.error?.message,f);if(K0)Y=K0}let d=await zQ(D,K,Q,$);if(d)yield d;if(K.success){if(sQ(A,D.function.name),D.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")R.add("EnterWorktree"),R.delete("ExitWorktree");else if(D.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&R.has("EnterWorktree"))R.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(D.function.name))R.add(D.function.name);if(D.function.name==="Task"&&K.metadata?.isolation==="worktree")R.add("TaskWorktree");_Q(m0,D.function.name,K)}else tQ(A,D.function.name);let S=K.success?K.llmContent||"":v2(D.function.name,K.error);if(!K.success){let M=eQ(A,D.function.name);if(M&&typeof S==="string")S=`${S}
611
+ </system-reminder>`};j.appendControl("user",f);let K0=await i(Q,$,f.content,Y);if(K0)Y=K0;continue}let r=J?.turnSteering?.drainOrSeal();if(r&&r.messages.length>0){j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let _=await h(Q,$,H.content||"",Y);if(_)Y=_;yield{kind:"steering_applied",...await i0(r.messages)};continue}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent});let M=await h(Q,$,H.content||"",Y);if(M)Y=M;return{success:!0,finalMessage:H.content,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c,toolSuccessRate:V.length>0?V.filter((_)=>_.success).length/V.length:void 0,totalToolFailures:A.totalFailures||void 0}}}j.appendAssistant({role:"assistant",content:H.content||"",reasoningContent:H.reasoningContent,tool_calls:H.toolCalls});{let v=await h(Q,$,H.content||"",Y);if(v)Y=v}if(J?.signal?.aborted)return q(G,V.length,J.signal);let l0=H.toolCalls.filter((v)=>v.type==="function"),O0;if(a?.hasTools()){y.debug(`[Loop] 使用 StreamingToolExecutor 收集 ${l0.length} 个工具结果`),O0=[];for await(let v of a.getRemainingResults())O0.push(v)}else{for(let K of l0){let D=b.get(K.function.name)?.kind;yield{kind:"tool_start",toolCall:K,toolKind:D}}let v=async(K)=>{try{let O=VZ(K.function.arguments);if(O===null)return{toolCall:K,result:{success:!1,llmContent:"",error:{type:"validation_error",message:`Invalid JSON object in tool arguments. Raw: ${K.function.arguments.slice(0,200)}`},metadata:void 0},toolUseUuid:null};if(K.function.name==="Task"&&(typeof O.subagent_session_id!=="string"||O.subagent_session_id.length===0))O.subagent_session_id=typeof O.resume==="string"&&O.resume.length>0?O.resume:D2();let D=null;if(D=await $Q(Q,$,K.function.name,O,Y),K.function.name==="ExitWorktree"&&R.has("EnterWorktree")&&!R.has("ExitWorktree")&&e0(c0,g0,0).action!=="none"){let r="Run the requested verification before ExitWorktree. The worktree remains active so Bash can run in isolation.";return{toolCall:K,result:{success:!1,llmContent:r,error:{type:"validation_error",message:r},metadata:{summary:"Blocked ExitWorktree until verification succeeds"}},toolUseUuid:D}}let S=await Q.toolExecutor.execute(K.function.name,O,{sessionId:$.sessionId,userId:$.userId||"default",workspaceRoot:$.workspaceRoot||g(),worktreeIsolationRequired:F0,worktreeActive:R.has("EnterWorktree")&&!R.has("ExitWorktree"),signal:J?.signal,confirmationHandler:$.confirmationHandler,permissionMode:$.permissionMode,toolRegistry:b,deferredToolManager:b.deferredToolManager});return{toolCall:K,result:S,toolUseUuid:D}}catch(O){return y.error(`Tool execution failed for ${K.function.name}:`,O),{toolCall:K,result:{success:!1,llmContent:"",error:{type:"execution_error",message:O instanceof Error?O.message:"Unknown error"},metadata:void 0},toolUseUuid:null,error:O instanceof Error?O:Error("Unknown error")}}};O0=await Promise.all(l0.map(v))}let KZ=new VQ;for(let{toolCall:v,result:K,toolUseUuid:O}of O0){let D=v;if(V.push(K),K.metadata?.abortedBeforeLaunch)return q(G,V.length,J?.signal);yield{kind:"tool_result",toolCall:D,result:K};{let M=K.metadata&&typeof K.metadata==="object"?K.metadata:void 0,C=((w0)=>w0==="running"||w0==="completed"||w0==="failed"||w0==="cancelled")(M?.subagentStatus)?M.subagentStatus:"completed",f=M&&typeof M.subagentSessionId==="string"?{subagentSessionId:M.subagentSessionId,subagentType:typeof M.subagentType==="string"?M.subagentType:D.function.name,subagentStatus:C,subagentSummary:typeof M.subagentSummary==="string"?M.subagentSummary:void 0}:void 0,K0=await JQ(Q,$,D.id,D.function.name,K.success?L2(K.llmContent):null,O,K.success?void 0:K.error?.message,f);if(K0)Y=K0}let m=await zQ(D,K,Q,$);if(m)yield m;if(K.success){if(sQ(A,D.function.name),D.function.name==="EnterWorktree"&&K.metadata?.workspaceTransition==="enter")R.add("EnterWorktree"),R.delete("ExitWorktree");else if(D.function.name==="ExitWorktree"&&K.metadata?.workspaceTransition==="exit"&&R.has("EnterWorktree"))R.add("ExitWorktree");else if(!["EnterWorktree","ExitWorktree"].includes(D.function.name))R.add(D.function.name);if(D.function.name==="Task"&&K.metadata?.isolation==="worktree")R.add("TaskWorktree");_Q(g0,D.function.name,K)}else tQ(A,D.function.name);let S=K.success?K.llmContent||"":v2(D.function.name,K.error);if(!K.success){let M=eQ(A,D.function.name);if(M&&typeof S==="string")S=`${S}
612
612
 
613
- ${M}`}if(typeof S==="object"&&S!==null)S=JSON.stringify(S,null,2);if(typeof S==="string")S=CQ(S,D.function.name,{messageBudget:KZ});let r=typeof S==="string"?S:JSON.stringify(S);if(j.appendToolResult({role:"tool",tool_call_id:D.id,name:D.function.name,content:r}),K.metadata?.shouldExitLoop){let M=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:M,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return q(G,V.length,J.signal);let a0=G>=R0,BZ=G>=x&&(Y0||!G0||n);if(a0||BZ){let v=a0?R0:x;if(y.info(`Warning: 达到轮次上限 ${v} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:G});if(K?.continue){j.writeback();try{let O=Q.chatService.getConfig(),D=await z0.compact($.messages,{trigger:"auto",modelName:O.model,maxContextTokens:O.maxContextTokens??Q.config.maxContextTokens,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:T0,signal:J?.signal,activeTask:c});$.messages=D.compactedMessages,j.replaceHistory($.messages);let d={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
613
+ ${M}`}if(typeof S==="object"&&S!==null)S=JSON.stringify(S,null,2);if(typeof S==="string")S=CQ(S,D.function.name,{messageBudget:KZ});let r=typeof S==="string"?S:JSON.stringify(S);if(j.appendToolResult({role:"tool",tool_call_id:D.id,name:D.function.name,content:r}),K.metadata?.shouldExitLoop){let M=typeof K.llmContent==="string"?K.llmContent:"循环已退出";return{success:K.success,finalMessage:M,metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,shouldExitLoop:!0,targetMode:K.metadata?.targetMode,planContent:typeof K.metadata?.planContent==="string"?K.metadata.planContent:void 0}}}}if(J?.signal?.aborted)return q(G,V.length,J.signal);let a0=G>=R0,BZ=G>=x&&(Y0||!G0||l);if(a0||BZ){let v=a0?R0:x;if(y.info(`Warning: 达到轮次上限 ${v} 轮`),J?.onTurnLimitReached){let K=await J.onTurnLimitReached({turnsCount:G});if(K?.continue){j.writeback();try{let O=Q.chatService.getConfig(),D=await z0.compact($.messages,{trigger:"auto",modelName:O.model,maxContextTokens:O.maxContextTokens??Q.config.maxContextTokens,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:T0,signal:J?.signal,activeTask:u});$.messages=D.compactedMessages,j.replaceHistory($.messages);let m={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
614
614
 
615
- Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};j.appendToHistory(d),await I0(Q,$,D.summary,{trigger:"auto",preTokens:D.preTokens,postTokens:D.postTokens,filesIncluded:D.filesIncluded})}catch(O){y.error("[Loop] 压缩失败,使用降级策略:",O);let d=j.getHistory().slice(-80);j.replaceHistory(d)}G=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m}}}return{success:!1,error:{type:"max_turns_exceeded",message:n?`子代理已达到轮次上限 (${v} 轮)。`:`已达到${a0?"安全":"显式"}轮次上限 (${v} 轮)。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:m}}}}}finally{j.writeback()}}catch(b){if(Q0(b))return q(G,V.length,J?.signal);let X=_2(b);return y.error(`API 调用失败: ${X}`),{success:!1,error:{type:"api_error",message:X,details:b},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(B)$.messages.push({role:"system",content:ZQ}),await IQ(Q,$,Y)}}export{WQ as Ma,mQ as Na,nQ as Oa,k0 as Pa,V2 as Qa,o as Ra,s0 as Sa,t0 as Ta,_Q as Ua,QQ as Va,L0 as Wa,_0 as Xa,jZ as Ya,u as Za,h as _a,$Q as $a,JQ as ab,I0 as bb,EQ as cb,SQ as db,UQ as eb,zQ as fb,j0 as gb,z0 as hb,x0 as ib,HZ as jb,A2 as kb};
615
+ Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};j.appendToHistory(m),await I0(Q,$,D.summary,{trigger:"auto",preTokens:D.preTokens,postTokens:D.postTokens,filesIncluded:D.filesIncluded})}catch(O){y.error("[Loop] 压缩失败,使用降级策略:",O);let m=j.getHistory().slice(-80);j.replaceHistory(m)}G=0;continue}return{success:!0,finalMessage:K?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}return{success:!1,error:{type:"max_turns_exceeded",message:l?`子代理已达到轮次上限 (${v} 轮)。`:`已达到${a0?"安全":"显式"}轮次上限 (${v} 轮)。`},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W,tokensUsed:c}}}}}finally{j.writeback()}}catch(b){if(Q0(b))return q(G,V.length,J?.signal);let X=_2(b);return y.error(`API 调用失败: ${X}`),{success:!1,error:{type:"api_error",message:X,details:b},metadata:{turnsCount:G,toolCallsCount:V.length,duration:Date.now()-W}}}finally{if(B)$.messages.push({role:"system",content:ZQ}),await IQ(Q,$,Y)}}export{WQ as Ja,gQ as Ka,nQ as La,k0 as Ma,V2 as Na,o as Oa,s0 as Pa,t0 as Qa,_Q as Ra,QQ as Sa,L0 as Ta,_0 as Ua,jZ as Va,i as Wa,h as Xa,$Q as Ya,JQ as Za,I0 as _a,EQ as $a,SQ as ab,UQ as bb,zQ as cb,j0 as db,z0 as eb,x0 as fb,HZ as gb,A2 as hb};
@@ -1,2 +1,2 @@
1
- import{Pb as y}from"./chunk-cfrbsnfb.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{Nb as y}from"./chunk-kfg3vx5z.js";import*as j from"fs/promises";import*as $ from"path";import b from"semver";import{fileURLToPath as N}from"url";import{ProxyAgent as G,fetch as H}from"undici";function T(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function R(){let q=T();if(q)try{return new G(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function K(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=R(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),w=()=>X.abort();Q?.addEventListener("abort",w);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await H(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",w)}}var D="blade-code",f="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",M=$.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),S=$.join(M,"version-cache.json"),k=3600000,L=`https://registry.npmjs.org/${D}/latest`;async function x(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let q=N(import.meta.url),z=$.dirname(q),W=[$.join(z,"..","..","package.json"),$.join(z,"..","package.json")];for(let Q of W)try{let B=await j.readFile(Q,"utf-8"),J=JSON.parse(B);if(J.name===D&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function I(){try{let q=await j.readFile(S,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<k)return z;return{...z,checkedAt:0}}catch{return null}}async function O(q){try{await j.mkdir(M,{recursive:!0,mode:493}),await j.writeFile(S,JSON.stringify(q,null,2))}catch{}}async function P(){try{let q=await K(L,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function v(q=!1){let z=await x(),W=f;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await I(),B=Q?.skipUntilVersion,J=null;if(!q&&Q&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await P(),J)await O({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});if(!J)return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};let X=b.gt(J,z),Y=X;if(X&&B)Y=b.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await I();await O({latestVersion:z?.latestVersion||q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${D}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function d(){try{let q=await v();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{v as a,u as b,g as c,C as d,d as e};
@@ -1,4 +1,4 @@
1
- import{p as A,q as E,r as N,s as f}from"./chunk-67zx7ymj.js";import{t as D}from"./chunk-qw2wy4jc.js";import{v as L,w as _,x}from"./chunk-m2k4h3bs.js";import{y as B}from"./chunk-cqrkeq20.js";import{K as $,Q as b}from"./chunk-t6y57501.js";import"./chunk-z0qxaky4.js";import"./chunk-t3pyakvc.js";import"./chunk-22gxb9qs.js";import"./chunk-wc2xb6ge.js";import"./chunk-b6mxeey0.js";import"./chunk-k18bq4mn.js";import{Ya as Z}from"./chunk-zcreym5g.js";import"./chunk-wcm0nc84.js";import"./chunk-p6d7k1x6.js";import{vb as Y,wb as T}from"./chunk-cadngkwr.js";import"./chunk-m4a480k7.js";import"./chunk-4hk7wfat.js";import"./chunk-cfrbsnfb.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
1
+ import{p as A,q as E,r as N,s as f}from"./chunk-87gff8b7.js";import{t as D}from"./chunk-vw3f4mbt.js";import{v as L,w as _,x}from"./chunk-cw125vv3.js";import{y as B}from"./chunk-k4behavv.js";import{H as $,N as b}from"./chunk-wp67n9q7.js";import"./chunk-e21htmg4.js";import"./chunk-y50fy1gq.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-06awrjgg.js";import{Va as Z}from"./chunk-gb0x14v5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as Y,tb as T}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import h from"yargs";import{hideBin as R}from"yargs/helpers";var w=new Set(Object.values(Y));function X(k){if(k&&w.has(k))return k;return}function M(k){return k.command("* [message]","Print response and exit (useful for pipes)",(F)=>F.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(F)=>{if(!F.p)return;let q=await O(F);process.exit(q)})}async function O(k,F=process){let q;try{await A();let J=await E({message:k.message,_:k._,defaultMessage:"Hello"}),G=await N(J);if(G.mode==="output"){if(G.content)F.stdout.write(`${G.content}
2
2
  `);return G.exitCode??0}let Q=G.content,{sessionId:K,messages:U}=await f({sessionId:k.sessionId,continue:k.continue,resume:k.resume,forkSession:k.forkSession,fallbackSessionPrefix:"print"});q=await $.create({sessionId:K,workspaceRoot:T(),modelId:k.model,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig,agents:k.agents?B(k.agents):void 0});let V=await b.createWithRuntime(q,{sessionId:K,systemPrompt:k.systemPrompt,appendSystemPrompt:k.appendSystemPrompt,maxTurns:k.maxTurns,modelId:k.model,permissionMode:X(k.permissionMode),toolWhitelist:k.allowedTools,toolBlacklist:k.disallowedTools,mcpConfig:k.mcpConfig,strictMcpConfig:k.strictMcpConfig}),H=(await Z(V.chatStream(Q,{messages:[...U],userId:"cli-user",sessionId:K,workspaceRoot:T(),permissionMode:X(k.permissionMode)}))).finalMessage||"";if(k.outputFormat==="json")F.stdout.write(`${JSON.stringify({response:H,input:Q,model:k.model,timestamp:new Date().toISOString()},null,2)}
3
3
  `);else if(k.outputFormat==="stream-json")F.stdout.write(`${JSON.stringify({type:"response",content:H})}
4
4
  `);else F.stdout.write(`${H}