blade-code 0.10.11 → 0.10.12

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 (36) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-s6v7kg40.js → chunk-04wd6zez.js} +1 -1
  3. package/dist/chunk-14rzj7js.js +1 -0
  4. package/dist/{chunk-yg2bd4w2.js → chunk-21zwc98r.js} +1 -1
  5. package/dist/{chunk-sa572750.js → chunk-2mmbqha8.js} +1 -1
  6. package/dist/{chunk-4vjx9ft1.js → chunk-2wkt2w3f.js} +1 -1
  7. package/dist/{chunk-7ysw82r9.js → chunk-4faz5tkt.js} +1 -1
  8. package/dist/{chunk-230xac12.js → chunk-63rg3mhn.js} +1 -1
  9. package/dist/{chunk-ajg3q7e4.js → chunk-670th5hb.js} +1 -1
  10. package/dist/{chunk-cskpqe1m.js → chunk-86shv4yp.js} +1 -1
  11. package/dist/{chunk-kqgtrnm6.js → chunk-86w8fd67.js} +2 -2
  12. package/dist/{chunk-3wms95qc.js → chunk-95zwz4q8.js} +1 -1
  13. package/dist/{chunk-z18bbtg9.js → chunk-9e8fyt60.js} +1 -1
  14. package/dist/{chunk-5b7xhvd1.js → chunk-cscm57tr.js} +1 -1
  15. package/dist/{chunk-brwths02.js → chunk-e2s6czgg.js} +1 -1
  16. package/dist/{chunk-93pn0vhs.js → chunk-e65vyfj7.js} +1 -1
  17. package/dist/{chunk-jvfzm6gn.js → chunk-eqr25kxv.js} +1 -1
  18. package/dist/{chunk-5df4x6ec.js → chunk-evn886hs.js} +1 -1
  19. package/dist/{chunk-fm913p7k.js → chunk-hb8krnp5.js} +1 -1
  20. package/dist/{chunk-82tsyr4f.js → chunk-jh4571hm.js} +1 -1
  21. package/dist/{chunk-bzwa0td4.js → chunk-k7caqeew.js} +1 -1
  22. package/dist/{chunk-qdf7sb0k.js → chunk-p5zstj8j.js} +1 -1
  23. package/dist/{chunk-k1my44xn.js → chunk-pmvfkre2.js} +1 -1
  24. package/dist/{chunk-wpjb7918.js → chunk-pqgw6t9b.js} +3 -3
  25. package/dist/{chunk-1qz9qfzc.js → chunk-pz21tcah.js} +1 -1
  26. package/dist/{chunk-tgtj3bj1.js → chunk-tadbcnwr.js} +1 -1
  27. package/dist/{chunk-xm9katxj.js → chunk-vaxcmm72.js} +1 -1
  28. package/dist/{chunk-sxcm8ryt.js → chunk-vdgskayb.js} +1 -1
  29. package/dist/{chunk-amx33f28.js → chunk-vpz57h5x.js} +1 -1
  30. package/dist/{chunk-h9k52syw.js → chunk-vszmbnjh.js} +1 -1
  31. package/dist/{chunk-ze1hqsbs.js → chunk-vwwf7p7x.js} +1 -1
  32. package/dist/{chunk-xe0z59h2.js → chunk-y2j96b3t.js} +1 -1
  33. package/dist/{chunk-gqrrheb3.js → chunk-z24sj1r8.js} +1 -1
  34. package/dist/{chunk-b692dgxx.js → chunk-zd3qxc5p.js} +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-efqa79kw.js +0 -1
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Ac as W}from"./chunk-amx33f28.js";import{Dc as F,Ec as M}from"./chunk-ktf3bpmw.js";import"./chunk-gqrrheb3.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import{de as T}from"./chunk-4dq9y7zn.js";import"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{hf as N,if as B}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as J}from"./chunk-g11hq0e5.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-s6v7kg40.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-cskpqe1m.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-fvrmjhz5.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-bzwa0td4.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-k1my44xn.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-xe0z59h2.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-efqa79kw.js"),import("./chunk-b692dgxx.js"),import("./chunk-kqgtrnm6.js"),import("./chunk-74shfpve.js"),import("./chunk-4vjx9ft1.js"),import("./chunk-mtk2tf9n.js"),import("./chunk-4zs5r4n4.js"),import("./chunk-sa572750.js"),import("./chunk-xx1d9kfd.js"),import("./chunk-ajg3q7e4.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
2
+ import{Ac as W}from"./chunk-vpz57h5x.js";import{Dc as F,Ec as M}from"./chunk-ktf3bpmw.js";import"./chunk-z24sj1r8.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import{de as T}from"./chunk-4dq9y7zn.js";import"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{hf as N,if as B}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as J}from"./chunk-g11hq0e5.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-04wd6zez.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-86shv4yp.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-fvrmjhz5.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-k7caqeew.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-pmvfkre2.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-y2j96b3t.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-14rzj7js.js"),import("./chunk-zd3qxc5p.js"),import("./chunk-86w8fd67.js"),import("./chunk-74shfpve.js"),import("./chunk-2wkt2w3f.js"),import("./chunk-mtk2tf9n.js"),import("./chunk-4zs5r4n4.js"),import("./chunk-2mmbqha8.js"),import("./chunk-xx1d9kfd.js"),import("./chunk-670th5hb.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
3
3
  Stack trace:`),console.error(Z.stack);else console.error(`
4
4
  Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
5
- Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-hxp5qs1x.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-ze1hqsbs.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
5
+ Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,h=import("./chunk-hxp5qs1x.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-vwwf7p7x.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
@@ -1 +1 @@
1
- import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-jvfzm6gn.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{uf as a,vf as b,wf as c,xf as d,yf as e,zf as f}from"./chunk-eqr25kxv.js";import"./chunk-g11hq0e5.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -0,0 +1 @@
1
+ import{sc as a,tc as b}from"./chunk-95zwz4q8.js";import"./chunk-eqr25kxv.js";import"./chunk-g11hq0e5.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{wb as NZ}from"./chunk-095x2ykj.js";import{$b as S$,Ab as I$,Bb as p$,Ib as R1,Kb as j2,Mb as o$,Nb as g0,Ob as a$,xb as T2}from"./chunk-93pn0vhs.js";import{ac as E2,dc as d1,ec as V2}from"./chunk-4hawehmd.js";import{fd as EZ}from"./chunk-ybvdac8k.js";import{gd as bZ,hd as R2,id as UZ,kd as v1}from"./chunk-ah97bmns.js";import{Od as _2,Pd as U2,Sd as _Z}from"./chunk-9tnaads5.js";import{$d as l2}from"./chunk-brwths02.js";import{ee as B2}from"./chunk-4dq9y7zn.js";import{Ve as PZ}from"./chunk-3aqdjrtm.js";import{if as u}from"./chunk-5s123nbs.js";import{vf as i1}from"./chunk-jvfzm6gn.js";import{Df as r2,Ff as A1,Gf as J2,Hf as p0,Jf as c1,Lf as l1}from"./chunk-363pgv1e.js";import{Mf as l5}from"./chunk-g11hq0e5.js";function V0($){return $.role==="system"&&Array.isArray($.content)}function A0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class k0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let W=$.messages.find(V0);if(this._contextualSystemMessages=$.messages.filter(A0),W)this.systemMessages=[W,...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((J)=>!V0(J)&&!A0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!A0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(V0);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)=>!V0(Z)&&!A0(Z))}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 B1($){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 V1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function D1($,Z,W){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:W?$.consecutiveContinuations+1:0}}import f2 from"node:path";var hZ=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"]),IZ=/^(LD_.+|DYLD_.+|PATH)$/,j1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function D0($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(!hZ.has(X))break;Z=K}return Z}function s6($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(IZ.test(X))break;Z=K}return Z}var pZ=[/^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 P$($){let Z=$,W=!0;while(W){W=!1;for(let J of pZ){let K=Z.match(J);if(K){Z=Z.slice(K[0].length),W=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),W=!0}return Z}function S0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){W+=z,Y=!0;continue}if(z==="'"&&!K){J=!J,W+=z;continue}if(z==='"'&&!J){K=!K,W+=z;continue}if(J||K){W+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(W.trim())Z.push(W.trim());W="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(W.trim())Z.push(W.trim());W="",X++;continue}if(z==="&")return null;if(z===";"){if(W.trim())Z.push(W.trim());W="";continue}W+=z}if(W.trim())Z.push(W.trim());return Z.length>0?Z:null}function w1($){let Z=!1,W=!1,J=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(J){J=!1;continue}if(Y==="\\"&&!Z){J=!0;continue}if(Y==="'"&&!W){Z=!Z;continue}if(Y==='"'&&!Z){W=!W;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(W)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 j0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;W+=z,Y=!1}continue}if(z==="'"&&!K){J=!J;continue}if(z==='"'&&!J){K=!K;continue}if(!J&&!K&&/[ \t]/.test(z)){if(W)Z.push(W),W="";continue}W+=z}if(W)Z.push(W);return Z}var gZ=new Set(["npm","pnpm","yarn","bun"]),q1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),mZ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function dZ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function uZ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function cZ($,Z,W){if(!W||Z.length!==2)return;let J=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!J)return;let K=j0(J[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=f2.isAbsolute(Y)?f2.resolve(Y):f2.resolve(W,Y);if(!T2.isWithinWorkspace(X,W))return;return J[2]?.trim()||void 0}function c2($,Z){let W=D0(uZ($)),J=S0(W);if(!J||w1(W)||/[\r\n]/.test(W))return!1;let K=J.length===1?J[0]:cZ(W,J,Z);if(!K)return!1;let Y=j0(K);if(Y.length===0||Y.some((V)=>[...mZ].some((D)=>V===D||V.startsWith(`${D}=`))))return!1;let[X,z,Q]=Y;if(gZ.has(X??""))return dZ(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&q1.has(z??""))return!0;if(q1.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 W7($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!f2.isAbsolute($);let W=f2.isAbsolute($)?f2.resolve($):f2.resolve(Z,$);return T2.isWithinWorkspace(W,Z)}var E$=B2("Agent"),lZ=3;function b$($,Z,W){if($!=="length")return{action:"none"};if(Z>=lZ)return{action:"truncated"};if(B1(W)==="stop")return E$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var iZ=[/:\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],rZ=/```[\s\S]{50,}```/,G1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",nZ=2;function _$($,Z,W=!0){if(!$||Z>=nZ)return{action:"none"};if(!W&&rZ.test($))return{action:"retry",prompt:G1};let J=$.slice(-200),K=J.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(iZ.some((X)=>X.test(J)))return{action:"retry",prompt:G1};return{action:"none"}}var oZ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],U1={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},aZ={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},sZ="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.",tZ="Required verification did not run successfully before the retry limit.",eZ=3;function F1($,Z,W,J){if(!W.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof W.metadata?.command==="string"&&W.metadata.exit_code===0&&c2(W.metadata.command,J)){$.add(W.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=W.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&c2(Y,J))$.add(Y)}function N$($,Z,W){if(!$||!oZ.some((Q)=>Q.test($)))return{action:"none"};let J=Object.keys(U1).filter((Q)=>U1[Q].test($)),K=[...Z],Y=J.filter((Q)=>!K.some((V)=>aZ[Q].test(V)));if(J.length>0?Y.length===0:K.some((Q)=>c2(Q)))return{action:"none"};if(W>=eZ)return{action:"fail",message:tZ};let z=J.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${sZ}${z}`}}var $5=[/\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|子代理|子智能体)/],L1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function y1($){return typeof $==="string"&&L1.some((Z)=>Z.test($))}var Z5=[/\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|子代理)/],W5=[/\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 J5($){if(typeof $!=="string")return;if(W5.some((Z)=>Z.test($)))return"multiple-allowed";return Z5.some((Z)=>Z.test($))?"required":void 0}function f0($){for(let Z of $){let W=J5(Z);if(W!==void 0)return W==="required"}return!1}var K5="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.",Y5="Required delegation did not complete before the retry limit.",X5=3;function P1($,Z,W){let J=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=f0(J),Y=!1;if(!K)for(let X of J){if(L1.some((z)=>z.test(X)))break;if($5.some((z)=>z.test(X))){Y=!0;break}}if(J.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(W>=X5)return{action:"fail",message:Y5};return{action:"retry",prompt:K5}}var z5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H5=[/\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 E1($){return H5.reduce((Z,W)=>Z.replace(W," "),$)}function T0($){if(typeof $!=="string")return!1;let Z=E1($);return z5.some((W)=>W.test(Z))}var B5="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.",V5="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.",D5="Required worktree lifecycle did not complete before the retry limit.",j5=3;function b1($,Z,W){if(!$)return{action:"none"};let J=E1($);if(!T0(J))return{action:"none"};let K=Q5.some((X)=>X.test(J));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(W>=j5)return{action:"fail",message:D5};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?B5:V5}}var O1=30000;async function A$($){try{let W=l2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??u(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,K=new Promise((Y)=>{J=setTimeout(()=>Y("timeout"),O1)});try{let Y=await Promise.race([W,K]);if(Y==="timeout")return E$.warn(`[Loop] Stop hook 超时 (${O1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return E$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w5($,Z){let W;while(!(W=await $.next()).done)if(Z)await Z(W.value);return W.value}var q5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G5($){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 W=Z.text;return typeof W==="string"?W:""}return""}).join(" ");return""}function U5($){let Z=$;for(let Q of q5)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let W=Z.replace(/\s+/g," ").trim();if(!W)return"";let J=W.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=J&&J[1].length>=6?J[1]:W;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 _1($){return U5(G5($))}import{EventEmitter as O5}from"events";import N1 from"node:path";function k$($){if(A1($.sessionId),!N1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N1.resolve($.projectPath)}}function w7($){let Z=k$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class i2 extends O5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!i2.instance)i2.instance=new i2;return i2.instance}publish($,Z,W,J){let K=k$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...J!==void 0?{seq:J}:{},properties:W})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var w0=i2.getInstance();var y2=B2("Agent"),M0=new Set;async function F5($,Z){let W=$.sessionId;if(!W||$.subagentInfo)return;if(M0.has(W))return;if(M0.size>=5000)M0.clear();M0.add(W);try{let J=$.workspaceRoot,K=await S$.findSessionMetadata(W,J);if(!K)return;if(K.title&&K.title.trim())return;let Y=_1(Z);if(!Y)return;await S$.updateSessionMetadata(W,K.projectPath,{title:Y}),w0.publish({sessionId:W,projectPath:K.projectPath},"session.updated",{title:Y})}catch(J){y2.debug?.("[Loop] 自动生成会话标题失败:",J)}}var x$=`<turn_aborted>
1
+ import{wb as NZ}from"./chunk-095x2ykj.js";import{$b as S$,Ab as I$,Bb as p$,Ib as R1,Kb as j2,Mb as o$,Nb as g0,Ob as a$,xb as T2}from"./chunk-e65vyfj7.js";import{ac as E2,dc as d1,ec as V2}from"./chunk-4hawehmd.js";import{fd as EZ}from"./chunk-ybvdac8k.js";import{gd as bZ,hd as R2,id as UZ,kd as v1}from"./chunk-ah97bmns.js";import{Od as _2,Pd as U2,Sd as _Z}from"./chunk-9tnaads5.js";import{$d as l2}from"./chunk-e2s6czgg.js";import{ee as B2}from"./chunk-4dq9y7zn.js";import{Ve as PZ}from"./chunk-3aqdjrtm.js";import{if as u}from"./chunk-5s123nbs.js";import{vf as i1}from"./chunk-eqr25kxv.js";import{Df as r2,Ff as A1,Gf as J2,Hf as p0,Jf as c1,Lf as l1}from"./chunk-363pgv1e.js";import{Mf as l5}from"./chunk-g11hq0e5.js";function V0($){return $.role==="system"&&Array.isArray($.content)}function A0($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class k0{systemMessages;_contextualSystemMessages;_history;_pending=[];context;constructor($,Z){this.context=$;let W=$.messages.find(V0);if(this._contextualSystemMessages=$.messages.filter(A0),W)this.systemMessages=[W,...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((J)=>!V0(J)&&!A0(J))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!A0($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(V0);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)=>!V0(Z)&&!A0(Z))}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 B1($){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 V1($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function D1($,Z,W){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:W?$.consecutiveContinuations+1:0}}import f2 from"node:path";var hZ=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"]),IZ=/^(LD_.+|DYLD_.+|PATH)$/,j1=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function D0($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(!hZ.has(X))break;Z=K}return Z}function s6($){let Z=$;while(!0){let W=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!W)break;let J=W[1],K=W[2],Y=J.match(j1);if(!Y)break;let X=Y[1];if(IZ.test(X))break;Z=K}return Z}var pZ=[/^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 P$($){let Z=$,W=!0;while(W){W=!1;for(let J of pZ){let K=Z.match(J);if(K){Z=Z.slice(K[0].length),W=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),W=!0}return Z}function S0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){W+=z,Y=!0;continue}if(z==="'"&&!K){J=!J,W+=z;continue}if(z==='"'&&!J){K=!K,W+=z;continue}if(J||K){W+=z;continue}if(z==="|"){if(X+1<$.length&&$[X+1]==="|"){if(W.trim())Z.push(W.trim());W="",X++;continue}return null}if(z===">"||z==="<")return null;if(z==="&"&&X+1<$.length&&$[X+1]==="&"){if(W.trim())Z.push(W.trim());W="",X++;continue}if(z==="&")return null;if(z===";"){if(W.trim())Z.push(W.trim());W="";continue}W+=z}if(W.trim())Z.push(W.trim());return Z.length>0?Z:null}function w1($){let Z=!1,W=!1,J=!1;for(let K=0;K<$.length;K++){let Y=$[K];if(J){J=!1;continue}if(Y==="\\"&&!Z){J=!0;continue}if(Y==="'"&&!W){Z=!Z;continue}if(Y==='"'&&!Z){W=!W;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(W)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 j0($){let Z=[],W="",J=!1,K=!1,Y=!1;for(let X=0;X<$.length;X++){let z=$[X];if(Y){W+=z,Y=!1;continue}if(z==="\\"&&!J){if(Y=!0,K){let Q=$[X+1];if(Q&&'$`"\\'.includes(Q))continue;W+=z,Y=!1}continue}if(z==="'"&&!K){J=!J;continue}if(z==='"'&&!J){K=!K;continue}if(!J&&!K&&/[ \t]/.test(z)){if(W)Z.push(W),W="";continue}W+=z}if(W)Z.push(W);return Z}var gZ=new Set(["npm","pnpm","yarn","bun"]),q1=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),mZ=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]);function dZ($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function uZ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function cZ($,Z,W){if(!W||Z.length!==2)return;let J=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!J)return;let K=j0(J[1]??"");if(K.length!==2||K[0]!=="cd")return;let Y=K[1];if(!Y||Y==="-")return;let X=f2.isAbsolute(Y)?f2.resolve(Y):f2.resolve(W,Y);if(!T2.isWithinWorkspace(X,W))return;return J[2]?.trim()||void 0}function c2($,Z){let W=D0(uZ($)),J=S0(W);if(!J||w1(W)||/[\r\n]/.test(W))return!1;let K=J.length===1?J[0]:cZ(W,J,Z);if(!K)return!1;let Y=j0(K);if(Y.length===0||Y.some((V)=>[...mZ].some((D)=>V===D||V.startsWith(`${D}=`))))return!1;let[X,z,Q]=Y;if(gZ.has(X??""))return dZ(z==="run"?Q:z)||z==="--test";if((X==="npx"||X==="bunx")&&q1.has(z??""))return!0;if(q1.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 W7($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!f2.isAbsolute($);let W=f2.isAbsolute($)?f2.resolve($):f2.resolve(Z,$);return T2.isWithinWorkspace(W,Z)}var E$=B2("Agent"),lZ=3;function b$($,Z,W){if($!=="length")return{action:"none"};if(Z>=lZ)return{action:"truncated"};if(B1(W)==="stop")return E$.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var iZ=[/:\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],rZ=/```[\s\S]{50,}```/,G1="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",nZ=2;function _$($,Z,W=!0){if(!$||Z>=nZ)return{action:"none"};if(!W&&rZ.test($))return{action:"retry",prompt:G1};let J=$.slice(-200),K=J.match(/```/g);if(K&&K.length%2!==0)return{action:"none"};if(iZ.some((X)=>X.test(J)))return{action:"retry",prompt:G1};return{action:"none"}}var oZ=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],U1={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},aZ={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},sZ="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.",tZ="Required verification did not run successfully before the retry limit.",eZ=3;function F1($,Z,W,J){if(!W.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof W.metadata?.command==="string"&&W.metadata.exit_code===0&&c2(W.metadata.command,J)){$.add(W.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let K=W.metadata?.verificationCommands;if(!Array.isArray(K))return;for(let Y of K)if(typeof Y==="string"&&c2(Y,J))$.add(Y)}function N$($,Z,W){if(!$||!oZ.some((Q)=>Q.test($)))return{action:"none"};let J=Object.keys(U1).filter((Q)=>U1[Q].test($)),K=[...Z],Y=J.filter((Q)=>!K.some((V)=>aZ[Q].test(V)));if(J.length>0?Y.length===0:K.some((Q)=>c2(Q)))return{action:"none"};if(W>=eZ)return{action:"fail",message:tZ};let z=J.length>1&&Y.length>0?` Missing successful verification categories: ${Y.join(", ")}.`:"";return{action:"retry",prompt:`${sZ}${z}`}}var $5=[/\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|子代理|子智能体)/],L1=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function y1($){return typeof $==="string"&&L1.some((Z)=>Z.test($))}var Z5=[/\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|子代理)/],W5=[/\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 J5($){if(typeof $!=="string")return;if(W5.some((Z)=>Z.test($)))return"multiple-allowed";return Z5.some((Z)=>Z.test($))?"required":void 0}function f0($){for(let Z of $){let W=J5(Z);if(W!==void 0)return W==="required"}return!1}var K5="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.",Y5="Required delegation did not complete before the retry limit.",X5=3;function P1($,Z,W){let J=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),K=f0(J),Y=!1;if(!K)for(let X of J){if(L1.some((z)=>z.test(X)))break;if($5.some((z)=>z.test(X))){Y=!0;break}}if(J.length===0||!K&&!Y||Z.has("Task"))return{action:"none"};if(W>=X5)return{action:"fail",message:Y5};return{action:"retry",prompt:K5}}var z5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],Q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],H5=[/\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 E1($){return H5.reduce((Z,W)=>Z.replace(W," "),$)}function T0($){if(typeof $!=="string")return!1;let Z=E1($);return z5.some((W)=>W.test(Z))}var B5="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.",V5="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.",D5="Required worktree lifecycle did not complete before the retry limit.",j5=3;function b1($,Z,W){if(!$)return{action:"none"};let J=E1($);if(!T0(J))return{action:"none"};let K=Q5.some((X)=>X.test(J));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(W>=j5)return{action:"fail",message:D5};return{action:"retry",tool:Y,prompt:Y==="EnterWorktree"?B5:V5}}var O1=30000;async function A$($){try{let W=l2.getInstance().executeStopHooks({projectDir:$.workspaceRoot??u(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),J,K=new Promise((Y)=>{J=setTimeout(()=>Y("timeout"),O1)});try{let Y=await Promise.race([W,K]);if(Y==="timeout")return E$.warn(`[Loop] Stop hook 超时 (${O1}ms),按 shouldStop: true 处理`),{action:"stop"};let X=Y;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(J)}}catch(Z){return E$.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function w5($,Z){let W;while(!(W=await $.next()).done)if(Z)await Z(W.value);return W.value}var q5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G5($){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 W=Z.text;return typeof W==="string"?W:""}return""}).join(" ");return""}function U5($){let Z=$;for(let Q of q5)Z=Z.replace(Q," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let W=Z.replace(/\s+/g," ").trim();if(!W)return"";let J=W.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),K=J&&J[1].length>=6?J[1]:W;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 _1($){return U5(G5($))}import{EventEmitter as O5}from"events";import N1 from"node:path";function k$($){if(A1($.sessionId),!N1.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:N1.resolve($.projectPath)}}function w7($){let Z=k$($);return JSON.stringify([Z.projectPath,Z.sessionId])}class i2 extends O5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!i2.instance)i2.instance=new i2;return i2.instance}publish($,Z,W,J){let K=k$($);this.emit("event",{sessionId:K.sessionId,projectPath:K.projectPath,type:Z,...J!==void 0?{seq:J}:{},properties:W})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var w0=i2.getInstance();var y2=B2("Agent"),M0=new Set;async function F5($,Z){let W=$.sessionId;if(!W||$.subagentInfo)return;if(M0.has(W))return;if(M0.size>=5000)M0.clear();M0.add(W);try{let J=$.workspaceRoot,K=await S$.findSessionMetadata(W,J);if(!K)return;if(K.title&&K.title.trim())return;let Y=_1(Z);if(!Y)return;await S$.updateSessionMetadata(W,K.projectPath,{title:Y}),w0.publish({sessionId:W,projectPath:K.projectPath},"session.updated",{title:Y})}catch(J){y2.debug?.("[Loop] 自动生成会话标题失败:",J)}}var x$=`<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>`;function M2($){return $.executionEngine?.getContextManager()}async function Z2($,Z,W,J=null,K){try{let Y=M2($),X=typeof W==="string"?W.trim()!=="":W.some((z)=>z.type==="text"?z.text.trim()!=="":!0);if(Y&&Z.sessionId&&X){let z=await Y.saveMessage(Z.sessionId,"user",W,J,K,Z.subagentInfo);return F5(Z,W),z}}catch(Y){y2.warn("[Loop] 保存用户消息失败:",Y)}return null}async function M($,Z,W,J,K,Y){try{let X=M2($);if(X&&Z.sessionId&&(W.trim()||K?.trim()))return await X.saveMessage(Z.sessionId,"assistant",W,J,Y,Z.subagentInfo,K)}catch(X){y2.warn("[Loop] 保存助手消息失败:",X)}return null}async function k1($,Z,W){try{let J=M2($);if(J&&Z.sessionId)return await J.saveMessage(Z.sessionId,"system",x$,W,void 0,Z.subagentInfo)}catch(J){y2.warn("[Loop] 保存中断边界失败:",J)}return null}async function S1($,Z,W,J,K){try{let Y=M2($);if(!Y||!Z.sessionId||W.length===0)return null;return await Y.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${W.length}" />`,K,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(W.map((X)=>({...X})))),triggerPaths:[...J]},Z.subagentInfo)}catch(Y){y2.warn("[Loop] 保存 contextual project rules provenance 失败:",Y)}return null}async function f$($,Z,W,J,K){try{let Y=M2($);if(Y&&Z.sessionId)return await Y.saveToolUse(Z.sessionId,W,J,K,Z.subagentInfo)}catch(Y){y2.warn("[Loop] 保存工具调用失败:",Y)}return null}async function v0($,Z,W,J,K,Y,X,z,Q){try{let V=M2($);if(V&&Z.sessionId)return await V.saveToolResult(Z.sessionId,W,J,K,Y,X,Z.subagentInfo,z,Q)}catch(V){y2.warn("[Loop] 保存工具结果失败:",V)}return null}async function R0($,Z,W,J){try{let K=M2($);if(K&&Z.sessionId)return await K.saveCompaction(Z.sessionId,W,J,null)}catch(K){y2.warn("[Loop] 保存压缩数据失败:",K)}return null}import{createHash as S6}from"node:crypto";import{promises as S5}from"node:fs";import x5 from"node:path";import{nanoid as P2}from"nanoid";import*as g from"node:fs/promises";import*as v2 from"node:path";var x1={enabled:!0,maxIndexLines:200};var L5="memory",f1="MEMORY.md";class T${memoryDir;config;initialized=!1;constructor($,Z,W){if(W)this.memoryDir=W;else{let J=r2($);this.memoryDir=v2.join(J,L5)}this.config={...x1,...Z}}async initialize(){if(this.initialized)return;await g.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=v2.join(this.memoryDir,f1);try{let Z=await g.readFile($,"utf-8");if(!Z.trim())return null;let W=Z.split(`
4
4
  `),K=W.slice(0,this.config.maxIndexLines).join(`
@@ -1 +1 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-qdf7sb0k.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-tgtj3bj1.js";import"./chunk-h9k52syw.js";import"./chunk-wpjb7918.js";import"./chunk-z18bbtg9.js";import"./chunk-p4zt7ts9.js";import"./chunk-yg2bd4w2.js";import"./chunk-095x2ykj.js";import"./chunk-93pn0vhs.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as q}from"./chunk-gqrrheb3.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-230xac12.js";import"./chunk-5df4x6ec.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
1
+ import{f as y,g as A,h as C,i as D}from"./chunk-p5zstj8j.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-tadbcnwr.js";import"./chunk-vszmbnjh.js";import"./chunk-pqgw6t9b.js";import"./chunk-9e8fyt60.js";import"./chunk-p4zt7ts9.js";import"./chunk-21zwc98r.js";import"./chunk-095x2ykj.js";import"./chunk-e65vyfj7.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as q}from"./chunk-z24sj1r8.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-63rg3mhn.js";import"./chunk-evn886hs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-z18bbtg9.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-gqrrheb3.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as k}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-9e8fyt60.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-z24sj1r8.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as k}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1 +1 @@
1
- import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-yg2bd4w2.js";import"./chunk-095x2ykj.js";import"./chunk-93pn0vhs.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-21zwc98r.js";import"./chunk-095x2ykj.js";import"./chunk-e65vyfj7.js";import"./chunk-4hawehmd.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-8j01ssaf.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,2 +1,2 @@
1
- import{Se as F}from"./chunk-1qz9qfzc.js";import{mf as D,nf as E}from"./chunk-s5666ta0.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{Se as F}from"./chunk-pz21tcah.js";import{mf as D,nf as E}from"./chunk-s5666ta0.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as qd,Q as rd,T as sd};
@@ -1,4 +1,4 @@
1
- import{f as Q,g as R,h as T,i as W}from"./chunk-qdf7sb0k.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-tgtj3bj1.js";import"./chunk-h9k52syw.js";import"./chunk-wpjb7918.js";import"./chunk-z18bbtg9.js";import"./chunk-p4zt7ts9.js";import"./chunk-yg2bd4w2.js";import"./chunk-095x2ykj.js";import"./chunk-93pn0vhs.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-gqrrheb3.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-230xac12.js";import"./chunk-5df4x6ec.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import{vf as J}from"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import b from"chalk";import H from"open";var $=`
1
+ import{f as Q,g as R,h as T,i as W}from"./chunk-p5zstj8j.js";import"./chunk-r76wc1cn.js";import"./chunk-z8c5rhdh.js";import"./chunk-tadbcnwr.js";import"./chunk-vszmbnjh.js";import"./chunk-pqgw6t9b.js";import"./chunk-9e8fyt60.js";import"./chunk-p4zt7ts9.js";import"./chunk-21zwc98r.js";import"./chunk-095x2ykj.js";import"./chunk-e65vyfj7.js";import"./chunk-4hawehmd.js";import"./chunk-ktf3bpmw.js";import{Vc as M}from"./chunk-z24sj1r8.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-63rg3mhn.js";import"./chunk-evn886hs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import{vf as J}from"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import b from"chalk";import H from"open";var $=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1 +1 @@
1
- import{Jd as a,Kd as b,Ld as c,Md as d,Nd as e}from"./chunk-5df4x6ec.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-brwths02.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
1
+ import{Jd as a,Kd as b,Ld as c,Md as d,Nd as e}from"./chunk-evn886hs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-e2s6czgg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
@@ -1,4 +1,4 @@
1
- import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-1qz9qfzc.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.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-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-5b7xhvd1.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-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-pz21tcah.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.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-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-cscm57tr.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,2 +1,2 @@
1
- import{vf as d,xf as h}from"./chunk-jvfzm6gn.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{vf as d,xf as h}from"./chunk-eqr25kxv.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as sc,w as tc};
@@ -1,4 +1,4 @@
1
- import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-brwths02.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-1qz9qfzc.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-jvfzm6gn.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-e2s6czgg.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-pz21tcah.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-eqr25kxv.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1 +1 @@
1
- import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-93pn0vhs.js";import"./chunk-4hawehmd.js";import"./chunk-8j01ssaf.js";import"./chunk-heqs3xan.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-dsj62dcg.js";import"./chunk-jvfzm6gn.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
1
+ import{$b as f,Wb as a,Xb as b,Yb as c,Zb as d,_b as e}from"./chunk-e65vyfj7.js";import"./chunk-4hawehmd.js";import"./chunk-8j01ssaf.js";import"./chunk-heqs3xan.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-dsj62dcg.js";import"./chunk-eqr25kxv.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -25,7 +25,7 @@ import{ae as YO}from"./chunk-7wjy6kgt.js";import{ee as XO}from"./chunk-4dq9y7zn.
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-xm9katxj.js"),{createChatServiceAsync:J}=await import("./chunk-9cnm1hgp.js"),{resolveModelConfig:W}=await import("./chunk-z5zcwwfm.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-sxcm8ryt.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal)).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-vaxcmm72.js"),{createChatServiceAsync:J}=await import("./chunk-9cnm1hgp.js"),{resolveModelConfig:W}=await import("./chunk-z5zcwwfm.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-vdgskayb.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1,4 +1,4 @@
1
- import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-jvfzm6gn.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
1
+ import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-eqr25kxv.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
2
2
  `,"utf8"),!0}catch(L){if(F0(L,"EEXIST"))return!1;if(G)await I.unlink($).catch(()=>{return});throw L}finally{await G?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=H$()){let G=Yq(q,$),L={version:X$,sessionId:$,ownerId:Bq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await I.mkdir(X0.dirname(G),{recursive:!0,mode:448}),await F$(G,L))return new i(G,L);let J=await N$(G);if(J&&Nq(J.pid))throw new n(J.pid);if(await I.unlink(G).catch((Z)=>{if(!F0(Z,"ENOENT"))throw Z}),await F$(G,L))return new i(G,L);throw new n((await N$(G))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await S0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}function Fq($,q){for(let G of $){if(G.type!=="part_created"||G.data.partType!=="tool_result")continue;let L=G.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let J=L;if(J.toolCallId===q||G.data.partId===q||G.data.messageId===q)return J}return}function W$($){let q=u($),G=new Map;for(let L of q){if(L.type==="interaction_requested"){G.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let J=G.get(L.data.requestId);if(J)J.response=L.data;continue}if(L.type==="interaction_recovered"){let J=G.get(L.data.requestId);if(J)J.recovery=L.data}}for(let L of G.values()){let J=Fq(q,L.request.toolCallId);L.hasToolResult=J!==void 0;let Z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;L.hasRecoveryToolResult=Z?.interactionRecovery===!0&&Z.requestId===L.request.requestId}return[...G.values()]}function T$($){return W$($).reverse().find((q)=>!q.response&&!q.recovery)}function z1($){let q=new Map;for(let G of W$($))q.set(G.request.toolCallId,G);return[...q.values()].filter((G)=>G.response&&!G.recovery&&(!G.hasToolResult||G.hasRecoveryToolResult))}function U$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function W0($){let q=new Map,G=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))G.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let J=q.get(L.data.reviewId);if(J&&J.completion===void 0)J.completion=L.data}return G.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function _1($){return W0($).reverse().find((q)=>q.completion===void 0)}function m0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O$($,q){let G=["## Code Review","",`Target: ${$.target.label}`,`Status: ${m0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)G.push("","No actionable findings.");else{G.push("","### Findings");for(let[L,J]of q.findings.entries()){let Z=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;G.push("",`${L+1}. ${J.title}`,` ${J.codeLocation.path}:L${Z} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)G.push("",`Error: ${q.error}`);return G.join(`
3
3
  `)}function C$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((G)=>({title:G.title,body:G.body,priority:G.priority,confidenceScore:G.confidenceScore,codeLocation:{...G.codeLocation}})),...q.error?{error:q.error}:{}}}var I0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Hq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Xq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function Wq($){return{code:$,...I0[$]}}function v0($){return Wq(Xq(Hq($)))}function P0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in I0))return!1;let G=I0[q.code];return q.message===G.message&&q.retryable===G.retryable}import{promises as G0,realpathSync as Uq}from"node:fs";import T0 from"node:path";import*as o from"fs/promises";import*as O from"path";var z$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class u0{static normalize($,q){let G=O.isAbsolute($)?$:O.resolve(q,$),L=O.normalize(G),J=O.normalize(q);if(!this.isWithinWorkspace(L,J))throw new d(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(O.sep);for(let G of z$)if(q.includes(G))throw new d(`Access denied: "${G}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let G=this.normalize($,q);this.checkRestricted(G);try{await o.access(G)}catch(L){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return G}static async resolveSymlink($,q){try{let G=await o.realpath($),L=await o.realpath(q);if(!this.isWithinWorkspace(G,L))throw new d(`Symlink points outside workspace: ${$} -> ${G}`,"SYMLINK_OUTSIDE_WORKSPACE");return G}catch(G){if(G instanceof d)throw G;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let G=O.resolve($),L=O.resolve(q),J=O.relative(L,G);return J===""||J!==".."&&!J.startsWith(`..${O.sep}`)&&!O.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let G=O.resolve(q),L=O.isAbsolute($)?O.resolve($):O.resolve(G,$);if(!this.isWithinWorkspace(L,G))return!1;let J;try{J=await o.realpath(G)}catch{return!1}let Z=L;while(!0){try{let V=await o.realpath(Z);return this.isWithinWorkspace(V,J)}catch(V){let B=V.code;if(B!=="ENOENT"&&B!=="ENOTDIR")return!1}let Q=O.dirname(Z);if(Q===Z)return!1;Z=Q}}static isRestricted($){let q=$.split(O.sep);return z$.some((G)=>q.includes(G))}}var L0=U0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let G=await G0.stat($),L={filePath:T0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),L0.debug(`记录文件读取: ${$}`)}catch(G){L0.warn(`记录文件读取失败: ${$}`,G)}}async recordFileEdit($,q,G="edit"){try{let L=await G0.stat($),J={filePath:T0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:G};this.setRecord(J),await this.recordAliases($,J.filePath),L0.debug(`记录文件${G==="edit"?"编辑":"写入"}: ${$}`)}catch(L){L0.warn(`记录文件${G==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return!1;return q?G.has(q):G.size>0}async checkFileModification($,q){let G=this.getFileRecord($,q);if(!G)return{modified:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(Math.abs(L.mtimeMs-G.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(G.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let G=this.getFileRecord($,q);if(!G)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(L.mtimeMs-G.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(G.accessTime).toISOString()} (${G.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return L0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return;if(q)return G.get(q);return[...G.values()].sort((L,J)=>J.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let G=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(G),this.removeAliases(G);return}let L=this.accessedFiles.get(G);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[G,L]of this.accessedFiles.entries()){if(q&&!u0.isWithinWorkspace(G,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(T0.resolve($),q);let G=await G0.realpath($).catch(()=>{return});if(G)this.pathAliases.set(G,q)}resolveTrackedPath($){let q=T0.resolve($);if(this.accessedFiles.has(q))return q;let G=this.pathAliases.get(q);if(G)return G;try{let L=Uq.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,G]of this.pathAliases)if(G===$)this.pathAliases.delete(q)}}import*as Z0 from"node:crypto";import{promises as X}from"node:fs";import*as T from"node:path";import h0 from"write-file-atomic";var D$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(f($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!T.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?T.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=J0();this.snapshotDir=T.join(q,"file-history",this.sessionId),this.manifestPath=T.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await X.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=J0(),q=await X.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),G=Z0.createHash("sha256").update(q).digest("hex").slice(0,24),L=T.join($,"file-history",this.sessionId),J=T.join($,"file-history","workspaces",G,this.sessionId),Z=T.join(J,"manifest.json");try{await X.access(Z)}catch{await this.migrateLegacySnapshotDir(L,J,q)}this.snapshotDir=J,this.manifestPath=Z}async migrateLegacySnapshotDir($,q,G){let L;try{L=JSON.parse(await X.readFile(T.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,G)))return;await X.mkdir(T.dirname(q),{recursive:!0,mode:493});try{await X.rename($,q)}catch(J){let Z=J.code;if(Z!=="ENOENT"&&Z!=="EEXIST"&&Z!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!T.isAbsolute($))return!1;let G=T.relative(q,T.resolve($));return G===""||G!==".."&&!G.startsWith(`..${T.sep}`)&&!T.isAbsolute(G)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let G=await this.resolveFileIdentity($),L=!0;try{await X.access(G)}catch{L=!1}let J=this.trackedFileBackups.get(G),Z=J?J.version+1:1,Q=this.generateFileHash(G,Z),V=this.getSnapshotPath(Q,Z),B=new Date;if(L){let K=await X.readFile(G);await X.writeFile(V,K)}let x={backupFileName:Q,version:Z,backupTime:B};return this.trackedFileBackups.set(G,x),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:B,filePath:G,version:Z,existedBefore:L}),await this.cleanupOldSnapshots(G),await this.persistManifest(),x}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${G}`);L.postEditHash=await this.hashFile(G),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)return;this.removeSnapshot(L),await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((Z)=>Z.filePath===q&&Z.postEditHash!==void 0);if(!G?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==G.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(q),{recursive:!0}),await X.writeFile(q,Z)}else await X.rm(q,{force:!0});return this.removeSnapshot(G),await X.rm(J,{force:!0}),await this.persistManifest(),G}async restoreSnapshot($,q){let G=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((Z)=>Z.messageId===q&&Z.filePath===G);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${G}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(G),{recursive:!0}),await X.writeFile(G,Z)}else await X.rm(G,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((G)=>G.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,L)=>G+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let G=new Map;for(let J of q){let Z,Q=!0;try{Z=await X.readFile(J.filePath)}catch(B){if(B.code!=="ENOENT")throw B;Q=!1}if((Z?Z0.createHash("sha256").update(Z).digest("hex"):D$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(G.set(J.filePath,{existed:Q,content:Z}),J.target.existedBefore)await X.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let L=[...this.snapshots];try{for(let Z of q)if(Z.target.existedBefore){let Q=await X.readFile(this.getSnapshotPath(Z.target.backupFileName,Z.target.version));await X.mkdir(T.dirname(Z.filePath),{recursive:!0}),await h0(Z.filePath,Q)}else await X.rm(Z.filePath,{force:!0});let J=new Set(q.flatMap((Z)=>Z.selected));this.snapshots=this.snapshots.filter((Z)=>!J.has(Z)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((Z)=>X.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=L,this.rebuildTrackedFileBackups();let Z=[];for(let[Q,V]of G)try{if(V.existed&&V.content)await h0(Q,V.content);else await X.rm(Q,{force:!0})}catch(B){Z.push(B)}if(Z.length>0)throw AggregateError([J,...Z],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,Z)=>J+Z.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),G=new Set(q.flatMap((J)=>J.selected));if(G.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!G.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=L,this.rebuildTrackedFileBackups(),J}return await Promise.all([...G].map((J)=>X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:G.size}}buildRewindPlan($){let q=new Set($),G=this.snapshots.filter((Z)=>Z.postEditHash!==void 0),L=G.filter((Z)=>q.has(Z.messageId));return[...new Set(L.map((Z)=>Z.filePath))].sort().map((Z)=>{let Q=G.filter((K)=>K.filePath===Z),V=Q.filter((K)=>q.has(K.messageId)),B=Q.indexOf(V[0]),x=Q.slice(B);if(x.length!==V.length||x.some((K)=>!q.has(K.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${Z}`);return{filePath:Z,selected:V,target:V[0],latest:V.at(-1)}})}async loadManifest(){try{let $=await X.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(G)=>({...G,filePath:await this.resolveFileIdentity(G.filePath),timestamp:new Date(G.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await X.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await h0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let G=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of G)await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,J)=>J.timestamp.getTime()-L.timestamp.getTime()),G=new Set(q.slice(0,$));for(let L of this.snapshots)if(!G.has(L))await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return T.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=T.resolve($),G=[],L=q;while(!0){try{let Z=await X.realpath(L);return T.join(Z,...G.reverse())}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw Z}let J=T.dirname(L);if(J===L)return q;G.push(T.basename(L)),L=J}}async hashFile($){try{let q=await X.readFile($);return Z0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return D$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let G=Z0.createHash("md5");return G.update(`${$}:${q}`),G.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as Oq}from"node:crypto";import Cq from"ajv";var E$="StructuredOutput",_$=65536,R$=131072,v1=2,f$=20,M$=1000,A$=200;function r($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function b$($,q){if(!r($))throw Error(`${q} must be a JSON object`);let G;try{G=JSON.stringify($)}catch(J){throw Error(`${q} must be JSON-serializable`,{cause:J})}if(G===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(G);if(!r(L))throw Error(`${q} must be a JSON object`);return L}function zq($){let q=0,G=0,L=(J,Z)=>{if(q++,q>M$)throw Error(`Output schema exceeds the ${M$} node complexity limit`);if(Z>f$)throw Error(`Output schema exceeds the ${f$} level depth limit`);if(Array.isArray(J)){for(let Q of J)L(Q,Z+1);return}if(!r(J))return;if("$ref"in J){let Q=J.$ref;if(typeof Q!=="string"||!(Q==="#"||Q.startsWith("#/$defs/")||Q.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in J&&r(J.properties)){if(G+=Object.keys(J.properties).length,G>A$)throw Error(`Output schema exceeds the ${A$} property limit`)}for(let Q of Object.values(J))L(Q,Z+1)};L($,0)}function Dq($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function _q($){let q=new Cq({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(G){throw Error(`Invalid output schema: ${G instanceof Error?G.message:String(G)}`)}}function k$($){let q=b$($,"Output schema"),G=JSON.stringify(q);if(Buffer.byteLength(G)>_$)throw Error(`Output schema exceeds ${_$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');zq(q);let J=_q(q),Z=Oq("sha256").update(G).digest("hex");return{schema:q,schemaDigest:Z,declaration:{name:E$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(Q){let V;try{V=b$(Q,"Structured output")}catch(x){return{success:!1,message:x instanceof Error?x.message:String(x)}}let B=JSON.stringify(V);if(Buffer.byteLength(B)>R$)return{success:!1,message:`Structured output exceeds ${R$} bytes`};if(!J(V))return{success:!1,message:Dq(J.errors)};return{success:!0,output:V}}}}function w$($,q){if(!r($))return;let G=r($.structuredOutput)?$.structuredOutput:$;if(G.schemaDigest!==q.schemaDigest||!("output"in G))return;let L=q.validate(G.output);return L.success?L.output:void 0}function P1($,q){for(let G=$.length-1;G>=0;G--){let L=$[G];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let Q=w$(L.metadata,q);if(Q)return{output:Q,completed:!0};continue}if(L.role!=="tool"||L.name!==E$)continue;let J=r(L.metadata)?L.metadata:void 0,Z=w$(J?.metadata,q);if(Z)return{output:Z,completed:!1}}return}import{createHash as mq}from"node:crypto";import u$ from"node:path";import{StringDecoder as Aq}from"node:string_decoder";function Rq($,q){let G=q;while(G<$.length&&($[G]&192)===128)G+=1;return G}class c0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let G=Rq($,q);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G}}}var C0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},a={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},g$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},fq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:C0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:C0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:a,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:g$},{pattern:/^git\s+(status|branch|remote)/i,config:a},{pattern:/^git\s+(log|diff|show)/i,config:g$},{pattern:/^(ls|dir|tree)\s+/i,config:a,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:C0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:C0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:a,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:a,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class l0{static getConfigForCommand($){for(let{pattern:q,config:G,summaryTemplate:L}of Mq)if(q.test($))return{config:G,summaryTemplate:L};return{config:fq}}static truncate($,q){let{config:G,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,G,L)}static truncateWithConfig($,q,G){let L=$.length,J=$.split(`
4
4
  `),Z=J.length;if(Z<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:Z,originalChars:L};let Q=J.slice(0,q.keepHead),V=J.slice(-q.keepTail),B=Z-q.keepHead-q.keepTail,x=Q.join(`
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.10.11",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.10.12",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
2
2
  export{i as uf,n as vf,o as wf,c as xf,a as yf,d as zf};
@@ -1,4 +1,4 @@
1
- import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-brwths02.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-1qz9qfzc.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-jvfzm6gn.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-e2s6czgg.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-pz21tcah.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-eqr25kxv.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,4 +1,4 @@
1
- import{xc as I}from"./chunk-632rgzcf.js";import{Qc as A}from"./chunk-gqrrheb3.js";import{ee as h}from"./chunk-4dq9y7zn.js";import{Ie as f,Me as T,Ne as w,Oe as M,Pe as P,Se as k,Te as E}from"./chunk-1qz9qfzc.js";import{Ue as c,Ve as y}from"./chunk-3aqdjrtm.js";import{Ye as S,_e as n,bf as p}from"./chunk-kvx3sb3z.js";import{gf as O}from"./chunk-5s123nbs.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
1
+ import{xc as I}from"./chunk-632rgzcf.js";import{Qc as A}from"./chunk-z24sj1r8.js";import{ee as h}from"./chunk-4dq9y7zn.js";import{Ie as f,Me as T,Ne as w,Oe as M,Pe as P,Se as k,Te as E}from"./chunk-pz21tcah.js";import{Ue as c,Ve as y}from"./chunk-3aqdjrtm.js";import{Ye as S,_e as n,bf as p}from"./chunk-kvx3sb3z.js";import{gf as O}from"./chunk-5s123nbs.js";import{promises as R}from"node:fs";import C from"node:path";var U=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],x=new Set([...Object.keys(f),...U]),m=n.Number({exclusiveMinimum:0}),e=n.String({minLength:1}),r=n.Array(n.String()),B=n.Object({currentModelId:n.Optional(n.String()),modelProviders:n.Optional(n.Record(e,n.Object({name:e,baseUrl:e,wireApi:p(["openai-completions","anthropic-messages"]),apiKeyEnv:n.Optional(e)}))),models:n.Optional(n.Array(n.Object({id:e,displayName:n.Optional(e),provider:e,model:e,overrides:n.Optional(n.Object({baseUrl:n.Optional(n.String()),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),timeout:n.Optional(m),streamIdleTimeout:n.Optional(n.Number({minimum:1000})),apiVersion:n.Optional(n.String()),customHeaders:n.Optional(n.Record(n.String(),n.String())),maxRetries:n.Optional(n.Integer({minimum:0})),enablePromptCaching:n.Optional(n.Boolean())})),fallbackModels:n.Optional(n.Array(n.Object({provider:e,model:e})))}))),temperature:n.Optional(n.Number()),maxOutputTokens:n.Optional(m),stream:n.Optional(n.Boolean()),topP:n.Optional(n.Number()),topK:n.Optional(n.Number()),timeout:n.Optional(m),theme:n.Optional(n.String()),uiTheme:n.Optional(p(["light","dark","system"])),language:n.Optional(n.String()),fontSize:n.Optional(m),autoSaveSessions:n.Optional(n.Boolean()),notifyBuild:n.Optional(n.Boolean()),notifyErrors:n.Optional(n.Boolean()),notifySounds:n.Optional(n.Boolean()),privacyTelemetry:n.Optional(n.Boolean()),privacyCrash:n.Optional(n.Boolean()),debug:n.Optional(n.Union([n.Boolean(),n.String()])),mcpEnabled:n.Optional(n.Boolean()),mcpServers:n.Optional(n.Record(n.String(),n.Record(n.String(),n.Unknown()))),lspServers:n.Optional(n.Record(e,n.Object({command:e,args:n.Optional(n.Array(n.String())),extensionToLanguage:n.Record(e,e),env:n.Optional(n.Record(n.String(),n.String())),initializationOptions:n.Optional(n.Unknown()),settings:n.Optional(n.Unknown()),enabled:n.Optional(n.Boolean()),priority:n.Optional(n.Integer()),startupTimeout:n.Optional(n.Integer({minimum:100})),shutdownTimeout:n.Optional(n.Integer({minimum:100})),requestTimeout:n.Optional(n.Integer({minimum:100})),diagnosticWaitTimeout:n.Optional(n.Integer({minimum:0})),maxRestarts:n.Optional(n.Integer({minimum:0,maximum:10}))}))),permissionMode:n.Optional(n.Enum(c)),maxTurns:n.Optional(n.Integer({minimum:-1,maximum:y})),maxConcurrentTasks:n.Optional(n.Integer({minimum:T,maximum:w})),maxQueuedTasks:n.Optional(n.Integer({minimum:M,maximum:P})),systemPrompt:n.Optional(n.String()),appendSystemPrompt:n.Optional(n.String()),initialMessage:n.Optional(n.String()),resumeSessionId:n.Optional(n.String()),forkSession:n.Optional(n.Boolean()),allowedTools:n.Optional(n.Array(e)),disallowedTools:n.Optional(n.Array(e)),mcpConfigPaths:n.Optional(n.Array(e)),strictMcpConfig:n.Optional(n.Boolean()),model:n.Optional(e),addDirs:n.Optional(n.Array(e)),outputFormat:n.Optional(p(["text","json","stream-json","jsonl"])),inputFormat:n.Optional(p(["text","stream-json"])),print:n.Optional(n.Boolean()),includePartialMessages:n.Optional(n.Boolean()),replayUserMessages:n.Optional(n.Boolean()),agentsConfig:n.Optional(n.String()),settingSources:n.Optional(n.String()),permissions:n.Optional(n.Object({allow:n.Optional(r),ask:n.Optional(r),deny:n.Optional(r)})),env:n.Optional(n.Record(n.String(),n.String())),hooks:n.Optional(n.Record(n.String(),n.Unknown())),enabledPlugins:n.Optional(n.Record(e,n.Boolean())),pluginSourcePolicy:n.Optional(n.Object({restrictToAllowedSources:n.Optional(n.Boolean()),requireGitCommitSha:n.Optional(n.Boolean()),allowedGitHosts:n.Optional(n.Array(e)),allowedMarketplaces:n.Optional(n.Array(e)),allowedLocalRoots:n.Optional(n.Array(e))})),disableAllHooks:n.Optional(n.Boolean())}),_=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"]];function d(o,i){let t;try{t=JSON.parse(o)}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Invalid JSON provided to --settings (${i})${a}`)}if(!t||typeof t!=="object"||Array.isArray(t))throw Error("--settings must contain a JSON object");for(let s of Object.keys(t))if(!x.has(s))throw Error(`Unknown --settings field: ${s}`);let l=S(B,t);if(!l.success){let s=l.error.issues.map((a)=>`${a.path.join(".")||"settings"}: ${a.message}`).join("; ");throw Error(`Invalid --settings value: ${s}`)}return l.data}async function N(o){if(o===void 0)return;let i=o.trim();if(!i)throw Error("--settings requires a JSON object or file path");if(i.startsWith("{"))return d(i,"inline JSON");let t=C.resolve(O(),i),l;try{l=await R.readFile(t,"utf8")}catch(s){let a=s instanceof Error?`: ${s.message}`:"";throw Error(`Unable to read --settings file ${t}${a}`)}return d(l,t)}function b(o,i){if(!i)return;let t=i;for(let[l,s]of _){if(l==="permissionMode"&&o.yolo===!0)continue;if(o[s]===void 0&&t[l]!==void 0)o[s]=t[l]}}var u=h("General"),Z=(o)=>{if(o.yolo){if(o.permissionMode&&o.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");o.permissionMode="yolo"}if(Array.isArray(o.allowedTools))o.allowedTools=o.allowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.disallowedTools))o.disallowedTools=o.disallowedTools.flatMap((i)=>i.split(",").map((t)=>t.trim()).filter((t)=>t.length>0));if(Array.isArray(o.allowedTools)&&Array.isArray(o.disallowedTools)){let i=o.allowedTools.filter((t)=>o.disallowedTools.includes(t));if(i.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${i.join(", ")}`)}},g=async(o)=>{let i=await N(typeof o.settings==="string"?o.settings:void 0);if(b(o,i),typeof o.agents==="string")I(o.agents);F(o);try{let l=await k.getInstance().initialize(i),s=E(l,o);if(A().config.actions.setConfig(s),o.debug)u.info("[CLI] 配置已加载到 Store")}catch(t){u.error("[CLI] [FAIL] 配置初始化失败",t instanceof Error?t.message:t),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",t instanceof Error?t.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1,4 +1,4 @@
1
- import{$ as F,Z as y}from"./chunk-wpjb7918.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-93pn0vhs.js";import{Ld as $}from"./chunk-5df4x6ec.js";import{if as K}from"./chunk-5s123nbs.js";async function O(){await $(K())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{$ as F,Z as y}from"./chunk-pqgw6t9b.js";import{$b as Q,Lb as Z,Nb as x}from"./chunk-e65vyfj7.js";import{Ld as $}from"./chunk-evn886hs.js";import{if as K}from"./chunk-5s123nbs.js";async function O(){await $(K())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let V of z)G.push(V);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:K(),surface:"headless",workspaceRoot:K()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:V}=z;return{mode:"agent",content:V?`Please use the "${G}" skill to help me with: ${V}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function P(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await Q.loadSession(b,K())}catch(q){if(J(q))return null;throw q}}async function T(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=K();return Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}let[q,z]=await Promise.all([Q.loadSession(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:K()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=K();return Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G})}return{sessionId:z,messages:await Q.loadSession(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,K())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{O as m,j as n,I as o,P as p,T as q};