blade-code 0.10.46 → 0.10.47

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 (50) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-yvyqhw5q.js → chunk-0b1qj502.js} +1 -1
  3. package/dist/{chunk-yha9fpc7.js → chunk-12akr5tm.js} +1 -1
  4. package/dist/{chunk-sh58bey1.js → chunk-1906ftqm.js} +1 -1
  5. package/dist/{chunk-ssymrsyx.js → chunk-1h9pcmkk.js} +1 -1
  6. package/dist/{chunk-8kzdhgys.js → chunk-26p6t5f2.js} +1 -1
  7. package/dist/{chunk-qbvm38ba.js → chunk-4ntsj9x5.js} +1 -1
  8. package/dist/{chunk-xes0szvj.js → chunk-5wjnbhpg.js} +2 -2
  9. package/dist/chunk-5x4v6tkt.js +1 -0
  10. package/dist/{chunk-vhamhbej.js → chunk-64z1vsd7.js} +4 -4
  11. package/dist/{chunk-qmxfkkgn.js → chunk-6pz076m9.js} +1 -1
  12. package/dist/{chunk-9mnbnyrc.js → chunk-6tcagnpd.js} +1 -1
  13. package/dist/{chunk-mqmf40p2.js → chunk-74nmcybn.js} +1 -1
  14. package/dist/{chunk-4dthhzfe.js → chunk-7pprh90t.js} +1 -1
  15. package/dist/chunk-85d5jmk3.js +1 -0
  16. package/dist/{chunk-ecf8dh3c.js → chunk-94zrzfyz.js} +15 -15
  17. package/dist/{chunk-j66r48pz.js → chunk-b29dn3xe.js} +1 -1
  18. package/dist/{chunk-fz91aw1w.js → chunk-b76w8nsk.js} +1 -1
  19. package/dist/{chunk-6h28xs47.js → chunk-cwcngsfq.js} +1 -1
  20. package/dist/{chunk-sjtbp01y.js → chunk-de1s7f6p.js} +1 -1
  21. package/dist/{chunk-67zpsrst.js → chunk-e8zc6vbq.js} +1 -1
  22. package/dist/{chunk-s5205dnv.js → chunk-hr79r0ee.js} +1 -1
  23. package/dist/{chunk-5vbrcvxg.js → chunk-k2wnxzdx.js} +1 -1
  24. package/dist/{chunk-2yjm55cb.js → chunk-k5f4kx9z.js} +1 -1
  25. package/dist/{chunk-jmksywff.js → chunk-kr5wj66e.js} +1 -1
  26. package/dist/{chunk-sztrmhgd.js → chunk-nvjkw9e5.js} +1 -1
  27. package/dist/{chunk-szdcprq7.js → chunk-nxcc0fbe.js} +1 -1
  28. package/dist/{chunk-yrd794kb.js → chunk-pgz8t0mk.js} +1 -1
  29. package/dist/{chunk-807x1cw8.js → chunk-pxqgt2h6.js} +1 -1
  30. package/dist/{chunk-n5dkq98k.js → chunk-rcjpv1qs.js} +37 -37
  31. package/dist/{chunk-cyw6cpac.js → chunk-sx4mkt0c.js} +1 -1
  32. package/dist/{chunk-aarwre5y.js → chunk-t1wxd1hj.js} +1 -1
  33. package/dist/{chunk-t4y3h47y.js → chunk-v287pexf.js} +1 -1
  34. package/dist/{chunk-7qpbtnsa.js → chunk-va43bd74.js} +1 -1
  35. package/dist/{chunk-v6ydjg9c.js → chunk-xwe22whb.js} +1 -1
  36. package/dist/{chunk-4qvna4m2.js → chunk-yp1vvxyc.js} +1 -1
  37. package/dist/{chunk-8y3skwtt.js → chunk-yre5973e.js} +1 -1
  38. package/dist/{chunk-1atpfmpe.js → chunk-z699m84q.js} +2 -2
  39. package/dist/web/assets/{ChatView-CyxiCTbL.js → ChatView-DsPSY2pr.js} +2 -2
  40. package/dist/web/assets/{CodeBlockHighlighter-Bb3gIeQv.js → CodeBlockHighlighter-D5L0d-8-.js} +1 -1
  41. package/dist/web/assets/{FilePreview-BXg9VaTv.js → FilePreview-Cb2olorI.js} +1 -1
  42. package/dist/web/assets/{MarkdownRenderer-vxpqGt4L.js → MarkdownRenderer-7ymM1e5M.js} +3 -3
  43. package/dist/web/assets/{SettingsModal-4L1nPkh0.js → SettingsModal-D6hLNUk9.js} +1 -1
  44. package/dist/web/assets/{TaskSwitcher-DKSqTLK1.js → TaskSwitcher-DAAp5x-y.js} +1 -1
  45. package/dist/web/assets/{TerminalPanel-Bv9PDclr.js → TerminalPanel-BpDMAo49.js} +1 -1
  46. package/dist/web/assets/{index-Bz4W1-8a.js → index-BdsO44FI.js} +6 -6
  47. package/dist/web/index.html +1 -1
  48. package/package.json +1 -1
  49. package/dist/chunk-54d7545y.js +0 -1
  50. package/dist/chunk-vhxtzacr.js +0 -1
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{dd as W}from"./chunk-szdcprq7.js";import{gd as F,hd as M}from"./chunk-fk4wbmv6.js";import"./chunk-ecf8dh3c.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{cg as N,dg as B}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Dg as T}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as J}from"./chunk-hfrcwkc8.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-sh58bey1.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-aarwre5y.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3y784b9c.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-7qpbtnsa.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-jmksywff.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-qmxfkkgn.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-vhxtzacr.js"),import("./chunk-v6ydjg9c.js"),import("./chunk-xes0szvj.js"),import("./chunk-c9s4n31b.js"),import("./chunk-2yjm55cb.js"),import("./chunk-2eddqgnh.js"),import("./chunk-9rrced3b.js"),import("./chunk-qbvm38ba.js"),import("./chunk-yrd794kb.js"),import("./chunk-fz91aw1w.js")]),A=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),p&&Z.stack)console.error(`
2
+ import{dd as W}from"./chunk-nxcc0fbe.js";import{gd as F,hd as M}from"./chunk-fk4wbmv6.js";import"./chunk-94zrzfyz.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-0b1qj502.js";import"./chunk-cxzx7j0p.js";import"./chunk-sx4mkt0c.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{cg as N,dg as B}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Dg as T}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as J}from"./chunk-hfrcwkc8.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function c(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function m(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function t(){if(c(E)){let{getVersion:K}=await import("./chunk-1906ftqm.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-t1wxd1hj.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-3y784b9c.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-va43bd74.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-kr5wj66e.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-6pz076m9.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-85d5jmk3.js"),import("./chunk-xwe22whb.js"),import("./chunk-5wjnbhpg.js"),import("./chunk-c9s4n31b.js"),import("./chunk-k5f4kx9z.js"),import("./chunk-2eddqgnh.js"),import("./chunk-9rrced3b.js"),import("./chunk-4ntsj9x5.js"),import("./chunk-pgz8t0mk.js"),import("./chunk-b76w8nsk.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-54d7545y.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-n5dkq98k.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-5x4v6tkt.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-rcjpv1qs.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};
@@ -25,7 +25,7 @@ import{Ne as YO}from"./chunk-cxzx7j0p.js";import{Tf as qO,Vf as S,Yf as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let J of O)try{let W=await this.executeHook(J,q,Q);if(!W.success){if(W.warning)Y.push(W.warning);continue}if(W.output?.suppressOutput){$=!0;break}if(W.stdout&&W.stdout.trim())X=W.stdout.trim()}catch(W){let G=W instanceof Error?W.message:String(W);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-sztrmhgd.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-9mnbnyrc.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let R=this.sessionModelResources.get(Q)??await G(q.projectDir,L),F=O?R.config.models.find((B)=>B.id===O):R.config.models.find((B)=>B.id===R.config.currentModelId)??R.config.models[0];if(!F)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await J(W(F,R.config,"off",R.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${jO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=DO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),J=JSON.stringify(q,null,2),W=new AbortController,G=setTimeout(()=>W.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:J}],void 0,W.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(F){if(W.signal.aborted||F instanceof Error&&F.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw F}finally{clearTimeout(G)}let R=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:R,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,J=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),W=()=>{if(X)return;X=!0,clearTimeout(J),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",W,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(J),Q.abortSignal?.removeEventListener("abort",W),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},J=JSON.stringify(q),W;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,R=setTimeout(()=>L.abort(),Z),F=()=>L.abort();Q.abortSignal?.addEventListener("abort",F,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:J,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){W=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(W=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let P={stdout:await yO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){W=Error("HTTP hook aborted by caller");break}if(B){let P={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(P,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});W=Error(`HTTP hook timeout attempt ${G+1}`);continue}W=V}finally{clearTimeout(R),Q.abortSignal?.removeEventListener("abort",F)}}return{success:!1,blocking:!1,error:W?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-nvjkw9e5.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-6tcagnpd.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 +1 @@
1
- import{Ac as g,uc as a,vc as b,wc as c,xc as d,yc as e,zc as f}from"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-qp2z1r7y.js";import"./chunk-2yvte5a7.js";import"./chunk-cxzx7j0p.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-fhnkyqfb.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{Ac as g,uc as a,vc as b,wc as c,xc as d,yc as e,zc as f}from"./chunk-v287pexf.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-qp2z1r7y.js";import"./chunk-2yvte5a7.js";import"./chunk-cxzx7j0p.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-fhnkyqfb.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1 +1 @@
1
- import{Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f}from"./chunk-807x1cw8.js";import"./chunk-hfrcwkc8.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{Rg as a,Sg as b,Tg as c,Ug as d,Vg as e,Wg as f}from"./chunk-pxqgt2h6.js";import"./chunk-hfrcwkc8.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,4 +1,4 @@
1
- import{Db as Xt,Eb as bn,Fb as Tn,Gb as fn}from"./chunk-mrsc4a55.js";import{Ec as jt}from"./chunk-0qsssahq.js";import{Je as Bt}from"./chunk-yvyqhw5q.js";import{$e as pn,Oe as xt,Pe as tn,Qe as en,Re as zt,Se as U,Te as rn,Ue as gt,Ve as mt,Xe as dn,Ye as En,Ze as B,_e as on,af as cn,bf as lt,cf as un,df as Mn,ef as wn,gf as S,jf as yn,kf as Ht,lf as Ut,mf as h,nf as qt}from"./chunk-cyw6cpac.js";import{Tf as X,Vf as x}from"./chunk-m8ss9rmx.js";import{dg as vt}from"./chunk-kfpzrmq7.js";import{Sg as nn,Tg as sn}from"./chunk-807x1cw8.js";import{hh as ss}from"./chunk-hfrcwkc8.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{Db as Xt,Eb as bn,Fb as Tn,Gb as fn}from"./chunk-mrsc4a55.js";import{Ec as jt}from"./chunk-0qsssahq.js";import{Je as Bt}from"./chunk-0b1qj502.js";import{$e as pn,Oe as xt,Pe as tn,Qe as en,Re as zt,Se as U,Te as rn,Ue as gt,Ve as mt,Xe as dn,Ye as En,Ze as B,_e as on,af as cn,bf as lt,cf as un,df as Mn,ef as wn,gf as S,jf as yn,kf as Ht,lf as Ut,mf as h,nf as qt}from"./chunk-sx4mkt0c.js";import{Tf as X,Vf as x}from"./chunk-m8ss9rmx.js";import{dg as vt}from"./chunk-kfpzrmq7.js";import{Sg as nn,Tg as sn}from"./chunk-pxqgt2h6.js";import{hh as ss}from"./chunk-hfrcwkc8.js";import{EventEmitter as hs}from"events";import Bn from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{ad as o}from"./chunk-v9tzhe90.js";import{td as n}from"./chunk-ecf8dh3c.js";import{Bf as R,Cf as E,Df as _,Ef as f,Gf as C,Hf as S,Lf as m,Qf as d,Rf as l,pf as Y,qf as x,sf as I,uf as N,vf as j,xf as F}from"./chunk-cyw6cpac.js";import{Sf as V}from"./chunk-7sna3js9.js";import{Tf as X,Vf as k,Yf as Z}from"./chunk-m8ss9rmx.js";import{bg as Q}from"./chunk-kfpzrmq7.js";import{fg as y,gg as D,mg as h,ng as A,qg as P,rg as T,tg as U,ug as L,wg as M,xg as O}from"./chunk-yk9pxkc1.js";import{Eg as u}from"./chunk-fhnkyqfb.js";import{promises as s}from"node:fs";import i from"node:path";var t=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],e=new Set([...Object.keys(m),...t]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),$=k.Array(k.String()),v=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:Y,maximum:x})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:P,maximum:T})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:M,maximum:O})),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(V)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:R,maximum:E})),maxQueuedTasks:k.Optional(k.Integer({minimum:_,maximum:f})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:C,maximum:S})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:I,maximum:N})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:j,maximum:F})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional($),ask:k.Optional($),deny:k.Optional($)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),a=[["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"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function G(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!e.has(H))throw Error(`Unknown --settings field: ${H}`);let J=X(v,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function c(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return G(B,"inline JSON");let w=i.resolve(Q(),B),J;try{J=await s.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return G(J,w)}function p(q,B){if(!B)return;let w=B;for(let[J,H]of a){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var b=u("General"),yk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Dk=async(q)=>{let B=await c(typeof q.settings==="string"?q.settings:void 0);if(p(q,B),typeof q.agents==="string")o(q.agents);g(q);try{let J=await d.getInstance().initialize(B),H=l(J,q);if(n().config.actions.setConfig(H),q.debug)b.info("[CLI] 配置已加载到 Store")}catch(w){b.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{ad as o}from"./chunk-v9tzhe90.js";import{td as n}from"./chunk-94zrzfyz.js";import{Bf as R,Cf as E,Df as _,Ef as f,Gf as C,Hf as S,Lf as m,Qf as d,Rf as l,pf as Y,qf as x,sf as I,uf as N,vf as j,xf as F}from"./chunk-sx4mkt0c.js";import{Sf as V}from"./chunk-7sna3js9.js";import{Tf as X,Vf as k,Yf as Z}from"./chunk-m8ss9rmx.js";import{bg as Q}from"./chunk-kfpzrmq7.js";import{fg as y,gg as D,mg as h,ng as A,qg as P,rg as T,tg as U,ug as L,wg as M,xg as O}from"./chunk-yk9pxkc1.js";import{Eg as u}from"./chunk-fhnkyqfb.js";import{promises as s}from"node:fs";import i from"node:path";var t=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],e=new Set([...Object.keys(m),...t]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),$=k.Array(k.String()),v=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:Y,maximum:x})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:P,maximum:T})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:M,maximum:O})),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(V)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:R,maximum:E})),maxQueuedTasks:k.Optional(k.Integer({minimum:_,maximum:f})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:C,maximum:S})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:I,maximum:N})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:j,maximum:F})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional($),ask:k.Optional($),deny:k.Optional($)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),a=[["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"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function G(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!e.has(H))throw Error(`Unknown --settings field: ${H}`);let J=X(v,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function c(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return G(B,"inline JSON");let w=i.resolve(Q(),B),J;try{J=await s.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return G(J,w)}function p(q,B){if(!B)return;let w=B;for(let[J,H]of a){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var b=u("General"),yk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Dk=async(q)=>{let B=await c(typeof q.settings==="string"?q.settings:void 0);if(p(q,B),typeof q.agents==="string")o(q.agents);g(q);try{let J=await d.getInstance().initialize(B),H=l(J,q);if(n().config.actions.setConfig(H),q.debug)b.info("[CLI] 配置已加载到 Store")}catch(w){b.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1 +1 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-6h28xs47.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-8y3skwtt.js";import"./chunk-4dthhzfe.js";import"./chunk-5vbrcvxg.js";import"./chunk-vhamhbej.js";import"./chunk-ssymrsyx.js";import"./chunk-y6tkxqjx.js";import"./chunk-1atpfmpe.js";import"./chunk-mrsc4a55.js";import"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as n}from"./chunk-szdcprq7.js";import"./chunk-fk4wbmv6.js";import{yd as s}from"./chunk-ecf8dh3c.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-j66r48pz.js";import"./chunk-sjtbp01y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{f as a,g as i,h as l,i as m}from"./chunk-cwcngsfq.js";import"./chunk-8vtyatd6.js";import"./chunk-f4sp074f.js";import"./chunk-yre5973e.js";import"./chunk-7pprh90t.js";import"./chunk-k2wnxzdx.js";import"./chunk-64z1vsd7.js";import"./chunk-1h9pcmkk.js";import"./chunk-y6tkxqjx.js";import"./chunk-z699m84q.js";import"./chunk-mrsc4a55.js";import"./chunk-v287pexf.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as n}from"./chunk-nxcc0fbe.js";import"./chunk-fk4wbmv6.js";import{yd as s}from"./chunk-94zrzfyz.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import"./chunk-qp2z1r7y.js";import"./chunk-b29dn3xe.js";import"./chunk-de1s7f6p.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-0b1qj502.js";import"./chunk-cxzx7j0p.js";import"./chunk-sx4mkt0c.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{Qf as Q}from"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as L}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as F}from"./chunk-hfrcwkc8.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-z1aqe7ms.js"),{SessionService:B}=await import("./chunk-yha9fpc7.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-v508x7cg.js";import{Qf as Q}from"./chunk-sx4mkt0c.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import{dg as L}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import{hh as F}from"./chunk-hfrcwkc8.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-z1aqe7ms.js"),{SessionService:B}=await import("./chunk-12akr5tm.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};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-e8zc6vbq.js";import"./chunk-pxqgt2h6.js";import"./chunk-hfrcwkc8.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,4 +1,4 @@
1
- import{ma as R,na as u0,sa as kJ,ta as F9,ua as g0}from"./chunk-ssymrsyx.js";import{Oa as w3,va as q3,xa as D3,ya as m4}from"./chunk-y6tkxqjx.js";import{$a as J9,Cb as v9,Pa as E$,Qa as Q1,Ra as $9,Sa as l$,Ta as c8,Ua as o9,Ya as Q0,_a as h2,ab as Y9,bb as X9,eb as o2,gb as p6,hb as t2,ib as s2,lb as J$,rb as O5,sb as bJ,tb as i7,zb as k9}from"./chunk-1atpfmpe.js";import{Ac as n,Ib as K0,Jb as L1,Kb as y$,Lb as U2,Mb as n4,Nb as n2,Ob as a2,Yb as V5,Zb as _0,_b as t0,hc as a4,ic as m0,jc as V1,kc as UJ,lc as QJ,oc as CJ,sc as f9,xc as VJ,yc as GJ}from"./chunk-t4y3h47y.js";import{Bc as h,Cc as $7,Dc as Z7,Ec as v2}from"./chunk-0qsssahq.js";import{Fc as E3,Ic as b3,Qc as N3,Wc as A3}from"./chunk-56qew7w0.js";import{fd as gZ,gd as xZ}from"./chunk-fk4wbmv6.js";import{Ad as M$,Bd as Y4,Cd as d$,Dd as P9,Id as W1,sd as e2,td as O0,ud as f,xd as B0,yd as g2,zd as z1}from"./chunk-ecf8dh3c.js";import{Jd as H$}from"./chunk-wwvb6znp.js";import{Nd as S9,Od as C9,Rd as FJ,Sd as u2}from"./chunk-egczvfsv.js";import{Ud as C0,Vd as I$}from"./chunk-7fqsgdee.js";import{Wd as AJ}from"./chunk-qp2z1r7y.js";import{Yd as ZJ,Zd as JJ,_d as YJ}from"./chunk-j66r48pz.js";import{$d as c2,ae as l2,ce as i2,de as r2,ee as f$,fe as U7,he as v0,ie as v3,je as y0,ke as r0,le as v5,me as G5,ne as Q$,oe as s$,pe as e$,qe as WJ,re as b4,te as W0,ue as d2,ve as KJ}from"./chunk-sjtbp01y.js";import{Ae as M2,xe as K1,ze as Z$}from"./chunk-tpa75y39.js";import{Be as pJ,De as XJ,Ee as Q5,Fe as uZ}from"./chunk-2yvte5a7.js";import{He as y4,Je as N0}from"./chunk-yvyqhw5q.js";import{Ke as s1,Le as r4,Me as e1,Ne as Z1}from"./chunk-cxzx7j0p.js";import{$e as fJ,Bf as D9,Cf as w9,Df as L9,Ef as E9,Ff as Z4,Gf as b9,Hf as T$,If as N9,Jf as A9,Kf as j9,Mf as OZ,Of as HJ,Pe as AZ,Pf as $J,Qf as X0,Ue as jZ,We as S4,df as TZ,ff as t7,hf as s8,if as e8,of as r$,rf as r8}from"./chunk-cyw6cpac.js";import{Tf as G2,Uf as P5,Vf as O,Wf as Q7,Xf as S,Yf as l}from"./chunk-m8ss9rmx.js";import{$f as l7,_f as c7}from"./chunk-j7edwwg1.js";import{bg as F2,dg as C}from"./chunk-kfpzrmq7.js";import{Eg as i}from"./chunk-fhnkyqfb.js";import{Jg as s7,Kg as e7}from"./chunk-26wse17p.js";import{Lg as lJ,Og as dJ}from"./chunk-hcm55r3d.js";import{Sg as aJ}from"./chunk-807x1cw8.js";import{Xg as f0}from"./chunk-bvf9syb2.js";import{_g as W2,ah as A$,ch as o7,dh as QZ,fh as L0}from"./chunk-qb0sqh29.js";import{hh as W$}from"./chunk-hfrcwkc8.js";import{randomUUID as C5}from"crypto";import{randomUUID as d3}from"node:crypto";var y3=String.raw`
1
+ import{ma as R,na as u0,sa as kJ,ta as F9,ua as g0}from"./chunk-1h9pcmkk.js";import{Oa as w3,va as q3,xa as D3,ya as m4}from"./chunk-y6tkxqjx.js";import{$a as J9,Cb as v9,Pa as E$,Qa as Q1,Ra as $9,Sa as l$,Ta as c8,Ua as o9,Ya as Q0,_a as h2,ab as Y9,bb as X9,eb as o2,gb as p6,hb as t2,ib as s2,lb as J$,rb as O5,sb as bJ,tb as i7,zb as k9}from"./chunk-z699m84q.js";import{Ac as n,Ib as K0,Jb as L1,Kb as y$,Lb as U2,Mb as n4,Nb as n2,Ob as a2,Yb as V5,Zb as _0,_b as t0,hc as a4,ic as m0,jc as V1,kc as UJ,lc as QJ,oc as CJ,sc as f9,xc as VJ,yc as GJ}from"./chunk-v287pexf.js";import{Bc as h,Cc as $7,Dc as Z7,Ec as v2}from"./chunk-0qsssahq.js";import{Fc as E3,Ic as b3,Qc as N3,Wc as A3}from"./chunk-56qew7w0.js";import{fd as gZ,gd as xZ}from"./chunk-fk4wbmv6.js";import{Ad as M$,Bd as Y4,Cd as d$,Dd as P9,Id as W1,sd as e2,td as O0,ud as f,xd as B0,yd as g2,zd as z1}from"./chunk-94zrzfyz.js";import{Jd as H$}from"./chunk-wwvb6znp.js";import{Nd as S9,Od as C9,Rd as FJ,Sd as u2}from"./chunk-egczvfsv.js";import{Ud as C0,Vd as I$}from"./chunk-7fqsgdee.js";import{Wd as AJ}from"./chunk-qp2z1r7y.js";import{Yd as ZJ,Zd as JJ,_d as YJ}from"./chunk-b29dn3xe.js";import{$d as c2,ae as l2,ce as i2,de as r2,ee as f$,fe as U7,he as v0,ie as v3,je as y0,ke as r0,le as v5,me as G5,ne as Q$,oe as s$,pe as e$,qe as WJ,re as b4,te as W0,ue as d2,ve as KJ}from"./chunk-de1s7f6p.js";import{Ae as M2,xe as K1,ze as Z$}from"./chunk-tpa75y39.js";import{Be as pJ,De as XJ,Ee as Q5,Fe as uZ}from"./chunk-2yvte5a7.js";import{He as y4,Je as N0}from"./chunk-0b1qj502.js";import{Ke as s1,Le as r4,Me as e1,Ne as Z1}from"./chunk-cxzx7j0p.js";import{$e as fJ,Bf as D9,Cf as w9,Df as L9,Ef as E9,Ff as Z4,Gf as b9,Hf as T$,If as N9,Jf as A9,Kf as j9,Mf as OZ,Of as HJ,Pe as AZ,Pf as $J,Qf as X0,Ue as jZ,We as S4,df as TZ,ff as t7,hf as s8,if as e8,of as r$,rf as r8}from"./chunk-sx4mkt0c.js";import{Tf as G2,Uf as P5,Vf as O,Wf as Q7,Xf as S,Yf as l}from"./chunk-m8ss9rmx.js";import{$f as l7,_f as c7}from"./chunk-j7edwwg1.js";import{bg as F2,dg as C}from"./chunk-kfpzrmq7.js";import{Eg as i}from"./chunk-fhnkyqfb.js";import{Jg as s7,Kg as e7}from"./chunk-26wse17p.js";import{Lg as lJ,Og as dJ}from"./chunk-hcm55r3d.js";import{Sg as aJ}from"./chunk-pxqgt2h6.js";import{Xg as f0}from"./chunk-bvf9syb2.js";import{_g as W2,ah as A$,ch as o7,dh as QZ,fh as L0}from"./chunk-qb0sqh29.js";import{hh as W$}from"./chunk-hfrcwkc8.js";import{randomUUID as C5}from"crypto";import{randomUUID as d3}from"node:crypto";var y3=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -776,7 +776,7 @@ ${t}
776
776
  </approved-plan>
777
777
 
778
778
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")v=H+d;else v=[...H,{type:"text",text:d}]}P=yield*this.runLoop(v,B,{...j,inputMessageId:void 0})}if(!this.sessionRuntime||!N)return P;let I=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(I)yield{kind:"goal_updated",goal:I};if(!P.success||B.signal?.aborted){if(I=await this.sessionRuntime.pauseActiveGoal(B.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),I)yield{kind:"goal_updated",goal:I}}if(P.success&&!B.signal?.aborted&&E<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(N,B.signal);let $0=P.success&&!B.signal?.aborted&&E<20,k=UU(P);if(b=await this.sessionRuntime.finishTurn(N,{continuePending:$0,...k?{acknowledgeInput:!0}:{},outcome:P.success&&!B.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:B.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),b){E++,F=!0,_=!1,D=null,H="",w=void 0,q=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:M()};continue}if(!P.success||B.signal?.aborted)return P;if(I=await this.sessionRuntime.getGoal(),!I||I.status!=="active"&&I.status!=="verifying")return P;if(D=await this.sessionRuntime.beginGoalContinuation(),!D)return P;b=await this.sessionRuntime.beginTurn("goal"),F=!1,_=!0,H=W6(D),w=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:D,continuation:D.continuationCount},yield{kind:"goal_updated",goal:D}}}finally{if(this.sessionRuntime&&b)await this.sessionRuntime.finishTurn(b)}}let G=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
779
- `),z={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-mqmf40p2.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await m$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=C1($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];X=$.map((Q)=>Q===U?{type:"text",text:C1(U.text)}:Q)}else X=[{type:"text",text:C1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await m$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return v9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,Q={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],G=k9(Y,Q);if(G)V.push(G);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await m$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await m2({sessionId:"default",configDir:y9.join(I9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await _2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=g0.createIsolated({artifactWriter:new M1(`legacy-${WU()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),p.debug(`MCP server "${W}" connected`)}catch(Q){p.warn(`Warning: MCP server "${W}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(k1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await W0(C());if(this.agentResources=d2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let W=X.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
779
+ `),z={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(z)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-74nmcybn.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await m$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=C1($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];X=$.map((Q)=>Q===U?{type:"text",text:C1(U.text)}:Q)}else X=[{type:"text",text:C1("")},...$]}return yield*this.executeLoop(X,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await m$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return v9(X,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},X=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,Q={success:W,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...X?{metadata:X}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],G=k9(Y,Q);if(G)V.push(G);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of Y)Z.unregister(X.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await m$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await m2({sessionId:"default",configDir:y9.join(I9.homedir(),".blade"),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await _2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=g0.createIsolated({artifactWriter:new M1(`legacy-${WU()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),p.debug(`MCP server "${W}" connected`)}catch(Q){p.warn(`Warning: MCP server "${W}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(k1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(W)=>{J.replaceMcpTools(W.tools,W)}),Z.on("contentCatalogChanged",(W)=>{J.queueMcpContentChange(W)}),Z.on("resourceUpdated",(W)=>{J.queueMcpResourceUpdated(W)}),Z.on("connectionLifecycleChanged",(W)=>{J.queueMcpConnectionChange(W)}),Z.on("log",(W)=>{J.queueMcpLog(W)}),Z.on("instructionsChanged",(W)=>{J.queueMcpInstructionsChange({revision:W.revision,reason:W.reason,replace:!1,instructions:W.action==="added"&&W.instruction?[{serverName:W.serverName,...W.instruction}]:[],removed:W.action==="removed"?[W.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await W0(C());if(this.agentResources=d2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((X)=>{if(X===Y.name)return!0;let W=X.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
780
780
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(Y);if(!X)return $;return[...$,{type:"text",text:X}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let W=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${W?` range="${W}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let Y="";if(Z.length>0)Y+=`
781
781
 
782
782
  <system-reminder>
@@ -873,7 +873,7 @@ Usage notes:
873
873
  - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
874
874
  - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
875
875
  - If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.
876
- `.trim()}function $5($=f$(),Z,J,Y,X,W,U,Q){return R({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:O.Object({subagent_type:O.Optional(O.Refine(O.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(V)=>cU($,V),(V)=>`Invalid subagent type: "${V}". Available: ${lU($)}`)),description:O.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:O.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(O.Boolean({description:"Set true to run in the background. Blade will deliver a durable terminal notification; use TaskOutput only for explicit status or full-result reads."}),!1),isolation:O.Optional(l(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:O.Optional(O.String({description:"Deprecated alias for resume_from."})),resume_from:O.Optional(O.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:O.Optional(O.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return iU($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(V,G){let{subagent_type:z,description:K,prompt:H,run_in_background:B=!1,isolation:F,resume:_,resume_from:q,subagent_session_id:D}=V,w=q??_,b=nU(G);if(!b)return S$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let E=X?.(),M=W?.(),T=U?.(),L=Q?.(),N=Z0.getInstance(),A=w?N.getAgent(w,b):void 0;if(w&&!A)return S$(`Cannot resume agent ${w}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${w}`);if(A&&(N.isRunning(A.id)||A.status==="running"))return S$(`Cannot resume agent ${A.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${A.id}`);if(A&&z&&A.subagentType!==z)return S$(`Cannot resume with subagent_type "${z}": source agent used "${A.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let j=A?.subagentType??z;if(!j)return S$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let P=$.getSubagent(j),$0=(A?.configSnapshot?{...A.configSnapshot}:void 0)??P;if(!$0)return S$(`Unknown subagent type: ${j}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${j}`);let k={...$0,model:$0.model&&$0.model!=="inherit"?$0.model:G.modelId??$0.model,permissionMode:$0.permissionMode??G.permissionMode},c=typeof D==="string"&&D.length>0?D:H$("agent"),t=A?.isolation??F??k.isolation??"none",v=A?.rootAgentId??c,d=A?A.resumeDepth+1:0,r=aU({owner:b,subagentSessionId:c,type:k.name,description:K,background:B,resumedFrom:A?.id,rootAgentId:v,resumeDepth:d,notifyBackgroundSubagentCompleted:G.notifyBackgroundSubagentCompleted});if(B){let J0=A?N.resumeAgent({agentId:A.id,prompt:H,config:k,owner:b,permissionMode:G.permissionMode,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L,newAgentId:c,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:N.startBackgroundAgent({config:k,description:K,prompt:H,parentSessionId:b.sessionId,providerAdmissionOwnerId:G.providerAdmissionOwnerId??b.sessionId,parentProjectPath:b.projectPath,permissionMode:G.permissionMode,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L,agentId:c,workspaceRoot:b.projectPath,isolation:t,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!J0)return S$(`Failed to resume agent ${A?.id??c}`,"恢复 Agent 失败");return G.registerBackgroundSubagent?.(J0),r.onStarted(),tU({sessionId:J0,config:k,description:K,isolation:t,resumedFrom:A?.id,rootAgentId:v,resumeDepth:d})}return oU({config:k,description:K,prompt:H,context:G,owner:b,subagentSessionId:c,isolation:t,source:A,eventBridge:r,agentResources:Z,modelResources:J,lspResources:Y,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(V)=>`${V.subagent_type||"resume"}:${V.resume_from||V.resume||""}:${V.description}`,abstractPermissionRule:()=>""})}var rU=$5(U7);function nU($){if(!$.sessionId)return;let Z=$.workspaceRoot||C();if(!X7.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:X7.resolve(Z)}}function S$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function aU($){let Z=pU(8),J=!1,Y={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{e2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Q0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...Y})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let W=X.toolCall,U="function"in W?W.function.name:"Unknown";if(e2.getState().app.actions.updateSubagentTool(Z,U),Q0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:U}),"function"in W)Q0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:U,arguments:W.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let W=X.toolCall;if(!("function"in W))break;Q0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:W.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:Y7(J7(W.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let W=X.toolCall;if(!("function"in W))break;Q0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:W.function.name,...X.update});break}case"content_delta":Q0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":Q0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":Q0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;case"provider_admission":Q0.publish($.owner,"subagent.provider.admission",{subagentSessionId:$.subagentSessionId,phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,reason:X.reason,queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,recoveryRemainingMs:X.recoveryRemainingMs});break;default:break}},onCompleted:async(X)=>{if(J)return;if(J=!0,$.background)try{await $.notifyBackgroundSubagentCompleted?.(X.id)}catch(W){console.warn(`[Task] Failed to enqueue background completion for ${X.id}:`,W)}e2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed"),Q0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:X.result?.message?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...Y})}}}async function oU($){let{config:Z,description:J,prompt:Y,context:X,owner:W,subagentSessionId:U,isolation:Q,source:V,eventBridge:G,agentResources:z,modelResources:K,lspResources:H}=$,B=b0.getInstance(),F=V?.workspaceRoot??W.projectPath,_=V?.rootAgentId??U,q=V?V.resumeDepth+1:0,D,w=!1,b=!1,E=async(M)=>{if(!D||w)return;let T=await C$.finalize({agentId:U,lease:D,success:M});return w=!0,T};try{D=await C$.prepare({agentId:U,sourceWorkspaceRoot:F,isolation:Q,restoredWorktree:V?.worktree});let M=Date.now();B.saveSession({schemaVersion:2,id:U,subagentType:Z.name,description:J,prompt:Y,messages:[...V?.messages??[]],status:"running",background:!1,createdAt:M,lastActiveAt:M,processId:process.pid,processIdentity:y$(process.pid),parentSessionId:W.sessionId,providerAdmissionOwnerId:X.providerAdmissionOwnerId??W.sessionId,parentProjectPath:W.projectPath,rootAgentId:_,resumedFrom:V?.id,resumeDepth:q,configSnapshot:P2(Z),workspaceRoot:F,isolation:Q,worktree:D.worktree}),b=!0,G.onStarted(),X.updateOutput?.(`${V?"恢复":"启动"} ${Z.name} subagent: ${J}`);let T=new W4(Z,z,K,H),L={prompt:Y,parentSessionId:W.sessionId,providerAdmissionOwnerId:X.providerAdmissionOwnerId??W.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:U,resumedFrom:V?.id,rootAgentId:_,resumeDepth:q,workspaceRoot:D.workspaceRoot,worktreeActive:Boolean(D.worktree),existingMessages:V?.messages,onEvent:G.onEvent},N=Date.now(),A=await T.execute(L);try{let I=await N0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:D.workspaceRoot,sessionId:W.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:A.success,resultSummary:A.message.slice(0,500),error:A.error});if(!I.shouldStop&&I.continueReason)A=await T.execute({...L,prompt:I.continueReason,existingMessages:A.messages});if(I.warning)console.warn(`[Task] SubagentStop hook warning: ${I.warning}`)}catch(I){console.warn("[Task] SubagentStop hook execution failed:",I)}let j=await E(A.success);if(j?.preserved)A.worktreePath=j.worktreePath,A.worktreeBranch=j.worktreeBranch,A.worktree=j.worktree;B.updateSession(U,{messages:A.messages??[],worktree:j?.worktree});let P=B.markCompleted(U,{success:A.success,message:A.message,error:A.error,verificationCommands:A.verificationCommands,verificationVerdict:A.verificationVerdict,modifiedFiles:A.modifiedFiles},{...A.stats,duration:Date.now()-N});if(P)await G.onCompleted(P);return sU({result:A,sessionId:U,config:Z,description:J,isolation:Q,resumedFrom:V?.id,rootAgentId:_,resumeDepth:q})}catch(M){let T=M,L;try{L=await E(!1)}catch(N){console.warn("[Task] Failed to preserve subagent worktree:",N)}if(b){let N=B.markCompleted(U,{success:!1,message:"",error:T.message});if(N)await G.onCompleted(N)}return{...S$(`Subagent execution error: ${T.message}`,`Subagent 执行异常: ${W7(T)}`),metadata:{summary:`Subagent 执行异常: ${W7(T)}`,subagentSessionId:U,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:V?.id,subagentRootId:_,subagentResumeDepth:q,isolation:Q,worktreePath:L?.worktreePath,worktreeBranch:L?.worktreeBranch}}}}function tU($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Blade will notify this parent when it reaches a terminal state.`,notification:"Blade will deliver a durable completion notification automatically. Continue independent parent work and do not poll repeatedly."},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function sU($){let Z=U4({result:$.result,sessionId:$.sessionId,subagentType:$.config.name,subagentSource:$.config.source,description:$.description,isolation:$.isolation,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth});if(Z.success)return{success:!0,llmContent:Z.llmContent,metadata:Z.metadata};return{success:!1,llmContent:Z.llmContent,error:{type:"execution_error",message:Z.errorMessage??"Unknown error"},metadata:Z.metadata}}import*as H1 from"fs/promises";import*as J5 from"path";var V4=l(["pending","in_progress","completed"]),eU=l(["high","medium","low"]),V7=Q7(O.Object({id:O.String(),subject:O.String(),description:O.String(),status:V4,activeForm:O.Optional(O.String()),owner:O.Optional(O.String()),priority:S(eU,"medium"),blocks:S(O.Array(O.String()),[]),blockedBy:S(O.Array(O.String()),[]),metadata:O.Optional(O.Record(O.String(),O.Unknown())),createdAt:O.String(),startedAt:O.Optional(O.String()),completedAt:O.Optional(O.String())}));class a${static instances=new Map;tasks=[];nextId=1;loaded=!1;filePath;constructor($,Z){this.filePath=J5.join(Z,"tasks",`${$}-agent-${$}.json`)}static getInstance($,Z){let J=`${$}-${Z}`;if(!a$.instances.has(J))a$.instances.set(J,new a$($,Z));return a$.instances.get(J)}async createTask($){await this.ensureLoaded();let Z=new Date().toISOString(),J={id:String(this.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:[],metadata:$.metadata,createdAt:Z};return this.nextId+=1,this.tasks=[...this.tasks,J],await this.saveTasks(),J}async getTask($){return await this.ensureLoaded(),this.tasks.find((Z)=>Z.id===$)||null}async listTasks(){return await this.ensureLoaded(),this.getSortedTasks()}async updateTask($,Z){await this.ensureLoaded();let J=this.tasks.findIndex((Q)=>Q.id===$);if(J===-1)return{task:null,updatedFields:[]};let Y=this.tasks[J],X=[],W={...Y};if(Z.subject!==void 0&&Z.subject!==Y.subject)W.subject=Z.subject,X.push("subject");if(Z.description!==void 0&&Z.description!==Y.description)W.description=Z.description,X.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Y.activeForm)W.activeForm=Z.activeForm,X.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Y.owner)W.owner=Z.owner,X.push("owner");if(Z.metadata!==void 0)W.metadata=ZQ(Y.metadata,Z.metadata),X.push("metadata");let U;if(Z.status!==void 0&&Z.status!==Y.status){if(W.status=Z.status,Z.status==="in_progress"&&!Y.startedAt)W.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Y.completedAt)W.completedAt=new Date().toISOString();U={from:Y.status,to:Z.status},X.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(W.blocks=Z5([...Y.blocks,...Z.addBlocks]),W.blocks.length!==Y.blocks.length)X.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(W.blockedBy=Z5([...Y.blockedBy,...Z.addBlockedBy]),W.blockedBy.length!==Y.blockedBy.length)X.push("blockedBy")}return this.tasks=this.tasks.map((Q)=>Q.id===$?W:Q),await this.syncDependencyEdges(W,Z.addBlocks,Z.addBlockedBy),await this.saveTasks(),{task:W,updatedFields:X,statusChange:U}}async deleteTask($){await this.ensureLoaded();let Z=this.tasks.length;if(this.tasks=this.tasks.filter((J)=>J.id!==$).map((J)=>({...J,blocks:J.blocks.filter((Y)=>Y!==$),blockedBy:J.blockedBy.filter((Y)=>Y!==$)})),this.tasks.length===Z)return!1;return await this.saveTasks(),!0}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){let $={in_progress:0,pending:1,completed:2},Z={high:0,medium:1,low:2};return[...this.tasks].sort((J,Y)=>{let X=$[J.status]-$[Y.status];if(X!==0)return X;let W=Z[J.priority]-Z[Y.priority];if(W!==0)return W;return Number(J.id)-Number(Y.id)})}async syncDependencyEdges($,Z,J){for(let Y of Z||[])this.tasks=this.tasks.map((X)=>X.id===Y?{...X,blockedBy:Z5([...X.blockedBy,$.id])}:X);for(let Y of J||[])this.tasks=this.tasks.map((X)=>X.id===Y?{...X,blocks:Z5([...X.blocks,$.id])}:X)}async ensureLoaded(){if(!this.loaded)await this.loadTasks(),this.loaded=!0}async loadTasks(){try{let $=JSON.parse(await H1.readFile(this.filePath,"utf-8")),Z=$Q($);this.tasks=Z.tasks,this.nextId=Z.nextId}catch($){if($.code!=="ENOENT")console.warn("加载任务列表失败:",$);this.tasks=[],this.nextId=1}}async saveTasks(){await H1.mkdir(J5.dirname(this.filePath),{recursive:!0,mode:493});let $={nextId:this.nextId,tasks:this.tasks};await H1.writeFile(this.filePath,JSON.stringify($,null,2),"utf-8")}}function $Q($){let J=($&&typeof $==="object"&&Array.isArray($.tasks)?$.tasks:Array.isArray($)?$:[]).map((W)=>G2(V7,W)).filter((W)=>W.success).map((W)=>W.data),Y=$&&typeof $==="object"&&typeof $.nextId==="number"?$.nextId:void 0,X=J.reduce((W,U)=>{let Q=Number(U.id);return Number.isFinite(Q)?Math.max(W,Q):W},0);return{tasks:J,nextId:Math.max(Y||1,X+1)}}function Z5($){return[...new Set($.filter(Boolean))]}function ZQ($,Z){let J={...$||{}};for(let[Y,X]of Object.entries(Z))if(X===null)delete J[Y];else J[Y]=X;return J}var JQ=`Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
876
+ `.trim()}function $5($=f$(),Z,J,Y,X,W,U,Q){return R({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:O.Object({subagent_type:O.Optional(O.Refine(O.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(V)=>cU($,V),(V)=>`Invalid subagent type: "${V}". Available: ${lU($)}`)),description:O.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:O.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(O.Boolean({description:"Set true to run in the background. Blade will deliver a durable terminal notification; use TaskOutput only for explicit status or full-result reads."}),!1),isolation:O.Optional(l(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:O.Optional(O.String({description:"Deprecated alias for resume_from."})),resume_from:O.Optional(O.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:O.Optional(O.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return iU($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(V,G){let{subagent_type:z,description:K,prompt:H,run_in_background:B=!1,isolation:F,resume:_,resume_from:q,subagent_session_id:D}=V,w=q??_,b=nU(G);if(!b)return S$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let E=X?.(),M=W?.(),T=U?.(),L=Q?.(),N=Z0.getInstance(),A=w?N.getAgent(w,b):void 0;if(w&&!A)return S$(`Cannot resume agent ${w}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${w}`);if(A&&(N.isRunning(A.id)||A.status==="running"))return S$(`Cannot resume agent ${A.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${A.id}`);if(A&&z&&A.subagentType!==z)return S$(`Cannot resume with subagent_type "${z}": source agent used "${A.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let j=A?.subagentType??z;if(!j)return S$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let P=$.getSubagent(j),$0=(A?.configSnapshot?{...A.configSnapshot}:void 0)??P;if(!$0)return S$(`Unknown subagent type: ${j}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${j}`);let k={...$0,model:$0.model&&$0.model!=="inherit"?$0.model:G.modelId??$0.model,permissionMode:$0.permissionMode??G.permissionMode},c=typeof D==="string"&&D.length>0?D:H$("agent"),t=A?.isolation??F??k.isolation??"none",v=A?.rootAgentId??c,d=A?A.resumeDepth+1:0,r=aU({owner:b,subagentSessionId:c,type:k.name,description:K,background:B,resumedFrom:A?.id,rootAgentId:v,resumeDepth:d,notifyBackgroundSubagentCompleted:G.notifyBackgroundSubagentCompleted});if(B){let J0=A?N.resumeAgent({agentId:A.id,prompt:H,config:k,owner:b,permissionMode:G.permissionMode,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L,newAgentId:c,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:N.startBackgroundAgent({config:k,description:K,prompt:H,parentSessionId:b.sessionId,providerAdmissionOwnerId:G.providerAdmissionOwnerId??b.sessionId,parentProjectPath:b.projectPath,permissionMode:G.permissionMode,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L,agentId:c,workspaceRoot:b.projectPath,isolation:t,agentResources:Z,modelResources:J,lspResources:Y,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!J0)return S$(`Failed to resume agent ${A?.id??c}`,"恢复 Agent 失败");return G.registerBackgroundSubagent?.(J0),r.onStarted(),tU({sessionId:J0,config:k,description:K,isolation:t,resumedFrom:A?.id,rootAgentId:v,resumeDepth:d})}return oU({config:k,description:K,prompt:H,context:G,owner:b,subagentSessionId:c,isolation:t,source:A,eventBridge:r,agentResources:Z,modelResources:J,lspResources:Y,reasoningEffort:E,serviceTier:M,responseVerbosity:T,communicationStyle:L})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(V)=>`${V.subagent_type||"resume"}:${V.resume_from||V.resume||""}:${V.description}`,abstractPermissionRule:()=>""})}var rU=$5(U7);function nU($){if(!$.sessionId)return;let Z=$.workspaceRoot||C();if(!X7.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:X7.resolve(Z)}}function S$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function aU($){let Z=pU(8),J=!1,Y={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{e2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Q0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...Y})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let W=X.toolCall,U="function"in W?W.function.name:"Unknown";if(e2.getState().app.actions.updateSubagentTool(Z,U),Q0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:U}),"function"in W)Q0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:U,arguments:W.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let W=X.toolCall;if(!("function"in W))break;Q0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:W.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:Y7(J7(W.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let W=X.toolCall;if(!("function"in W))break;Q0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:W.id,toolName:W.function.name,...X.update});break}case"content_delta":Q0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":Q0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":Q0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;case"provider_admission":Q0.publish($.owner,"subagent.provider.admission",{subagentSessionId:$.subagentSessionId,phase:X.phase,requestClass:X.requestClass,resource:X.resource,scope:X.scope,reason:X.reason,queuePosition:X.queuePosition,queueDepth:X.queueDepth,inFlight:X.inFlight,limit:X.limit,waitMs:X.waitMs,maxWaitMs:X.maxWaitMs,recoveryRemainingMs:X.recoveryRemainingMs});break;default:break}},onCompleted:async(X)=>{if(J)return;J=!0;let W=X.status==="completed"?X.result?.message:X.result?.error||X.result?.message;if($.background)try{await $.notifyBackgroundSubagentCompleted?.(X.id)}catch(U){console.warn(`[Task] Failed to enqueue background completion for ${X.id}:`,U)}e2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed",W),Q0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:W?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...Y})}}}async function oU($){let{config:Z,description:J,prompt:Y,context:X,owner:W,subagentSessionId:U,isolation:Q,source:V,eventBridge:G,agentResources:z,modelResources:K,lspResources:H}=$,B=b0.getInstance(),F=V?.workspaceRoot??W.projectPath,_=V?.rootAgentId??U,q=V?V.resumeDepth+1:0,D,w=!1,b=!1,E=async(M)=>{if(!D||w)return;let T=await C$.finalize({agentId:U,lease:D,success:M});return w=!0,T};try{D=await C$.prepare({agentId:U,sourceWorkspaceRoot:F,isolation:Q,restoredWorktree:V?.worktree});let M=Date.now();B.saveSession({schemaVersion:2,id:U,subagentType:Z.name,description:J,prompt:Y,messages:[...V?.messages??[]],status:"running",background:!1,createdAt:M,lastActiveAt:M,processId:process.pid,processIdentity:y$(process.pid),parentSessionId:W.sessionId,providerAdmissionOwnerId:X.providerAdmissionOwnerId??W.sessionId,parentProjectPath:W.projectPath,rootAgentId:_,resumedFrom:V?.id,resumeDepth:q,configSnapshot:P2(Z),workspaceRoot:F,isolation:Q,worktree:D.worktree}),b=!0,G.onStarted(),X.updateOutput?.(`${V?"恢复":"启动"} ${Z.name} subagent: ${J}`);let T=new W4(Z,z,K,H),L={prompt:Y,parentSessionId:W.sessionId,providerAdmissionOwnerId:X.providerAdmissionOwnerId??W.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:U,resumedFrom:V?.id,rootAgentId:_,resumeDepth:q,workspaceRoot:D.workspaceRoot,worktreeActive:Boolean(D.worktree),existingMessages:V?.messages,onEvent:G.onEvent},N=Date.now(),A=await T.execute(L);try{let I=await N0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:D.workspaceRoot,sessionId:W.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:A.success,resultSummary:A.message.slice(0,500),error:A.error});if(!I.shouldStop&&I.continueReason)A=await T.execute({...L,prompt:I.continueReason,existingMessages:A.messages});if(I.warning)console.warn(`[Task] SubagentStop hook warning: ${I.warning}`)}catch(I){console.warn("[Task] SubagentStop hook execution failed:",I)}let j=await E(A.success);if(j?.preserved)A.worktreePath=j.worktreePath,A.worktreeBranch=j.worktreeBranch,A.worktree=j.worktree;B.updateSession(U,{messages:A.messages??[],worktree:j?.worktree});let P=B.markCompleted(U,{success:A.success,message:A.message,error:A.error,verificationCommands:A.verificationCommands,verificationVerdict:A.verificationVerdict,modifiedFiles:A.modifiedFiles},{...A.stats,duration:Date.now()-N});if(P)await G.onCompleted(P);return sU({result:A,sessionId:U,config:Z,description:J,isolation:Q,resumedFrom:V?.id,rootAgentId:_,resumeDepth:q})}catch(M){let T=M,L;try{L=await E(!1)}catch(N){console.warn("[Task] Failed to preserve subagent worktree:",N)}if(b){let N=B.markCompleted(U,{success:!1,message:"",error:T.message});if(N)await G.onCompleted(N)}return{...S$(`Subagent execution error: ${T.message}`,`Subagent 执行异常: ${W7(T)}`),metadata:{summary:`Subagent 执行异常: ${W7(T)}`,subagentSessionId:U,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:V?.id,subagentRootId:_,subagentResumeDepth:q,isolation:Q,worktreePath:L?.worktreePath,worktreeBranch:L?.worktreeBranch}}}}function tU($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Blade will notify this parent when it reaches a terminal state.`,notification:"Blade will deliver a durable completion notification automatically. Continue independent parent work and do not poll repeatedly."},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function sU($){let Z=U4({result:$.result,sessionId:$.sessionId,subagentType:$.config.name,subagentSource:$.config.source,description:$.description,isolation:$.isolation,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth});if(Z.success)return{success:!0,llmContent:Z.llmContent,metadata:Z.metadata};return{success:!1,llmContent:Z.llmContent,error:{type:"execution_error",message:Z.errorMessage??"Unknown error"},metadata:Z.metadata}}import*as H1 from"fs/promises";import*as J5 from"path";var V4=l(["pending","in_progress","completed"]),eU=l(["high","medium","low"]),V7=Q7(O.Object({id:O.String(),subject:O.String(),description:O.String(),status:V4,activeForm:O.Optional(O.String()),owner:O.Optional(O.String()),priority:S(eU,"medium"),blocks:S(O.Array(O.String()),[]),blockedBy:S(O.Array(O.String()),[]),metadata:O.Optional(O.Record(O.String(),O.Unknown())),createdAt:O.String(),startedAt:O.Optional(O.String()),completedAt:O.Optional(O.String())}));class a${static instances=new Map;tasks=[];nextId=1;loaded=!1;filePath;constructor($,Z){this.filePath=J5.join(Z,"tasks",`${$}-agent-${$}.json`)}static getInstance($,Z){let J=`${$}-${Z}`;if(!a$.instances.has(J))a$.instances.set(J,new a$($,Z));return a$.instances.get(J)}async createTask($){await this.ensureLoaded();let Z=new Date().toISOString(),J={id:String(this.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:[],metadata:$.metadata,createdAt:Z};return this.nextId+=1,this.tasks=[...this.tasks,J],await this.saveTasks(),J}async getTask($){return await this.ensureLoaded(),this.tasks.find((Z)=>Z.id===$)||null}async listTasks(){return await this.ensureLoaded(),this.getSortedTasks()}async updateTask($,Z){await this.ensureLoaded();let J=this.tasks.findIndex((Q)=>Q.id===$);if(J===-1)return{task:null,updatedFields:[]};let Y=this.tasks[J],X=[],W={...Y};if(Z.subject!==void 0&&Z.subject!==Y.subject)W.subject=Z.subject,X.push("subject");if(Z.description!==void 0&&Z.description!==Y.description)W.description=Z.description,X.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==Y.activeForm)W.activeForm=Z.activeForm,X.push("activeForm");if(Z.owner!==void 0&&Z.owner!==Y.owner)W.owner=Z.owner,X.push("owner");if(Z.metadata!==void 0)W.metadata=ZQ(Y.metadata,Z.metadata),X.push("metadata");let U;if(Z.status!==void 0&&Z.status!==Y.status){if(W.status=Z.status,Z.status==="in_progress"&&!Y.startedAt)W.startedAt=new Date().toISOString();if(Z.status==="completed"&&!Y.completedAt)W.completedAt=new Date().toISOString();U={from:Y.status,to:Z.status},X.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(W.blocks=Z5([...Y.blocks,...Z.addBlocks]),W.blocks.length!==Y.blocks.length)X.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(W.blockedBy=Z5([...Y.blockedBy,...Z.addBlockedBy]),W.blockedBy.length!==Y.blockedBy.length)X.push("blockedBy")}return this.tasks=this.tasks.map((Q)=>Q.id===$?W:Q),await this.syncDependencyEdges(W,Z.addBlocks,Z.addBlockedBy),await this.saveTasks(),{task:W,updatedFields:X,statusChange:U}}async deleteTask($){await this.ensureLoaded();let Z=this.tasks.length;if(this.tasks=this.tasks.filter((J)=>J.id!==$).map((J)=>({...J,blocks:J.blocks.filter((Y)=>Y!==$),blockedBy:J.blockedBy.filter((Y)=>Y!==$)})),this.tasks.length===Z)return!1;return await this.saveTasks(),!0}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){let $={in_progress:0,pending:1,completed:2},Z={high:0,medium:1,low:2};return[...this.tasks].sort((J,Y)=>{let X=$[J.status]-$[Y.status];if(X!==0)return X;let W=Z[J.priority]-Z[Y.priority];if(W!==0)return W;return Number(J.id)-Number(Y.id)})}async syncDependencyEdges($,Z,J){for(let Y of Z||[])this.tasks=this.tasks.map((X)=>X.id===Y?{...X,blockedBy:Z5([...X.blockedBy,$.id])}:X);for(let Y of J||[])this.tasks=this.tasks.map((X)=>X.id===Y?{...X,blocks:Z5([...X.blocks,$.id])}:X)}async ensureLoaded(){if(!this.loaded)await this.loadTasks(),this.loaded=!0}async loadTasks(){try{let $=JSON.parse(await H1.readFile(this.filePath,"utf-8")),Z=$Q($);this.tasks=Z.tasks,this.nextId=Z.nextId}catch($){if($.code!=="ENOENT")console.warn("加载任务列表失败:",$);this.tasks=[],this.nextId=1}}async saveTasks(){await H1.mkdir(J5.dirname(this.filePath),{recursive:!0,mode:493});let $={nextId:this.nextId,tasks:this.tasks};await H1.writeFile(this.filePath,JSON.stringify($,null,2),"utf-8")}}function $Q($){let J=($&&typeof $==="object"&&Array.isArray($.tasks)?$.tasks:Array.isArray($)?$:[]).map((W)=>G2(V7,W)).filter((W)=>W.success).map((W)=>W.data),Y=$&&typeof $==="object"&&typeof $.nextId==="number"?$.nextId:void 0,X=J.reduce((W,U)=>{let Q=Number(U.id);return Number.isFinite(Q)?Math.max(W,Q):W},0);return{tasks:J,nextId:Math.max(Y||1,X+1)}}function Z5($){return[...new Set($.filter(Boolean))]}function ZQ($,Z){let J={...$||{}};for(let[Y,X]of Object.entries(Z))if(X===null)delete J[Y];else J[Y]=X;return J}var JQ=`Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
877
877
 
878
878
  ## When to Use This Tool
879
879
 
@@ -1574,7 +1574,7 @@ ${J}
1574
1574
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1575
1575
  `)}}case"create":{let Q=Az(W);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:U,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let G=await $.create(V),z=G.nextRunAt?new Date(G.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${G.id}\`
1576
1576
  ${m4(G.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${G.id} created`}}catch(G){let z=G instanceof Error?G.message:String(G);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let Q=W[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=W[0];if(!Q)return Y.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,X==="enable");return Y.sendMessage(V?`[OK] 已${X==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=W[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await jz(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let G=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${G}`),{success:!1,error:G}}}default:return Y.sendMessage(`未知子命令: ${X}
1577
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var L3=Tz();import*as D1 from"node:fs/promises";import*as w1 from"node:path";async function j3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:W}=Z,U=W??W2(X??C());if(!W){let H=await Mz($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await D1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>w1.join(U,B))}catch{return[]}let G=(await Promise.all(Q.map(async(H)=>{try{let B=await D1.stat(H);return{path:H,mtime:B.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,B)=>B.mtime-H.mtime).map((H)=>H.path),z=[],K=Y?$:$.toLowerCase();for(let H of G){if(z.length>=J)break;let B=w1.basename(H,".jsonl"),F=await Cz(H,K,Y,B);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function Mz($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-z1aqe7ms.js"),W=await N3();if(!W)return null;let{SessionService:U}=await import("./chunk-yha9fpc7.js");await X(W,U.projectionDeriverForSearch());let Q=w1.resolve(Z),V=A3(W,$,Q,J*4),G=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=p4(K.text,G,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)z.push(H);if(z.length>=J)break}return z}catch{return null}}async function Cz($,Z,J,Y){try{let X=await D1.readFile($,"utf8"),U=X.split(`
1577
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var L3=Tz();import*as D1 from"node:fs/promises";import*as w1 from"node:path";async function j3($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:X,storagePath:W}=Z,U=W??W2(X??C());if(!W){let H=await Mz($,X??C(),J,Y);if(H)return H}let Q;try{Q=(await D1.readdir(U)).filter((B)=>B.endsWith(".jsonl")&&!B.startsWith("agent_")).map((B)=>w1.join(U,B))}catch{return[]}let G=(await Promise.all(Q.map(async(H)=>{try{let B=await D1.stat(H);return{path:H,mtime:B.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,B)=>B.mtime-H.mtime).map((H)=>H.path),z=[],K=Y?$:$.toLowerCase();for(let H of G){if(z.length>=J)break;let B=w1.basename(H,".jsonl"),F=await Cz(H,K,Y,B);if(z.push(...F),z.length>=J){z.length=J;break}}return z}async function Mz($,Z,J,Y){try{let{syncAll:X}=await import("./chunk-z1aqe7ms.js"),W=await N3();if(!W)return null;let{SessionService:U}=await import("./chunk-12akr5tm.js");await X(W,U.projectionDeriverForSearch());let Q=w1.resolve(Z),V=A3(W,$,Q,J*4),G=Y?$:$.toLowerCase(),z=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=p4(K.text,G,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)z.push(H);if(z.length>=J)break}return z}catch{return null}}async function Cz($,Z,J,Y){try{let X=await D1.readFile($,"utf8"),U=X.split(`
1578
1578
  `).flatMap((K,H)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:H}]}catch{return[]}});if(!U.some(({event:K})=>K.type==="session_created"))return Rz(U,Z,J,Y);let V=new Map(U.flatMap(({event:K,index:H})=>typeof K.id==="string"?[[K.id,H+1]]:[])),G=E3(b3(X,$)),z=new Map;for(let K of G){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))z.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let H=z.get(K.data.messageId),B=K.data.payload.text;if(H&&typeof B==="string")H.content.push(B)}}return[...z.values()].flatMap((K)=>{let H=p4(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return H?[H]:[]})}catch{return[]}}function Rz($,Z,J,Y){return $.flatMap(({event:X,index:W})=>{if(X.type!=="message")return[];let U=X.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let Q=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((G)=>typeof G==="object"&&G!==null&&G.type==="text"&&typeof G.text==="string").map((G)=>G.text).join(" "):"",V=p4(Q,Z,J,Y,U.role,typeof X.timestamp==="string"?X.timestamp:void 0,W+1);return V?[V]:[]})}function p4($,Z,J,Y,X,W,U){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),G=Math.max(0,V-80),z=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:X,content:(G>0?"...":"")+$.slice(G,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:W,lineNumber:U}}function T3($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1579
1579
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",X=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${X} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1580
1580
  `)}var Pz={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=x(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let X=await j3(Y,{maxResults:15,projectPath:Z.cwd}),W=T3(X);return J.sendMessage(W),{success:!0,message:`found ${X.length} results`,data:{matches:X.length}}}catch(X){let W=X instanceof Error?X.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},M3=Pz;var Sz={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await v0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),e$(Z.workspaceRoot??Z.cwd),await s$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},C3=Sz;import fz from"node:path";function E5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function R3($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function P3($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function kz($,Z){let J=x(Z),Y=$[0],X=a.getInstance(),W=Z0.getInstance(),U=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:fz.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let B=$[1],F=$.slice(2).join(" ").trim();if(!B||!F)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let _=await Z.subagents.resume(B,F),q=`Resumed \`${B}\` as \`${_.session.id}\` (depth ${_.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:B,subagent:_.session}}}if(Y==="clean"){let B=W.cleanupExpiredSessionsForParent(Q??U,0);return J.sendMessage(`已清理 ${B} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${B} agent sessions`}}let V=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{s as Oz,t as Rz}from"./chunk-8y3skwtt.js";import{u as T}from"./chunk-4dthhzfe.js";import{A as Qz,v as Kz,w as e,x as zz,y as Hz,z as Jz}from"./chunk-5vbrcvxg.js";import{E as P,N as o,Q as n,R as t,V as s,ha as Zz,ia as $z,ja as Wz,ka as Yz}from"./chunk-vhamhbej.js";import{ua as Az}from"./chunk-ssymrsyx.js";import"./chunk-y6tkxqjx.js";import{Ya as i,lb as r,ub as a}from"./chunk-1atpfmpe.js";import{Db as M}from"./chunk-mrsc4a55.js";import{Ac as G,Wb as p,bc as m,ec as d,mc as k,nc as v,pc as E,sc as l,xc as R}from"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as Nz}from"./chunk-szdcprq7.js";import"./chunk-fk4wbmv6.js";import{xd as Uz,yd as Vz}from"./chunk-ecf8dh3c.js";import"./chunk-v508x7cg.js";import{Jd as I}from"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import{Wd as wz}from"./chunk-qp2z1r7y.js";import"./chunk-j66r48pz.js";import"./chunk-sjtbp01y.js";import"./chunk-tpa75y39.js";import{Be as _z}from"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import{tf as Lz,wf as Gz}from"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import{$f as h,Zf as y,_f as c}from"./chunk-j7edwwg1.js";import{dg as Bz}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Eg as x}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import{Lg as Dz,Og as Fz}from"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import{Readable as Mz,Writable as kz}from"node:stream";import*as S from"@agentclientprotocol/sdk";import jz from"node:path";import{PROTOCOL_VERSION as yz,RequestError as hz}from"@agentclientprotocol/sdk";import{RequestError as Ez}from"@agentclientprotocol/sdk";import{nanoid as b}from"nanoid";var F=x("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function Tz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function xz(z){let J={};for(let H of z){let W=Tz(H);if(W)J[H.name]=W}return J}function Xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function Sz(z){let J=v(z.metadata);return J?[{type:"text",text:k(J)}]:Xz(z.content)}function bz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as Oz,t as Rz}from"./chunk-yre5973e.js";import{u as T}from"./chunk-7pprh90t.js";import{A as Qz,v as Kz,w as e,x as zz,y as Hz,z as Jz}from"./chunk-k2wnxzdx.js";import{E as P,N as o,Q as n,R as t,V as s,ha as Zz,ia as $z,ja as Wz,ka as Yz}from"./chunk-64z1vsd7.js";import{ua as Az}from"./chunk-1h9pcmkk.js";import"./chunk-y6tkxqjx.js";import{Ya as i,lb as r,ub as a}from"./chunk-z699m84q.js";import{Db as M}from"./chunk-mrsc4a55.js";import{Ac as G,Wb as p,bc as m,ec as d,mc as k,nc as v,pc as E,sc as l,xc as R}from"./chunk-v287pexf.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import{cd as Nz}from"./chunk-nxcc0fbe.js";import"./chunk-fk4wbmv6.js";import{xd as Uz,yd as Vz}from"./chunk-94zrzfyz.js";import"./chunk-v508x7cg.js";import{Jd as I}from"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-7fqsgdee.js";import{Wd as wz}from"./chunk-qp2z1r7y.js";import"./chunk-b29dn3xe.js";import"./chunk-de1s7f6p.js";import"./chunk-tpa75y39.js";import{Be as _z}from"./chunk-2yvte5a7.js";import"./chunk-sqd5ge5s.js";import"./chunk-0b1qj502.js";import"./chunk-cxzx7j0p.js";import{tf as Lz,wf as Gz}from"./chunk-sx4mkt0c.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import{$f as h,Zf as y,_f as c}from"./chunk-j7edwwg1.js";import{dg as Bz}from"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import{Eg as x}from"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import{Lg as Dz,Og as Fz}from"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";import{Readable as Mz,Writable as kz}from"node:stream";import*as S from"@agentclientprotocol/sdk";import jz from"node:path";import{PROTOCOL_VERSION as yz,RequestError as hz}from"@agentclientprotocol/sdk";import{RequestError as Ez}from"@agentclientprotocol/sdk";import{nanoid as b}from"nanoid";var F=x("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function Tz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function xz(z){let J={};for(let H of z){let W=Tz(H);if(W)J[H.name]=W}return J}function Xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function Sz(z){let J=v(z.metadata);return J?[{type:"text",text:k(J)}]:Xz(z.content)}function bz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}class q{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,J,H,W,Y={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=Y;this.messages=[...Y.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(Y.permissionMode),this.updateEgress=new Qz({maxPendingItems:e,maxPendingBytes:zz,writeTimeoutMs:Hz,signal:H.signal,sizeOf:($)=>Buffer.byteLength(JSON.stringify($)),write:async($)=>{await H.sessionUpdate($)},onFailure:($)=>this.handleUpdateEgressFailure($)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([G.loadSession(this.id,this.cwd),G.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await G.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return s.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(F.debug(`[AcpSession ${this.id}] Initializing...`),await G.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),F.debug(`[AcpSession ${this.id}] ACP service context initialized`),await a.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?xz(this.options.mcpServers):void 0,H=P.getInstance().getTerminalService(this.id);if(this.runtime=await o.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,Z)=>{let X=await H.execute($,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(j)=>Z.onOutput?.("stdout",j)});return{exitCode:X.exitCode,stdout:X.stdout,stderr:X.stderr,...X.error?{error:X.error}:{},timedOut:X.failureKind==="timeout",aborted:X.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await $z(this.cwd),F.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=i.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.schedulePendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||Y?.status==="active"||Y?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of Sz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);F.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{F.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Z);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Z)=>{if(await this.setServiceTier(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Z)=>{if(await this.setResponseVerbosity(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Z)=>{if(await this.setCommunicationStyle(Z),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=!1,B,L=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},D=this.runtime.resumeSubagent({agentId:Z,prompt:X,onCompleted:(U)=>{if(j)L(U);else B=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.session.id,status:"in_progress",title:`Resuming ${D.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${D.source.id} at depth ${D.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),j=!0,B)L(B);return D}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,X,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,X,j)},complete:async(Z,X,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,X,j)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,X)},getLogs:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,X)},setLoggingLevel:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Z,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:X,onEvent:(D)=>{if(D.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.toolCall.id,status:"in_progress",title:`Review: ${D.toolCall.function.name}`,content:[],kind:this.mapToolKind(D.toolKind)});else if(D.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.toolCall.id,status:D.result.success?"completed":"failed",content:[]})}}),B=await j.completion,L=(await T.list(this.cwd,this.id)).find((D)=>D.start.reviewId===j.reviewId);if(!L)throw Error(`Review not found: ${j.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:j.reviewId,status:B.status,findings:B.findings.length,content:p(L.start,B)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,X,j)=>{let B=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(j);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:L})},sendToolResult:(Z,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},W=await Wz(z,H),Y=W.data?.action;if(Y==="start_goal"||Y==="resume_goal")this.schedulePendingResume();if(Y==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await G.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let $=W.content||W.message;if($)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){return F.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Yz(this.cwd),J=["model","permissions","theme","config","exit","ide"],W=z.filter((Y)=>!J.includes(Y.name)).map((Y)=>{let $;if(Y.usage){let Z=Y.usage.replace(/^\/\w+\s*/,"").trim();if(Z)$=Z}if(Y.aliases?.length){let Z=`Aliases: ${Y.aliases.join(", ")}`;$=$?`${$} | ${Z}`:Z}return{name:Y.name,description:Y.description,input:$?{hint:$}:void 0}});F.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((Y)=>Y.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),F.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){F.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,Y=H.displayText,$=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Z;if($!==void 0)Z=l($).schema;if(Y.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(Y)}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(Y.trim()))return this.handleSlashCommand(Y,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(F.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let X=new AbortController,j=!1,B,L=new Promise((D)=>{B=D});this.pendingPrompt=X,this.pendingPromptCompletion=L;try{if(F.debug(`[AcpSession ${this.id}] Received prompt: ${Y.slice(0,100)}...`),Zz(Y)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(Y,X.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:X.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},U=await r(this.agent.chatStream(W,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{let w=Q.toolCall,K=w.function.name;if(K===E)break;let O=this.mapToolKind(Q.toolKind),V=`Executing ${K}`;if(K==="Task"&&"function"in w)try{let N=JSON.parse(w.function.arguments),_=N.resume_from??N.resume;if(typeof _==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:O});break}case"tool_progress":{let w=Q.toolCall;if(w.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{let w=Q.toolCall;if(w.function.name===E)break;let K=Q.result,O=[],V=K.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let _ of V.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;O.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))O.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let _=w.function.name,Pz=t(d(n(_,K),m));O.push({type:"content",content:{type:"text",text:Pz}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))O.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=K.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:N,content:O});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
@@ -1 +1 @@
1
- import{Yd as a,Zd as b,_d as c}from"./chunk-j66r48pz.js";import"./chunk-cyw6cpac.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
1
+ import{Yd as a,Zd as b,_d as c}from"./chunk-b29dn3xe.js";import"./chunk-sx4mkt0c.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +1 @@
1
- import{Ab as p,Bb as q,Cb as r,cb as a,db as b,fb as c,jb as d,kb as e,lb as f,mb as g,nb as h,ob as i,pb as j,qb as k,vb as l,wb as m,xb as n,yb as o}from"./chunk-1atpfmpe.js";import"./chunk-mrsc4a55.js";import"./chunk-t4y3h47y.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-qp2z1r7y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-yvyqhw5q.js";import"./chunk-cxzx7j0p.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-807x1cw8.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{Ab as p,Bb as q,Cb as r,cb as a,db as b,fb as c,jb as d,kb as e,lb as f,mb as g,nb as h,ob as i,pb as j,qb as k,vb as l,wb as m,xb as n,yb as o}from"./chunk-z699m84q.js";import"./chunk-mrsc4a55.js";import"./chunk-v287pexf.js";import"./chunk-0qsssahq.js";import"./chunk-56qew7w0.js";import"./chunk-wwvb6znp.js";import"./chunk-egczvfsv.js";import"./chunk-qp2z1r7y.js";import"./chunk-tpa75y39.js";import"./chunk-2yvte5a7.js";import"./chunk-0b1qj502.js";import"./chunk-cxzx7j0p.js";import"./chunk-7sna3js9.js";import"./chunk-m8ss9rmx.js";import"./chunk-j7edwwg1.js";import"./chunk-kfpzrmq7.js";import"./chunk-yk9pxkc1.js";import"./chunk-fhnkyqfb.js";import"./chunk-26wse17p.js";import"./chunk-hcm55r3d.js";import"./chunk-pxqgt2h6.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,4 +1,4 @@
1
- import{O as P}from"./chunk-vhamhbej.js";import{_a as K}from"./chunk-1atpfmpe.js";import{Ac as B,Tb as G,Ub as N,Vb as S,Wb as O,Xb as s}from"./chunk-t4y3h47y.js";import{Jc as j}from"./chunk-56qew7w0.js";import{Jd as q}from"./chunk-wwvb6znp.js";import{be as v}from"./chunk-sjtbp01y.js";import{bh as z}from"./chunk-qb0sqh29.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{O as P}from"./chunk-64z1vsd7.js";import{_a as K}from"./chunk-z699m84q.js";import{Ac as B,Tb as G,Ub as N,Vb as S,Wb as O,Xb as s}from"./chunk-v287pexf.js";import{Jc as j}from"./chunk-56qew7w0.js";import{Jd as q}from"./chunk-wwvb6znp.js";import{be as v}from"./chunk-de1s7f6p.js";import{bh as z}from"./chunk-qb0sqh29.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -0,0 +1 @@
1
+ import{Xc as a,Yc as b}from"./chunk-hr79r0ee.js";import"./chunk-pxqgt2h6.js";import"./chunk-hfrcwkc8.js";export{a as globalOptions,b as cliConfig};