blade-code 0.10.20 → 0.10.21

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 (80) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-bv7e8221.js → chunk-033vmd74.js} +1 -1
  3. package/dist/{chunk-y72p0x68.js → chunk-0et4h9p3.js} +1 -1
  4. package/dist/chunk-0qayfsc9.js +2 -0
  5. package/dist/{chunk-j9vqys2g.js → chunk-17jpjcvb.js} +2 -2
  6. package/dist/{chunk-q6ev6t06.js → chunk-1p5822w7.js} +1 -1
  7. package/dist/{chunk-qkrssft1.js → chunk-1y52h772.js} +1 -1
  8. package/dist/{chunk-xpt6cdn8.js → chunk-2wp6h1p8.js} +1 -1
  9. package/dist/{chunk-d9k98jy2.js → chunk-2ygqbd1z.js} +1 -1
  10. package/dist/chunk-303cba4k.js +1 -0
  11. package/dist/{chunk-eakfkjk4.js → chunk-4tkn9bky.js} +1 -1
  12. package/dist/{chunk-wmttq8eq.js → chunk-4v8nxcxp.js} +1 -1
  13. package/dist/{chunk-f6a1grte.js → chunk-4ypy5bk8.js} +1 -1
  14. package/dist/chunk-51vnya3v.js +1 -0
  15. package/dist/{chunk-6pa6c2n0.js → chunk-5hhfv1w1.js} +1 -1
  16. package/dist/{chunk-k3nkcaap.js → chunk-65kbckpt.js} +1 -1
  17. package/dist/{chunk-axe8621t.js → chunk-6f3rp67k.js} +1 -1
  18. package/dist/chunk-6v4dwkw7.js +1 -0
  19. package/dist/{chunk-htarfekt.js → chunk-72ztan96.js} +2 -2
  20. package/dist/{chunk-83jkb44s.js → chunk-73jh6fz9.js} +2 -2
  21. package/dist/{chunk-6207mbmr.js → chunk-77z6x1zb.js} +2 -2
  22. package/dist/{chunk-zt5wq0qj.js → chunk-7mpa4esh.js} +1 -1
  23. package/dist/chunk-7p4qvftj.js +1 -0
  24. package/dist/chunk-9snsxf18.js +1 -0
  25. package/dist/{chunk-yqfqj7mh.js → chunk-9wqr1sbq.js} +1 -1
  26. package/dist/{chunk-ehgfwwqk.js → chunk-a1ztrwjb.js} +1 -1
  27. package/dist/{chunk-kbpc97n3.js → chunk-afhdpen9.js} +1 -1
  28. package/dist/{chunk-y2g5a5bp.js → chunk-ah8hky46.js} +1 -1
  29. package/dist/{chunk-kf56q9zs.js → chunk-bdn1tkyz.js} +1 -1
  30. package/dist/{chunk-nqd6t5t7.js → chunk-bjf7ecgy.js} +1 -1
  31. package/dist/chunk-c23c1vn6.js +1 -0
  32. package/dist/chunk-cb0rb9ss.js +1 -0
  33. package/dist/{chunk-w6azkwgq.js → chunk-cysaxtfp.js} +1 -1
  34. package/dist/{chunk-prgh321y.js → chunk-dbb20rxh.js} +1 -1
  35. package/dist/{chunk-t3b689pm.js → chunk-e9xv0yyr.js} +1 -1
  36. package/dist/{chunk-619rxqh6.js → chunk-edphxwj1.js} +1 -1
  37. package/dist/chunk-efkqwhff.js +1 -0
  38. package/dist/{chunk-6g5k5de1.js → chunk-fasxw5bb.js} +1 -1
  39. package/dist/{chunk-0y0wbjyf.js → chunk-g7p165yz.js} +1 -1
  40. package/dist/{chunk-1n60pgsq.js → chunk-jahf977w.js} +2 -2
  41. package/dist/{chunk-fvj1mzgs.js → chunk-jdsr22s2.js} +1 -1
  42. package/dist/{chunk-zdkc4kj1.js → chunk-jhzk287k.js} +1 -1
  43. package/dist/chunk-jyeas4p9.js +2 -0
  44. package/dist/{chunk-wt7gy9bm.js → chunk-k106g2p6.js} +1 -1
  45. package/dist/{chunk-xfr5z6pz.js → chunk-kfqj54ax.js} +1 -1
  46. package/dist/{chunk-yvf4nmds.js → chunk-kmeccj99.js} +2 -2
  47. package/dist/{chunk-qt114yth.js → chunk-ktbe458z.js} +1 -1
  48. package/dist/{chunk-e37k44j1.js → chunk-mvc0tad6.js} +2 -2
  49. package/dist/{chunk-z2fn2yg8.js → chunk-ns5015tn.js} +1 -1
  50. package/dist/{chunk-7pkscxbb.js → chunk-pmw9pn3v.js} +1 -1
  51. package/dist/{chunk-zzkdr84r.js → chunk-q4fjec99.js} +1 -1
  52. package/dist/{chunk-96h588rd.js → chunk-r561wfcz.js} +1 -1
  53. package/dist/chunk-r73fanrm.js +1 -0
  54. package/dist/{chunk-zqf8043h.js → chunk-ryhk5qmv.js} +339 -318
  55. package/dist/{chunk-xet98pc1.js → chunk-sj2w24fe.js} +1 -1
  56. package/dist/chunk-smh39yy2.js +1 -0
  57. package/dist/{chunk-8rzwyknk.js → chunk-vprpk6q1.js} +1 -1
  58. package/dist/{chunk-h41b8965.js → chunk-vzgy95tp.js} +1 -1
  59. package/dist/{chunk-jpwfq49n.js → chunk-w5m418w5.js} +2 -2
  60. package/dist/chunk-w9tnd1q2.js +1 -0
  61. package/dist/{chunk-fa6313dv.js → chunk-wc1ee4tc.js} +1 -1
  62. package/dist/{chunk-bffw1t7e.js → chunk-whftbz4b.js} +1 -1
  63. package/dist/{chunk-fbnetqrz.js → chunk-wxqkpvqw.js} +2 -2
  64. package/dist/{chunk-entmz5b1.js → chunk-y68sxcgk.js} +1 -1
  65. package/dist/chunk-zz9rax72.js +1 -0
  66. package/package.json +1 -1
  67. package/dist/chunk-3qhqbj09.js +0 -2
  68. package/dist/chunk-4544fy5s.js +0 -1
  69. package/dist/chunk-4svjvyyd.js +0 -1
  70. package/dist/chunk-7wx9vt15.js +0 -1
  71. package/dist/chunk-87vsgqvy.js +0 -1
  72. package/dist/chunk-88639hse.js +0 -1
  73. package/dist/chunk-8mp5qg8q.js +0 -1
  74. package/dist/chunk-a5ncqsat.js +0 -1
  75. package/dist/chunk-bcxbrbvd.js +0 -1
  76. package/dist/chunk-eq5kb8m9.js +0 -1
  77. package/dist/chunk-h1b6wehr.js +0 -1
  78. package/dist/chunk-n00q74bt.js +0 -1
  79. package/dist/chunk-q3c07kb4.js +0 -2
  80. package/dist/chunk-zvdervx9.js +0 -1
