blade-code 0.10.45 → 0.10.46

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 (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-ereap4qs.js → chunk-1atpfmpe.js} +1 -1
  3. package/dist/{chunk-enybb4b6.js → chunk-2yjm55cb.js} +1 -1
  4. package/dist/{chunk-73tvqr7n.js → chunk-4dthhzfe.js} +1 -1
  5. package/dist/{chunk-4ny0av9k.js → chunk-4qvna4m2.js} +1 -1
  6. package/dist/chunk-54d7545y.js +1 -0
  7. package/dist/{chunk-kebr832m.js → chunk-5vbrcvxg.js} +1 -1
  8. package/dist/{chunk-15bz0eah.js → chunk-67zpsrst.js} +1 -1
  9. package/dist/{chunk-0yg3bgz2.js → chunk-6h28xs47.js} +1 -1
  10. package/dist/{chunk-4tmjbf35.js → chunk-7qpbtnsa.js} +1 -1
  11. package/dist/{chunk-ay81q381.js → chunk-807x1cw8.js} +1 -1
  12. package/dist/{chunk-yt4ejj2z.js → chunk-8kzdhgys.js} +1 -1
  13. package/dist/{chunk-jejrwnht.js → chunk-8y3skwtt.js} +1 -1
  14. package/dist/{chunk-5h6k5bkc.js → chunk-9mnbnyrc.js} +1 -1
  15. package/dist/{chunk-n80jaza9.js → chunk-aarwre5y.js} +1 -1
  16. package/dist/{chunk-s1yhkewh.js → chunk-cyw6cpac.js} +1 -1
  17. package/dist/{chunk-sb7z2kch.js → chunk-ecf8dh3c.js} +1 -1
  18. package/dist/{chunk-brrp1cw0.js → chunk-fz91aw1w.js} +1 -1
  19. package/dist/{chunk-rgwnrxrb.js → chunk-j66r48pz.js} +1 -1
  20. package/dist/{chunk-e7xwf4md.js → chunk-jmksywff.js} +1 -1
  21. package/dist/{chunk-5649wxm6.js → chunk-mqmf40p2.js} +1 -1
  22. package/dist/{chunk-rpvpkeb9.js → chunk-n5dkq98k.js} +1 -1
  23. package/dist/{chunk-5fdd1442.js → chunk-qbvm38ba.js} +1 -1
  24. package/dist/{chunk-pa16h87y.js → chunk-qmxfkkgn.js} +1 -1
  25. package/dist/{chunk-v6x2s43e.js → chunk-s5205dnv.js} +1 -1
  26. package/dist/{chunk-6rymht2v.js → chunk-sh58bey1.js} +1 -1
  27. package/dist/{chunk-z0fytz7s.js → chunk-sjtbp01y.js} +1 -1
  28. package/dist/{chunk-ywcxq2k7.js → chunk-ssymrsyx.js} +1 -1
  29. package/dist/{chunk-bh9f6mn6.js → chunk-szdcprq7.js} +1 -1
  30. package/dist/{chunk-s80bapcn.js → chunk-sztrmhgd.js} +1 -1
  31. package/dist/{chunk-wzvapee1.js → chunk-t4y3h47y.js} +1 -1
  32. package/dist/{chunk-dpe823m6.js → chunk-v6ydjg9c.js} +1 -1
  33. package/dist/{chunk-knxwdyec.js → chunk-vhamhbej.js} +3 -3
  34. package/dist/chunk-vhxtzacr.js +1 -0
  35. package/dist/{chunk-qznhw24r.js → chunk-xes0szvj.js} +2 -2
  36. package/dist/{chunk-gryj7pn3.js → chunk-yha9fpc7.js} +1 -1
  37. package/dist/{chunk-2fv3pgmf.js → chunk-yrd794kb.js} +1 -1
  38. package/dist/{chunk-ay413kfr.js → chunk-yvyqhw5q.js} +1 -1
  39. package/package.json +2 -2
  40. package/dist/chunk-3sxwsb8t.js +0 -1
  41. package/dist/chunk-aee982fx.js +0 -1
@@ -1 +1 @@
1
- import{$c as c,Zc as a,_c as b}from"./chunk-yt4ejj2z.js";import"./chunk-v9tzhe90.js";import"./chunk-sb7z2kch.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-sqd5ge5s.js";import"./chunk-s1yhkewh.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-ay81q381.js";import"./chunk-bvf9syb2.js";import"./chunk-q78s028m.js";import"./chunk-qb0sqh29.js";import"./chunk-hfrcwkc8.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{$c as c,Zc as a,_c as b}from"./chunk-8kzdhgys.js";import"./chunk-v9tzhe90.js";import"./chunk-ecf8dh3c.js";import"./chunk-v508x7cg.js";import"./chunk-wwvb6znp.js";import"./chunk-sqd5ge5s.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{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1,4 +1,4 @@
1
- import{ma as R,na as u0,sa as kJ,ta as F9,ua as g0}from"./chunk-ywcxq2k7.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-ereap4qs.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-wzvapee1.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-sb7z2kch.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-rgwnrxrb.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-z0fytz7s.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-ay413kfr.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-s1yhkewh.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-ay81q381.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-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`
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-5649wxm6.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-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(`
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>
@@ -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-gryj7pn3.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-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(`
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=[`**后台任务列表**
@@ -0,0 +1 @@
1
+ import{Xc as a,Yc as b}from"./chunk-s5205dnv.js";import"./chunk-807x1cw8.js";import"./chunk-hfrcwkc8.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{Qf as Q}from"./chunk-s1yhkewh.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-ay81q381.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-gryj7pn3.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-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...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1 +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-wzvapee1.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-ay81q381.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-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 +1 @@
1
- import{a as o}from"./chunk-15bz0eah.js";import"./chunk-ay81q381.js";import"./chunk-hfrcwkc8.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-67zpsrst.js";import"./chunk-807x1cw8.js";import"./chunk-hfrcwkc8.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -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-s80bapcn.js"),{createChatServiceAsync:J}=await import("./chunk-6cx4t8r6.js"),{resolveModelConfig:W}=await import("./chunk-fer18bbe.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-5h6k5bkc.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-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} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.45",
3
+ "version": "0.10.46",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -115,7 +115,7 @@
115
115
  "zustand": "^5.0.14"
116
116
  },
117
117
  "devDependencies": {
118
- "@biomejs/biome": "^2.5.7",
118
+ "@biomejs/biome": "2.5.7",
119
119
  "@types/bun": "^1.3.14",
120
120
  "@types/json-schema": "^7.0.15",
121
121
  "@types/lodash-es": "^4.17.12",
@@ -1 +0,0 @@
1
- import{Xc as a,Yc as b}from"./chunk-v6x2s43e.js";import"./chunk-ay81q381.js";import"./chunk-hfrcwkc8.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-15bz0eah.js";import"./chunk-ay81q381.js";import"./chunk-hfrcwkc8.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};