@@ -1,4 +1,4 @@
1
- import{wb as I5}from"./chunk-095x2ykj.js";import{Ab as Z5,Bb as J5,Cb as c$,Db as u$,Kb as d1,Tb as L2,Vb as J1,Wb as i0,Xb as W1,bc as P0,xb as d2}from"./chunk-q6ev6t06.js";import{cc as V2,fc as o1,gc as q2}from"./chunk-8rzwyknk.js";import{hd as v5}from"./chunk-yz2bsntj.js";import{id as R5,jd as f2,kd as S5,ld as h5,md as Z1,od as m1}from"./chunk-xet98pc1.js";import{Sd as v2,Td as b2,Wd as C5}from"./chunk-r1jxbx1h.js";import{de as t2}from"./chunk-j9vqys2g.js";import{ie as w2}from"./chunk-6207mbmr.js";import{Ze as M5}from"./chunk-y2g5a5bp.js";import{mf as i}from"./chunk-prgh321y.js";import{zf as $5}from"./chunk-fbnetqrz.js";import{Hf as Z0,Jf as M1,Kf as X2,Lf as l0,Nf as t1,Pf as e1}from"./chunk-yvf4nmds.js";import{Qf as K7}from"./chunk-6g5k5de1.js";function a2($){return $.role==="system"&&Array.isArray($.content)}function o2($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class R0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let J=$.messages.find(a2);if(this._contextualSystemMessages=$.messages.filter(o2),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!a2(W)&&!o2(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!o2($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(a2);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!a2(Z)&&!o2(Z))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(o2),this._history=$.filter((Z)=>!a2(Z)&&!o2(Z)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function G1($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function L1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function F1($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import m2 from"node:path";var o5=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),a5=/^(LD_.+|DYLD_.+|PATH)$/,U1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function U0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(!o5.has(X))break;Z=K}return Z}function q8($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(a5.test(X))break;Z=K}return Z}var s5=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function A$($){let Z=$,J=!0;while(J){J=!1;for(let W of s5){let K=Z.match(W);if(K){Z=Z.slice(K[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function h0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){J+=z,Y=!0;continue}if(z==="'"&&!K){W=!W,J+=z;continue}if(z==='"'&&!W){K=!K,J+=z;continue}if(W||K){J+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(z==="&")return null;if(z===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=z}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function O1($){let Z=!1,J=!1,W=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(J)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function O0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;J+=z,Y=!1}continue}if(z==="'"&&!K){W=!W;continue}if(z==='"'&&!W){K=!K;continue}if(!W&&!K&&/[ \t]/.test(z)){if(J)Z.push(J),J="";continue}J+=z}if(J)Z.push(J);return Z}var t5=new Set(["npm","pnpm","yarn","bun"]),y1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),e5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function $6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function J6($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let K=O0(W[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=m2.isAbsolute(Y)?m2.resolve(Y):m2.resolve(J,Y);if(!d2.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function s2($,Z){let J=U0(Z6($)),W=h0(J);if(!W||O1(J)||/[\r\n]/.test(J))return!1;let K=W.length===1?W[0]:J6(J,W,Z);if(!K)return!1;let Y=O0(K);if(Y.length===0||Y.some((H)=>[...e5].some((V)=>H===V||H.startsWith(`${V}=`))))return!1;let[X,z,Q]=Y;if(t5.has(X??""))return $6(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&y1.has(z??""))return!0;if(y1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function O8($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!m2.isAbsolute($);let J=m2.isAbsolute($)?m2.resolve($):m2.resolve(Z,$);return d2.isWithinWorkspace(J,Z)}var x$=w2("Agent"),W6=3;function k$($,Z,J){if($!=="length")return{action:"none"};if(Z>=W6)return{action:"truncated"};if(G1(J)==="stop")return x$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var K6=[/:\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],Y6=/```[\s\S]{50,}```/,P1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",X6=2;function T$($,Z,J=!0){if(!$||Z>=X6)return{action:"none"};if(!J&&Y6.test($))return{action:"retry",prompt:P1};let W=$.slice(-200),K=W.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(K6.some((X)=>X.test(W)))return{action:"retry",prompt:P1};return{action:"none"}}var z6=[/\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}(?:测试|单测|集成测试|检查|构建)/],E1={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},Q6={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},H6="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.",B6="Required verification did not run successfully before the retry limit.",V6=3;function N1($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&s2(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=J.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&s2(Y,W))$.add(Y)}function f$($,Z,J){if(!$||!z6.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(E1).filter((Q)=>E1[Q].test($)),K=[...Z],Y=W.filter((Q)=>!K.some((H)=>Q6[Q].test(H)));if(W.length>0?Y.length===0:K.some((Q)=>s2(Q)))return{action:"none"};if(J>=V6)return{action:"fail",message:B6};let z=W.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${H6}${z}`}}var D6=[/\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|子代理|子智能体)/],_1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function S1($){return typeof $==="string"&&_1.some((Z)=>Z.test($))}var j6=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],w6=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function q6($){if(typeof $!=="string")return;if(w6.some((Z)=>Z.test($)))return"multiple-allowed";return j6.some((Z)=>Z.test($))?"required":void 0}function I0($){for(let Z of $){let J=q6(Z);if(J!==void 0)return J==="required"}return!1}var G6="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.",L6="Required delegation did not complete before the retry limit.",F6=3;function A1($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=I0(W),Y=!1;if(!K)for(let X of W){if(_1.some((z)=>z.test(X)))break;if(D6.some((z)=>z.test(X))){Y=!0;break}}if(W.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(J>=F6)return{action:"fail",message:L6};return{action:"retry",prompt:G6}}var U6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],O6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],y6=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function x1($){return y6.reduce((Z,J)=>Z.replace(J," "),$)}function p0($){if(typeof $!=="string")return!1;let Z=x1($);return U6.some((J)=>J.test(Z))}var P6="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.",E6="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.",b6="Required worktree lifecycle did not complete before the retry limit.",N6=3;function k1($,Z,J){if(!$)return{action:"none"};let W=x1($);if(!p0(W))return{action:"none"};let K=O6.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(J>=N6)return{action:"fail",message:b6};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?P6:E6}}var b1=30000;async function M$($){try{let J=t2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,K=new Promise((Y)=>{W=setTimeout(()=>Y("timeout"),b1)});try{let Y=await Promise.race([J,K]);if(Y==="timeout")return x$.warn(`[Loop] Stop hook 超时 (${b1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return x$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function _6($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function A6($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function x6($){let Z=$;for(let Q of S6)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=W&&W[1].length>=6?W[1]:J;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function T1($){return x6(A6($))}import{EventEmitter as k6}from"events";import f1 from"node:path";function v$($){if(M1($.sessionId),!f1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f1.resolve($.projectPath)}}function f8($){let Z=v$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class e2 extends k6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!e2.instance)e2.instance=new e2;return e2.instance}publish($,Z,J,W){let K=v$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var y0=e2.getInstance();var x2=w2("Agent"),g0=new Set;async function T6($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g0.has(J))return;if(g0.size>=5000)g0.clear();g0.add(J);try{let W=$.workspaceRoot,K=await P0.findSessionMetadata(J,W);if(!K)return;if(K.title&&K.title.trim())return;let Y=T1(Z);if(!Y)return;await P0.updateSessionMetadata(J,K.projectPath,{title:Y}),y0.publish({sessionId:J,projectPath:K.projectPath},"session.updated",{title:Y})}catch(W){x2.debug?.("[Loop] 自动生成会话标题失败:",W)}}var R$=`<turn_aborted>
1
+ import{wb as I5}from"./chunk-095x2ykj.js";import{Ab as Z5,Bb as J5,Cb as c$,Db as u$,Kb as d1,Tb as L2,Vb as J1,Wb as i0,Xb as W1,bc as P0,xb as d2}from"./chunk-1p5822w7.js";import{cc as V2,fc as o1,gc as q2}from"./chunk-vprpk6q1.js";import{hd as v5}from"./chunk-yz2bsntj.js";import{id as R5,jd as f2,kd as S5,ld as h5,md as Z1,od as m1}from"./chunk-sj2w24fe.js";import{Sd as v2,Td as b2,Wd as C5}from"./chunk-r1jxbx1h.js";import{de as t2}from"./chunk-17jpjcvb.js";import{je as w2}from"./chunk-77z6x1zb.js";import{_e as M5}from"./chunk-ah8hky46.js";import{nf as i}from"./chunk-dbb20rxh.js";import{Af as $5}from"./chunk-wxqkpvqw.js";import{If as Z0,Kf as M1,Lf as X2,Mf as l0,Of as t1,Qf as e1}from"./chunk-kmeccj99.js";import{Rf as K7}from"./chunk-fasxw5bb.js";function a2($){return $.role==="system"&&Array.isArray($.content)}function o2($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class R0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let J=$.messages.find(a2);if(this._contextualSystemMessages=$.messages.filter(o2),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!a2(W)&&!o2(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!o2($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(a2);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(Z)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((Z)=>!a2(Z)&&!o2(Z))}restoreDurableHistory($){this._contextualSystemMessages=$.filter(o2),this._history=$.filter((Z)=>!a2(Z)&&!o2(Z)),this._pending=[],this.syncContextualSystemMessages()}removeMessages($){this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages()}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function G1($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function L1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function F1($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import m2 from"node:path";var o5=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),a5=/^(LD_.+|DYLD_.+|PATH)$/,U1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function U0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(!o5.has(X))break;Z=K}return Z}function q8($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],K=J[2],Y=W.match(U1);if(!Y)break;let X=Y[1];if(a5.test(X))break;Z=K}return Z}var s5=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function A$($){let Z=$,J=!0;while(J){J=!1;for(let W of s5){let K=Z.match(W);if(K){Z=Z.slice(K[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function h0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){J+=z,Y=!0;continue}if(z==="'"&&!K){W=!W,J+=z;continue}if(z==='"'&&!W){K=!K,J+=z;continue}if(W||K){J+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(z==="&")return null;if(z===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=z}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function O1($){let Z=!1,J=!1,W=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let X=$[K+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(Y==="`")return!0;if(J)continue;if(Y==="|")return!0;if(Y===">"||Y==="<")return!0;if(Y==="{"){let X=$.slice(K);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function O0($){let Z=[],J="",W=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){J+=z,Y=!1;continue}if(z==="\\"&&!W){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;J+=z,Y=!1}continue}if(z==="'"&&!K){W=!W;continue}if(z==='"'&&!W){K=!K;continue}if(!W&&!K&&/[ \t]/.test(z)){if(J)Z.push(J),J="";continue}J+=z}if(J)Z.push(J);return Z}var t5=new Set(["npm","pnpm","yarn","bun"]),y1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),e5=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function $6($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function Z6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function J6($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let K=O0(W[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=m2.isAbsolute(Y)?m2.resolve(Y):m2.resolve(J,Y);if(!d2.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function s2($,Z){let J=U0(Z6($)),W=h0(J);if(!W||O1(J)||/[\r\n]/.test(J))return!1;let K=W.length===1?W[0]:J6(J,W,Z);if(!K)return!1;let Y=O0(K);if(Y.length===0||Y.some((H)=>[...e5].some((V)=>H===V||H.startsWith(`${V}=`))))return!1;let[X,z,Q]=Y;if(t5.has(X??""))return $6(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&y1.has(z??""))return!0;if(y1.has(X??""))return!0;if(X==="node"&&z==="--test")return!0;if(X==="go"&&["build","test","vet"].includes(z??""))return!0;return X==="cargo"&&["build","check","clippy","test"].includes(z??"")}function O8($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!m2.isAbsolute($);let J=m2.isAbsolute($)?m2.resolve($):m2.resolve(Z,$);return d2.isWithinWorkspace(J,Z)}var x$=w2("Agent"),W6=3;function k$($,Z,J){if($!=="length")return{action:"none"};if(Z>=W6)return{action:"truncated"};if(G1(J)==="stop")return x$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var K6=[/:\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],Y6=/```[\s\S]{50,}```/,P1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",X6=2;function T$($,Z,J=!0){if(!$||Z>=X6)return{action:"none"};if(!J&&Y6.test($))return{action:"retry",prompt:P1};let W=$.slice(-200),K=W.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(K6.some((X)=>X.test(W)))return{action:"retry",prompt:P1};return{action:"none"}}var z6=[/\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}(?:测试|单测|集成测试|检查|构建)/],E1={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},Q6={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},H6="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.",B6="Required verification did not run successfully before the retry limit.",V6=3;function N1($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&s2(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=J.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&s2(Y,W))$.add(Y)}function f$($,Z,J){if(!$||!z6.some((Q)=>Q.test($)))return{action:"none"};let W=Object.keys(E1).filter((Q)=>E1[Q].test($)),K=[...Z],Y=W.filter((Q)=>!K.some((H)=>Q6[Q].test(H)));if(W.length>0?Y.length===0:K.some((Q)=>s2(Q)))return{action:"none"};if(J>=V6)return{action:"fail",message:B6};let z=W.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${H6}${z}`}}var D6=[/\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|子代理|子智能体)/],_1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function S1($){return typeof $==="string"&&_1.some((Z)=>Z.test($))}var j6=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],w6=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function q6($){if(typeof $!=="string")return;if(w6.some((Z)=>Z.test($)))return"multiple-allowed";return j6.some((Z)=>Z.test($))?"required":void 0}function I0($){for(let Z of $){let J=q6(Z);if(J!==void 0)return J==="required"}return!1}var G6="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.",L6="Required delegation did not complete before the retry limit.",F6=3;function A1($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=I0(W),Y=!1;if(!K)for(let X of W){if(_1.some((z)=>z.test(X)))break;if(D6.some((z)=>z.test(X))){Y=!0;break}}if(W.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(J>=F6)return{action:"fail",message:L6};return{action:"retry",prompt:G6}}var U6=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],O6=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],y6=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function x1($){return y6.reduce((Z,J)=>Z.replace(J," "),$)}function p0($){if(typeof $!=="string")return!1;let Z=x1($);return U6.some((J)=>J.test(Z))}var P6="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.",E6="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.",b6="Required worktree lifecycle did not complete before the retry limit.",N6=3;function k1($,Z,J){if(!$)return{action:"none"};let W=x1($);if(!p0(W))return{action:"none"};let K=O6.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let Y=!Z.has("EnterWorktree")?"EnterWorktree":K&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!Y)return{action:"none"};if(J>=N6)return{action:"fail",message:b6};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?P6:E6}}var b1=30000;async function M$($){try{let J=t2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??i(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,K=new Promise((Y)=>{W=setTimeout(()=>Y("timeout"),b1)});try{let Y=await Promise.race([J,K]);if(Y==="timeout")return x$.warn(`[Loop] Stop hook 超时 (${b1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return x$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function _6($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var S6=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function A6($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function x6($){let Z=$;for(let Q of S6)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=W&&W[1].length>=6?W[1]:J;if(K=K.trim().replace(/[\s.。!!??,,;;::-]+$/,""),K.length<=60)return K;let Y=K.slice(0,60),X=Y.lastIndexOf(" ");return`${(X>36?Y.slice(0,X):Y).trimEnd()}…`}function T1($){return x6(A6($))}import{EventEmitter as k6}from"events";import f1 from"node:path";function v$($){if(M1($.sessionId),!f1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:f1.resolve($.projectPath)}}function f8($){let Z=v$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class e2 extends k6{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!e2.instance)e2.instance=new e2;return e2.instance}publish($,Z,J,W){let K=v$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var y0=e2.getInstance();var x2=w2("Agent"),g0=new Set;async function T6($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(g0.has(J))return;if(g0.size>=5000)g0.clear();g0.add(J);try{let W=$.workspaceRoot,K=await P0.findSessionMetadata(J,W);if(!K)return;if(K.title&&K.title.trim())return;let Y=T1(Z);if(!Y)return;await P0.updateSessionMetadata(J,K.projectPath,{title:Y}),y0.publish({sessionId:J,projectPath:K.projectPath},"session.updated",{title:Y})}catch(W){x2.debug?.("[Loop] 自动生成会话标题失败:",W)}}var R$=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,c2="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",v1="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class $0 extends Error{phase;constructor($,Z){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function u2($){return $.executionEngine?.getContextManager()}async function W2($,Z,J,W=null,K,Y={}){let X=Y.required??$.executionEngine!==void 0;try{let z=u2($),Q=typeof J==="string"?J.trim()!=="":J.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(z&&Z.sessionId&&Q){let H=await z.saveMessage(Z.sessionId,"user",J,W,K,Z.subagentInfo);if(X&&!H)throw Error("Durable user-message commit returned no identity");return T6(Z,J),H}if(X&&Z.sessionId&&Q)throw Error("Durable user-message storage is unavailable")}catch(z){if(x2.warn("[Loop] 保存用户消息失败:",z),X)throw new $0("user_message",{cause:z})}return null}async function C($,Z,J,W,K,Y,X={}){let z=X.required??$.executionEngine!==void 0;try{let Q=u2($),H=Boolean(J.trim()||K?.trim());if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"assistant",J,W,Y,Z.subagentInfo,K);if(z&&!V)throw Error("Durable assistant-message commit returned no identity");return V}if(z&&Z.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(Q){if(x2.warn("[Loop] 保存助手消息失败:",Q),z)throw new $0("assistant_message",{cause:Q})}return null}async function R1($,Z,J){try{let W=u2($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",R$,J,void 0,Z.subagentInfo)}catch(W){x2.warn("[Loop] 保存中断边界失败:",W)}return null}async function h1($,Z,J,W,K){try{let Y=u2($);if(!Y||!Z.sessionId||J.length===0)return null;return await Y.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,K,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(Y){x2.warn("[Loop] 保存 contextual project rules provenance 失败:",Y)}return null}async function h$($,Z,J,W,K,Y={}){try{let X=u2($);if(X&&Z.sessionId){let z=await X.saveToolUse(Z.sessionId,J,W,K,Z.subagentInfo);if(Y.required&&!z)throw Error("Durable tool-use commit returned no identity");return z}if(Y.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if(x2.warn("[Loop] 保存工具调用失败:",X),Y.required)throw X}return null}async function m0($,Z,J,W,K,Y,X,z,Q,H={}){try{let V=u2($);if(V&&Z.sessionId){let w=await V.saveToolResult(Z.sessionId,J,W,K,Y,X,Z.subagentInfo,z,Q);if(H.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(H.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(V){if(x2.warn("[Loop] 保存工具结果失败:",V),H.required)throw V}return null}async function E0($,Z,J,W,K={}){try{let Y=u2($);if(Y&&Z.sessionId){let X=await Y.saveCompaction(Z.sessionId,J,W,null);if(K.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(K.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(Y){if(x2.warn("[Loop] 保存压缩数据失败:",Y),K.required)throw Y}return null}import{createHash as n7}from"node:crypto";import{promises as m6}from"node:fs";import d6 from"node:path";import{nanoid as T2}from"nanoid";import*as d from"node:fs/promises";import*as l2 from"node:path";var C1={enabled:!0,maxIndexLines:200};var f6="memory",I1="MEMORY.md";class C${memoryDir;config;initialized=!1;constructor($,Z,J){if(J)this.memoryDir=J;else{let W=Z0($);this.memoryDir=l2.join(W,f6)}this.config={...C1,...Z}}async initialize(){if(this.initialized)return;await d.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=l2.join(this.memoryDir,I1);try{let Z=await d.readFile($,"utf-8");if(!Z.trim())return null;let J=Z.split(`
4
4
  `),K=J.slice(0,this.config.maxIndexLines).join(`
@@ -118,7 +118,7 @@ Full output saved to: ${z}`}catch{return`${Z}
118
118
 
119
119
  ${K}`}}import{Mutex as D7}from"async-mutex";import{nanoid as j7}from"nanoid";import*as B2 from"node:fs/promises";import*as a1 from"node:path";import{Mutex as e6}from"async-mutex";import $7 from"write-file-atomic";var u0=1,n1=8388608;function m$($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function Z7($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function J7($,Z,J){let W;try{W=JSON.parse($)}catch(Y){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:Y})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==u0||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let K=W.messages.map((Y)=>{if(!Y||typeof Y!=="object"||!("id"in Y)||typeof Y.id!=="string"||!("content"in Y)||!Z7(Y.content)||!("queuedAt"in Y)||typeof Y.queuedAt!=="number"||"persisted"in Y&&typeof Y.persisted!=="boolean"||"outputSchema"in Y&&Y.outputSchema!==void 0&&(!Y.outputSchema||typeof Y.outputSchema!=="object"||Array.isArray(Y.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let X="outputSchema"in Y&&Y.outputSchema!==void 0?i0(Y.outputSchema).schema:void 0;return{id:Y.id,content:Y.content,queuedAt:Y.queuedAt,..."persisted"in Y&&Y.persisted===!0?{persisted:!0}:{},...X?{outputSchema:X}:{}}});return{version:u0,sessionId:J,messages:K}}function W7($){return new Set($.flatMap((Z)=>Z.type==="inbox_acknowledged"?Z.data.messageIds:[]))}class r0{workspaceRoot;sessionId;filePath;mutex=new e6;messages=[];constructor($,Z,J){this.workspaceRoot=$;this.sessionId=Z;this.filePath=J}static async open($,Z){let J=new r0($,Z,l0($,Z));return await J.loadAndReconcile(),J}async enqueue($,Z){return this.mutex.runExclusive(async()=>{if(Z&&!Z(this.messages))return!1;let J=[...this.messages,{...$,recovered:!1}];return await this.persist(J),this.messages=J,!0})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=this.messages.filter((W)=>!Z.has(W.id));this.messages=J,await this.persist(J)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:u0,sessionId:this.sessionId,messages:[]};try{if((await B2.stat(this.filePath)).size>n1)throw Error(`Steering inbox exceeds ${n1} bytes: ${this.filePath}`);await B2.chmod(this.filePath,384),$=J7(await B2.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(K){if(!m$(K,"ENOENT"))throw K}let Z=X2(this.workspaceRoot,this.sessionId),J=new Set;try{J=W7(o1(await B2.readFile(Z,"utf8"),Z))}catch(K){if(!m$(K,"ENOENT"))throw K}let W=$.messages.filter((K)=>!J.has(K.id)).map((K)=>({...K,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($){if(await B2.mkdir(a1.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await B2.unlink(this.filePath).catch((J)=>{if(!m$(J,"ENOENT"))throw J});return}let Z={version:u0,sessionId:this.sessionId,messages:$.map(({recovered:J,...W})=>W)};await $7(this.filePath,`${JSON.stringify(Z)}
120
120
  `,{encoding:"utf8",mode:384,fsync:!0})}}import*as G2 from"node:fs/promises";import*as W5 from"node:path";import{nanoid as z2}from"nanoid";class i2{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,Z){this.sessionId=$;this.projectPath=Z;this.store=new q2(X2(Z,$))}static for($,Z){let J=`${Z}\x00${$}`,W=i2.instances.get(J);if(!W)W=new i2($,Z),i2.instances.set(J,W);return W}static release($,Z){i2.instances.delete(`${Z}\x00${$}`)}get lastSeq(){return this.highestSeq}async commit($){let Z=await this.store.append($);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.store.appendBatch($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.store.appendValidated($);return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.store.appendValidatedBatch($);for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);y0.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($)}}async replay($,Z){let J=await this.store.readFromSeq(Z);for(let W of J)$.onCommitted(W)}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;for(let Z of this.subscribers)Z.onCommitted($);y0.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function _0($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class E2 extends Error{}var Y7="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.",X7=20,z7=1e4,Q7=1e5,H7=2592000000;function B7($,Z){let J=V2($),W=J.findLastIndex((K)=>K.type==="turn_started"&&K.data.turnId===Z);if(W<0)return;for(let K=J.length-1;K>W;K--){let Y=J[K];if(Y?.type!=="message_created")continue;let X=Y.data.metadata;if(!X||typeof X!=="object"||Array.isArray(X))continue;let z=X.turnFinalization;if(!z||typeof z!=="object"||Array.isArray(z))continue;let{inputMessageIds:Q,turnsCount:H,toolCallsCount:V,durationMs:w}=z,G=Array.isArray(Q)?Q.filter((j)=>typeof j==="string"&&j.length>0&&j.length<=128):[];if(z.turnId!==Z||Z.length===0||Z.length>128||!Array.isArray(Q)||Q.length>X7||G.length!==Q.length||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>z7||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>Q7||typeof w!=="number"||!Number.isSafeInteger(w)||w<0||w>H7)continue;return{turnId:Z,inputMessageIds:[...new Set(G)],turnsCount:H,toolCallsCount:V,durationMs:w}}return}function s1($,Z){let J=V2($),W=Z?J.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===Z):-1;if(Z&&W<0)return{all:[],orphaned:[]};let K=new Map,Y=new Set,X=new Set;for(let Q of J.slice(W+1)){if(Q.type==="interaction_requested"){X.add(Q.data.toolCallId);continue}if(Q.type!=="part_created")continue;let H=Q.data.payload&&typeof Q.data.payload==="object"&&!Array.isArray(Q.data.payload)?Q.data.payload:{},V=typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId;if(Q.data.partType==="tool_call")K.set(V,{toolCallId:V,toolName:typeof H.toolName==="string"?H.toolName:"unknown"});else if(Q.data.partType==="tool_result")Y.add(V),Y.add(Q.data.partId),Y.add(Q.data.messageId)}let z=[...K.values()];return{all:z,orphaned:z.filter((Q)=>!Y.has(Q.toolCallId)&&!X.has(Q.toolCallId))}}class M2{projectPath;maxSessions;version;constructor($=i(),Z=100,J=$5()){this.projectPath=$,this.maxSessions=Z,this.version=J}createEvent($,Z,J){return{id:z2(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:t1(this.projectPath),version:this.version,data:J}}log($){return i2.for($,this.projectPath)}async ensureSessionCreated($,Z){let J=X2(this.projectPath,$);if((await new q2(J).readAll()).length>0)return;let Y=new Date().toISOString(),X={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},z=this.createEvent("session_created",$,X);await this.log($).commit(z)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=Z5;return Z}async initialize(){try{let $=Z0(this.projectPath);await G2.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,K,Y,X){try{await this.ensureSessionCreated($,Y);let z=new Date().toISOString(),Q=z2(),H={messageId:Q,role:Z,parentMessageId:W??void 0,inboxMessageId:K?.inboxMessageId,createdAt:z,model:K?.model,usage:K?.usage,metadata:K?JSON.parse(JSON.stringify(K)):void 0},V=this.createEvent("message_created",$,H),w=Z==="assistant"&&X?.trim()?[this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:"reasoning",payload:{text:X},createdAt:z})]:[],G=typeof J==="string"?[this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:"text",payload:{text:J},createdAt:z})]:J.map((j)=>this.createEvent("part_created",$,{partId:z2(),messageId:Q,partType:j.type==="text"?"text":"image",payload:j.type==="text"?{text:j.text}:{mimeType:V7(j.image_url.url)??"image/png",dataUrl:j.image_url.url},createdAt:z}));return await this.log($).commitBatch([V,...w,...G]),Q}catch(z){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,z),z}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async saveTurnStart($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=V2(J);if(W.some((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z.turnId))throw new E2;let K=_0(W).active;if(K)throw Error(`Session already has an active turn: ${K.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof E2))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let K=V2(W),Y=new Set(K.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),X=[...new Set(J)].filter((H)=>!Y.has(H)),z=K.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===Z.turnId);if(z){if(z.type==="turn_aborted"||X.length===0)throw new E2;return[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]}let Q=_0(K).active;if(!Q||Q.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...X.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof E2))throw W}}async saveTurnAbort($,Z){await this.saveTurnTerminal($,"turn_aborted",Z)}async recoverInterruptedTurn($){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((J)=>{let W=V2(J),K=_0(W).active,Y=s1(W);if(!K&&Y.orphaned.length===0)throw new E2;let X=K?B7(W,K.turnId):void 0;if(K&&X&&Y.orphaned.length===0){Z={turnId:K.turnId,outcome:"completed"};let w=new Set(W.flatMap((T)=>T.type==="inbox_acknowledged"?T.data.messageIds:[])),G=X.inputMessageIds.filter((T)=>!w.has(T)),j=new Date().toISOString();return[...G.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:G,acknowledgedAt:j})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:j,turnsCount:X.turnsCount,toolCallsCount:X.toolCallsCount,durationMs:X.durationMs})]}Z=K?{turnId:K.turnId,outcome:"aborted"}:void 0;let z=K?s1(W,K.turnId).all.length:0,Q=new Date().toISOString(),H=K?Date.parse(K.startedAt):Number.NaN,V=Y.orphaned.map((w)=>this.createEvent("part_created",$,{partId:w.toolCallId,messageId:w.toolCallId,partType:"tool_result",payload:{toolCallId:w.toolCallId,toolName:w.toolName,output:null,error:Y7,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:Q}));return K?[...V,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:Q,turnsCount:0,toolCallsCount:z,durationMs:Number.isFinite(H)?Math.max(0,Date.now()-H):0})]:V})}catch(J){if(!(J instanceof E2))throw J}return Z}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((K)=>K.type==="interaction_requested"&&K.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((Y)=>Y.type==="interaction_responded"&&Y.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="interaction_responded"&&Y.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((Y)=>Y.type==="interaction_recovered"&&Y.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="review_started"&&Y.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((Y)=>Y.type==="review_started"&&!J.some((X)=>X.type==="review_completed"&&X.data.reviewId===Y.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((Y)=>Y.type==="review_started"&&Y.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((Y)=>Y.type==="review_completed"&&Y.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,K){try{await this.ensureSessionCreated($,K);let Y=new Date().toISOString(),X=W??z2(),z=[];if(!W){let V={messageId:X,role:"assistant",parentMessageId:void 0,createdAt:Y};z.push(this.createEvent("message_created",$,V))}let Q=z2(),H={partId:Q,messageId:X,partType:"tool_call",payload:{toolCallId:Q,toolName:Z,input:J},createdAt:Y};if(z.push(this.createEvent("part_created",$,H)),Z==="Task"&&J&&typeof J==="object"){let V=J,w=typeof V.subagent_session_id==="string"?V.subagent_session_id:void 0,G=typeof V.subagent_type==="string"?V.subagent_type:void 0;if(w&&G){let j={partId:z2(),messageId:X,partType:"subtask_ref",payload:{childSessionId:w,agentType:G,status:"running",summary:typeof V.description==="string"?V.description:"",startedAt:Y},createdAt:Y};z.push(this.createEvent("part_created",$,j))}}return await this.log($).commitBatch(z),Q}catch(Y){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Y),Y}}async saveToolResult($,Z,J,W,K=null,Y,X,z,Q){try{await this.ensureSessionCreated($,X);let H=new Date().toISOString(),V=K??z2(),w=[];if(!K){let j={messageId:V,role:"assistant",parentMessageId:void 0,createdAt:H};w.push(this.createEvent("message_created",$,j))}let G={partId:Z,messageId:V,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:Y??null,...Q===void 0?{}:{metadata:Q}},createdAt:H};if(w.push(this.createEvent("part_created",$,G)),z){let j=z.subagentStatus==="running"?null:H,T={partId:z2(),messageId:V,partType:"subtask_ref",payload:{childSessionId:z.subagentSessionId,agentType:z.subagentType,description:z.subagentDescription??"",status:z.subagentStatus,summary:z.subagentSummary??"",resumedFrom:z.subagentResumedFrom??null,rootAgentId:z.subagentRootId??z.subagentSessionId,resumeDepth:z.subagentResumeDepth??0,verificationVerdict:z.verificationVerdict??null,startedAt:H,finishedAt:j},createdAt:H};w.push(this.createEvent("part_created",$,T))}return await this.log($).commitBatch(w),Z}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let K=new Date().toISOString(),Y=z2(),X={messageId:Y,role:"system",parentMessageId:W??void 0,createdAt:K},z=this.buildCompactionMetadata(J),Q={partId:z2(),messageId:Y,partType:"summary",payload:{text:Z,metadata:z,...J.replacementMessages?{replacementMessages:J5(J.replacementMessages)}:{}},createdAt:K},H=[this.createEvent("message_created",$,X),this.createEvent("part_created",$,Q)];return await this.log($).commitBatch(H),Y}catch(K){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,K),K}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=X2(this.projectPath,$),W=await new q2(Z).readAll();return W.length>0?V2(W):null}catch{return null}}async loadSession($){try{let Z=X2(this.projectPath,$),J=new q2(Z),W=V2(await J.readAll());if(W.length===0)return null;let K=W.find((Y)=>Y.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(K?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=X2(this.projectPath,$),J=new q2(Z),W=V2(await J.readAll());if(W.length===0)return null;let K=new Map;for(let Q of W){if(Q.type==="message_created")K.set(Q.data.messageId,{id:Q.data.messageId,role:Q.data.role,content:"",timestamp:new Date(Q.timestamp).getTime()});if(Q.type==="part_created"&&Q.data.partType==="text"){let H=K.get(Q.data.messageId);if(H){let V=Q.data.payload;H.content=V.text??""}}if(Q.type==="part_created"&&Q.data.partType==="image"){let H=K.get(Q.data.messageId);if(H)H.content=H.content?`${H.content}
121
- [Image]`:"[Image]"}}let Y=Array.from(K.values()),X=W[W.length-1],z=new Date(X.timestamp).getTime();return{messages:Y,topics:[],lastActivity:z}}catch{return null}}async listSessions(){try{let $=Z0(this.projectPath);return(await G2.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=X2(this.projectPath,$),J=new q2(Z);if(!(await J.getStats()).exists)return null;let K=await J.readAll();if(K.length===0)return null;let Y=V2(K),X=K[K.length-1],z=Y.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:z,topics:[]}}catch{return null}}async deleteSession($){try{let Z=X2(this.projectPath,$);await new q2(Z).delete(),await G2.unlink(l0(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:K}=await import("./chunk-y72p0x68.js"),Y=await W();if(Y)K(Y,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((K)=>this.getSessionSummary(K)))).filter((K)=>K!==null).sort((K,Y)=>Y.lastActivity-K.lastActivity).slice(this.maxSessions).map((K)=>K.sessionId);await Promise.all(W.map((K)=>this.deleteSession(K))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,Z,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let K=V2(W);if(K.some((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId))throw new E2;let X=_0(K).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return Z==="turn_completed"?this.createEvent("turn_completed",$,J):this.createEvent("turn_aborted",$,J)})}catch(W){if(!(W instanceof E2))throw W}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let W=X2(this.projectPath,J),Y=await new q2(W).getStats();Z+=Y.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=Z0(this.projectPath);await G2.mkdir($,{recursive:!0,mode:493});let Z=W5.join($,".health-check");return await G2.writeFile(Z,"test","utf-8"),await G2.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return e1()}}function V7($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var K5=131072,Y5=new Map;function d$($,Z){let J=`${$}\x00${Z}`,W=Y5.get(J);if(!W)W=new D7,Y5.set(J,W);return W}function l$($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>K5)throw Error(`${Z} exceeds ${K5} bytes`);return JSON.parse(J)}function X5($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function w7($,Z){return JSON.stringify($)===JSON.stringify(Z)}function q7($,Z){if($.request.interactionType!=="elicitation")return l$(Z,"Interaction response");return l$({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function z5($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function G7($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function L7($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
121
+ [Image]`:"[Image]"}}let Y=Array.from(K.values()),X=W[W.length-1],z=new Date(X.timestamp).getTime();return{messages:Y,topics:[],lastActivity:z}}catch{return null}}async listSessions(){try{let $=Z0(this.projectPath);return(await G2.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=X2(this.projectPath,$),J=new q2(Z);if(!(await J.getStats()).exists)return null;let K=await J.readAll();if(K.length===0)return null;let Y=V2(K),X=K[K.length-1],z=Y.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:z,topics:[]}}catch{return null}}async deleteSession($){try{let Z=X2(this.projectPath,$);await new q2(Z).delete(),await G2.unlink(l0(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W});try{let{getProjectionDb:W,removeSessionFromProjection:K}=await import("./chunk-0et4h9p3.js"),Y=await W();if(Y)K(Y,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((K)=>this.getSessionSummary(K)))).filter((K)=>K!==null).sort((K,Y)=>Y.lastActivity-K.lastActivity).slice(this.maxSessions).map((K)=>K.sessionId);await Promise.all(W.map((K)=>this.deleteSession(K))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async saveTurnTerminal($,Z,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((W)=>{let K=V2(W);if(K.some((z)=>(z.type==="turn_completed"||z.type==="turn_aborted")&&z.data.turnId===J.turnId))throw new E2;let X=_0(K).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return Z==="turn_completed"?this.createEvent("turn_completed",$,J):this.createEvent("turn_aborted",$,J)})}catch(W){if(!(W instanceof E2))throw W}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let W=X2(this.projectPath,J),Y=await new q2(W).getStats();Z+=Y.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=Z0(this.projectPath);await G2.mkdir($,{recursive:!0,mode:493});let Z=W5.join($,".health-check");return await G2.writeFile(Z,"test","utf-8"),await G2.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return e1()}}function V7($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var K5=131072,Y5=new Map;function d$($,Z){let J=`${$}\x00${Z}`,W=Y5.get(J);if(!W)W=new D7,Y5.set(J,W);return W}function l$($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>K5)throw Error(`${Z} exceeds ${K5} bytes`);return JSON.parse(J)}function X5($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function w7($,Z){return JSON.stringify($)===JSON.stringify(Z)}function q7($,Z){if($.request.interactionType!=="elicitation")return l$(Z,"Interaction response");return l$({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function z5($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function G7($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function L7($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
122
122
  `)}function F7($,Z){let{request:J}=$;if(J.interactionType==="question"){let X=L7(Z);return{toolOutput:`User answers:
123
123
  ${X}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
124
124
  ${X}
@@ -1,4 +1,4 @@
1
- import"./chunk-6pa6c2n0.js";import"./chunk-6207mbmr.js";import{We as Q}from"./chunk-e37k44j1.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as L}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-fbnetqrz.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import{Qf as F}from"./chunk-6g5k5de1.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-y72p0x68.js"),{SessionService:B}=await import("./chunk-n00q74bt.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-5hhfv1w1.js";import"./chunk-77z6x1zb.js";import{Xe as Q}from"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as L}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import{Rf as F}from"./chunk-fasxw5bb.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-0et4h9p3.js"),{SessionService:B}=await import("./chunk-smh39yy2.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,3 +1,3 @@
1
- import{Of as j}from"./chunk-yvf4nmds.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{Pf as j}from"./chunk-kmeccj99.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
- export{m as fe,I as ge,M as he,V as ie,h as je};
3
+ export{m as ge,I as he,M as ie,V as je,h as ke};
@@ -1 +1 @@
1
- import{Ea as J,la as V,na as W,oa as O}from"./chunk-qt114yth.js";import"./chunk-6207mbmr.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as Q}from"./chunk-prgh321y.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{Ea as J,la as V,na as W,oa as O}from"./chunk-ktbe458z.js";import"./chunk-77z6x1zb.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as Q}from"./chunk-dbb20rxh.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -0,0 +1 @@
1
+ import{wc as a,xc as b,yc as c}from"./chunk-2wp6h1p8.js";import"./chunk-k106g2p6.js";import"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-2c3zavy2.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -0,0 +1 @@
1
+ import{Ff as a}from"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as WorkspaceTrustService};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as sf,p as tf,u as uf,S as vf,c as wf,l as xf};
2
+ export{f as tf,p as uf,u as vf,S as wf,c as xf,l as yf};
@@ -1,4 +1,4 @@
1
- import{G as P}from"./chunk-zqf8043h.js";import{gb as K}from"./chunk-htarfekt.js";import{Eb as G,Fb as N,Gb as S,Hb as O,Ib as s,bc as B}from"./chunk-q6ev6t06.js";import{gc as j}from"./chunk-8rzwyknk.js";import{hd as q}from"./chunk-yz2bsntj.js";import{zd as v}from"./chunk-0y0wbjyf.js";import{Kf as z}from"./chunk-yvf4nmds.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{G as P}from"./chunk-ryhk5qmv.js";import{gb as K}from"./chunk-72ztan96.js";import{Eb as G,Fb as N,Gb as S,Hb as O,Ib as s,bc as B}from"./chunk-1p5822w7.js";import{gc as j}from"./chunk-vprpk6q1.js";import{hd as q}from"./chunk-yz2bsntj.js";import{zd as v}from"./chunk-g7p165yz.js";import{Lf as z}from"./chunk-kmeccj99.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,2 +1,2 @@
1
- import{td as B}from"./chunk-5chec8rs.js";import{rf as Y}from"./chunk-jpwfq49n.js";import{uf as Z,xf as $}from"./chunk-yqfqj7mh.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
1
+ import{td as B}from"./chunk-5chec8rs.js";import{sf as Y}from"./chunk-w5m418w5.js";import{vf as Z,yf as $}from"./chunk-9wqr1sbq.js";import{createHash as D}from"node:crypto";var F="fast-mode-2026-02-01";function H(q,z,W){if(z.api!=="anthropic-messages"||W.providerValue!=="fast")return q;let G={...q},J=Object.keys(G).find((w)=>w.toLowerCase()==="anthropic-beta")??"anthropic-beta",L=new Set((G[J]??"").split(",").map((w)=>w.trim()).filter(Boolean));return L.add(F),G[J]=[...L].join(","),G}function K(q){return`BLADE_MODEL_API_KEY_${D("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function O(q,z,W,G=Y(),J="auto",L="auto"){let w=G.resolveConfig(q),Q=B(w,W),U=$(w,J),X=Z(w,L),x=q.overrides;return{config:q,model:w,displayName:q.displayName??w.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[K(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??x?.baseUrl,temperature:x?.temperature??z.temperature,maxContextTokens:w.contextWindow,maxOutputTokens:x?.maxOutputTokens,timeout:x?.timeout??z.timeout,streamIdleTimeout:x?.streamIdleTimeout,reasoningEnabled:Q.effective!=="off",...Q.effective==="off"?{}:{reasoningEffort:Q.effective},...U.providerValue?{serviceTier:U.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:q.fallbackModels,enablePromptCaching:x?.enablePromptCaching,customHeaders:H(x?.customHeaders,w,U),apiVersion:x?.apiVersion,maxRetries:x?.maxRetries,modelCatalog:G},reasoning:Q,serviceTier:U,responseVerbosity:X}}function E(q,z=Y()){try{return q.displayName??z.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
2
  export{K as pd,O as qd,E as rd};
@@ -1,2 +1,2 @@
1
1
  var r;((t)=>{t.DEFAULT="default";t.AUTO_EDIT="autoEdit";t.YOLO="yolo";t.PLAN="plan"})(r||={});var N=100;function _(n){return Number.isInteger(n)&&n>=-1&&n<=100}function u(){return"-1, 0, or an integer from 1 to 100"}
2
- export{r as Ye,N as Ze,_ as _e,u as $e};
2
+ export{r as Ze,N as _e,_ as $e,u as af};
@@ -1,4 +1,4 @@
1
- import{m as R,n as I,o as C,p as v,q as S}from"./chunk-z2fn2yg8.js";import{F as y,L as w}from"./chunk-zqf8043h.js";import"./chunk-eakfkjk4.js";import"./chunk-qt114yth.js";import{Va as x,hb as U}from"./chunk-htarfekt.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-q6ev6t06.js";import"./chunk-8rzwyknk.js";import{uc as P}from"./chunk-zzkdr84r.js";import{wc as h,xc as O,yc as M}from"./chunk-xpt6cdn8.js";import{zc as z}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Wc as N}from"./chunk-bffw1t7e.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-f6a1grte.js";import"./chunk-0y0wbjyf.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-j9vqys2g.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-e37k44j1.js";import{Ye as D}from"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as E}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-fbnetqrz.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
1
+ import{m as R,n as I,o as C,p as v,q as S}from"./chunk-ns5015tn.js";import{F as y,L as w}from"./chunk-ryhk5qmv.js";import"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import{Va as x,hb as U}from"./chunk-72ztan96.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import{uc as P}from"./chunk-q4fjec99.js";import{wc as h,xc as O,yc as M}from"./chunk-2wp6h1p8.js";import{zc as z}from"./chunk-k106g2p6.js";import"./chunk-65kbckpt.js";import{Wc as N}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import{Ze as D}from"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as E}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
2
2
  `);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSessionModelContext(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
3
3
  `);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
4
4
  `);else q.stdout.write(`${k(H.record)}
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-eakfkjk4.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-bffw1t7e.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-j9vqys2g.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-e37k44j1.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as k}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-fbnetqrz.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-4tkn9bky.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import{nf as k}from"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -0,0 +1 @@
1
+ import{ud as a,vd as b,wd as c}from"./chunk-4ypy5bk8.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -0,0 +1 @@
1
+ import{uc as a,vc as b}from"./chunk-q4fjec99.js";import"./chunk-wxqkpvqw.js";import"./chunk-fasxw5bb.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{f as Q,g as R,h as T,i as W}from"./chunk-7pkscxbb.js";import"./chunk-zdkc4kj1.js";import"./chunk-fa6313dv.js";import"./chunk-ehgfwwqk.js";import"./chunk-wmttq8eq.js";import"./chunk-zqf8043h.js";import"./chunk-eakfkjk4.js";import"./chunk-qt114yth.js";import"./chunk-htarfekt.js";import"./chunk-095x2ykj.js";import"./chunk-q6ev6t06.js";import"./chunk-8rzwyknk.js";import"./chunk-k3nkcaap.js";import{Xc as M}from"./chunk-bffw1t7e.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-f6a1grte.js";import"./chunk-0y0wbjyf.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-j9vqys2g.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-e37k44j1.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import{zf as J}from"./chunk-fbnetqrz.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import b from"chalk";import H from"open";var $=`
1
+ import{f as Q,g as R,h as T,i as W}from"./chunk-pmw9pn3v.js";import"./chunk-jhzk287k.js";import"./chunk-wc1ee4tc.js";import"./chunk-a1ztrwjb.js";import"./chunk-4v8nxcxp.js";import"./chunk-ryhk5qmv.js";import"./chunk-4tkn9bky.js";import"./chunk-ktbe458z.js";import"./chunk-72ztan96.js";import"./chunk-095x2ykj.js";import"./chunk-1p5822w7.js";import"./chunk-vprpk6q1.js";import"./chunk-65kbckpt.js";import{Xc as M}from"./chunk-whftbz4b.js";import"./chunk-5hhfv1w1.js";import"./chunk-yz2bsntj.js";import"./chunk-sj2w24fe.js";import"./chunk-afhdpen9.js";import"./chunk-5chec8rs.js";import"./chunk-4ypy5bk8.js";import"./chunk-g7p165yz.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-17jpjcvb.js";import"./chunk-jyeas4p9.js";import"./chunk-77z6x1zb.js";import"./chunk-mvc0tad6.js";import"./chunk-ah8hky46.js";import"./chunk-r561wfcz.js";import"./chunk-0qayfsc9.js";import"./chunk-dbb20rxh.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import{Af as J}from"./chunk-wxqkpvqw.js";import"./chunk-jahf977w.js";import"./chunk-1y52h772.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as jf,D as kf,P as lf,V as mf};
2
+ export{N as kf,D as lf,P as mf,V as nf};
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-fa6313dv.js";import{mf as s}from"./chunk-prgh321y.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-wc1ee4tc.js";import{nf as s}from"./chunk-dbb20rxh.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1,4 +1,4 @@
1
- import{Sc as W}from"./chunk-bffw1t7e.js";import{de as X}from"./chunk-j9vqys2g.js";import{ge as Q,ie as U}from"./chunk-6207mbmr.js";import{mf as V}from"./chunk-prgh321y.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Sc as W}from"./chunk-whftbz4b.js";import{de as X}from"./chunk-17jpjcvb.js";import{he as Q,je as U}from"./chunk-77z6x1zb.js";import{nf as V}from"./chunk-dbb20rxh.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
4
4
  export{K as Ac,P as Bc,L as Cc,k as Dc};
@@ -0,0 +1 @@
1
+ import{od as a}from"./chunk-sj2w24fe.js";import"./chunk-77z6x1zb.js";import"./chunk-w5m418w5.js";import"./chunk-9wqr1sbq.js";import"./chunk-kmeccj99.js";import"./chunk-fasxw5bb.js";export{a as createChatServiceAsync};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as Qf};
2
+ export{c as Rf};
@@ -1,4 +1,4 @@
1
- import{Sd as L1,Td as Z0,Ud as G1}from"./chunk-r1jxbx1h.js";import{Yd as $O,Zd as HO}from"./chunk-6sb7cg95.js";import{ae as Y1}from"./chunk-2c3zavy2.js";import{be as B0,de as M0}from"./chunk-j9vqys2g.js";import{ie as h,je as z}from"./chunk-6207mbmr.js";import{Me as V0,Ne as o1,We as j0}from"./chunk-e37k44j1.js";import{af as u,cf as W,ff as R1}from"./chunk-96h588rd.js";import{mf as b}from"./chunk-prgh321y.js";import{zf as d0}from"./chunk-fbnetqrz.js";import{Ef as T}from"./chunk-1n60pgsq.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{Sd as L1,Td as Z0,Ud as G1}from"./chunk-r1jxbx1h.js";import{Yd as $O,Zd as HO}from"./chunk-6sb7cg95.js";import{ae as Y1}from"./chunk-2c3zavy2.js";import{be as B0,de as M0}from"./chunk-17jpjcvb.js";import{je as h,ke as z}from"./chunk-77z6x1zb.js";import{Ne as V0,Oe as o1,Xe as j0}from"./chunk-mvc0tad6.js";import{bf as u,df as W,gf as R1}from"./chunk-r561wfcz.js";import{nf as b}from"./chunk-dbb20rxh.js";import{Af as d0}from"./chunk-wxqkpvqw.js";import{Ff as T}from"./chunk-jahf977w.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,3 +1,3 @@
1
- import{Ff as y}from"./chunk-qkrssft1.js";import{Of as b}from"./chunk-yvf4nmds.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
1
+ import{Gf as y}from"./chunk-1y52h772.js";import{Pf as b}from"./chunk-kmeccj99.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
2
2
  `,{mode:384}),await d.chmod(t,384)}async ensureStoreDirectoryForWrite(){try{let e=await d.lstat(this.storeDir);if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(e){if(e.code!=="ENOENT")throw e;await d.mkdir(this.storeDir,{recursive:!0,mode:448}),await d.chmod(this.storeDir,448)}}}
3
- export{h as Ef};
3
+ export{h as Ff};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-d9k98jy2.js";import"./chunk-6g5k5de1.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-2ygqbd1z.js";import"./chunk-fasxw5bb.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1,2 +1,2 @@
1
- import{rf as o}from"./chunk-jpwfq49n.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{sf as o}from"./chunk-w5m418w5.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e as j,i as k};
@@ -0,0 +1,2 @@
1
+ import{spawn as b}from"node:child_process";var I=500;function X(j){return new Promise((q)=>setTimeout(q,j))}function Y(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function x(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=b("taskkill",z,{stdio:"ignore",windowsHide:!0}),J=!1,K=(H)=>{if(J)return;J=!0,y(H)};B.once("error",()=>K(!1)),B.once("close",(H)=>K(H===0))})}async function N(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??I,B=q.killProcess??process.kill.bind(process),J=q.taskkill??x,K=q.wait??X,H=q.validatePidOwnership??(()=>!0);if(!H())return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let Q=await J(j,!1);if(await K(z),!H())return{success:Q,alreadyExited:!1,forced:!1};let V=await J(j,!0);return{success:Q||V,alreadyExited:!Q&&!V,forced:V}}let W=(Q,V)=>{try{return B(Q,V)}catch(G){return Y(G)==="ESRCH"}},Z=W(-j,"SIGTERM")||W(j,"SIGTERM");if(await K(z),!H())return{success:Z,alreadyExited:!1,forced:!1};let $=W(-j,"SIGKILL")||W(j,"SIGKILL");return{success:Z||$,alreadyExited:!1,forced:$}}class D{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??I,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??x,this.wait=q.wait??X,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Y(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Y(q)==="ESRCH"}}}function U(j,q,y={},z={}){let B=b(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new D(B,z)}}
2
+ export{N as ee,U as fe};
@@ -1,2 +1,2 @@
1
- import{ae as W}from"./chunk-2c3zavy2.js";import{Ze as V}from"./chunk-y2g5a5bp.js";import{af as F,cf as k,ff as H}from"./chunk-96h588rd.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
1
+ import{ae as W}from"./chunk-2c3zavy2.js";import{_e as V}from"./chunk-ah8hky46.js";import{bf as F,df as k,gf as H}from"./chunk-r561wfcz.js";var $=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),Q=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),b=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(Q),disallowedTools:k.Optional(Q),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(H(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1,maximum:V})),isolation:k.Optional(H(["none","worktree"]))},{additionalProperties:!1});function O(Y){let w;try{w=JSON.parse(Y)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let I=Object.entries(w);if(I.length>64)throw Error("--agents supports at most 64 definitions");return I.map(([z,Z])=>{if(!F($,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let K=F(b,Z);if(!K.success)throw Error(`Invalid --agents definition for "${z}"`);let q=K.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:W(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
2
  export{O as zc};