blade-code 0.10.121 → 0.10.122

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 (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-n1t4vdw5.js → chunk-0axgw6c3.js} +1 -1
  3. package/dist/{chunk-ssmd3rn9.js → chunk-0gyv0ws4.js} +1 -1
  4. package/dist/{chunk-8myvrket.js → chunk-1dscrttm.js} +1 -1
  5. package/dist/{chunk-pccb23xv.js → chunk-2cdnsdx2.js} +1 -1
  6. package/dist/{chunk-863ynx9m.js → chunk-2kgp4h99.js} +1 -1
  7. package/dist/{chunk-szw16t85.js → chunk-4jt2gxzt.js} +1 -1
  8. package/dist/{chunk-akcn83x5.js → chunk-5h1x1a11.js} +1 -1
  9. package/dist/{chunk-dw9wcrtp.js → chunk-5n1ymw0p.js} +1 -1
  10. package/dist/{chunk-pttzjrg7.js → chunk-6xmz6mn0.js} +1 -1
  11. package/dist/{chunk-pqt9p2tb.js → chunk-7k4ehjfj.js} +1 -1
  12. package/dist/{chunk-ymaxdwy1.js → chunk-7w1z4hdy.js} +1 -1
  13. package/dist/{chunk-kaqz84w8.js → chunk-9byspsen.js} +1 -1
  14. package/dist/{chunk-vsr1g5ke.js → chunk-9vrsygd9.js} +1 -1
  15. package/dist/{chunk-d75myaef.js → chunk-b62w3ceq.js} +1 -1
  16. package/dist/chunk-bn6g1g8k.js +169 -0
  17. package/dist/{chunk-gnvepc4p.js → chunk-cqg8xkmd.js} +1 -1
  18. package/dist/{chunk-vxxcdarq.js → chunk-d1gnxqpg.js} +1 -1
  19. package/dist/{chunk-v9bfzh20.js → chunk-d59y2wwj.js} +1 -1
  20. package/dist/{chunk-6x5c8qa6.js → chunk-dwqqvn2w.js} +1 -1
  21. package/dist/{chunk-vke2en0x.js → chunk-edqe893j.js} +1 -1
  22. package/dist/chunk-gades6fm.js +1 -0
  23. package/dist/{chunk-fwmym1zk.js → chunk-gqfa43gv.js} +1 -1
  24. package/dist/{chunk-v5d7he8r.js → chunk-j0efq6yy.js} +1 -1
  25. package/dist/{chunk-b1rqfaea.js → chunk-j19j9ypt.js} +1 -1
  26. package/dist/{chunk-9p4jkczh.js → chunk-j8ae2jpv.js} +2 -2
  27. package/dist/{chunk-88krdjg8.js → chunk-jg81tz55.js} +1 -1
  28. package/dist/{chunk-rvvvx553.js → chunk-jhcxqhj9.js} +1 -1
  29. package/dist/{chunk-e2b6d9mw.js → chunk-khewsbnt.js} +1 -1
  30. package/dist/{chunk-y7wwx4jn.js → chunk-mzjw10nw.js} +1 -1
  31. package/dist/{chunk-5yd5k1tf.js → chunk-n8xv0whr.js} +1 -1
  32. package/dist/chunk-nm7cm174.js +1 -0
  33. package/dist/{chunk-a31m4s8k.js → chunk-p6spv3yg.js} +1 -1
  34. package/dist/{chunk-w9gj8etn.js → chunk-qk0yyvgk.js} +3 -3
  35. package/dist/{chunk-wgv86d7e.js → chunk-tyvzbbwd.js} +1 -1
  36. package/dist/{chunk-r72e7yj0.js → chunk-xb5g8q82.js} +1 -1
  37. package/dist/{chunk-z2w3d9gy.js → chunk-yyp7awr7.js} +1 -1
  38. package/dist/{chunk-2jx9yez1.js → chunk-zqt0f9hc.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-khwmnyjg.js +0 -169
  41. package/dist/chunk-myg02cas.js +0 -1
  42. package/dist/chunk-nhnkbddn.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Aa as EZ}from"./chunk-dabq8kdx.js";import{Da as A,Ea as n0,Ja as dY,Ka as A7,La as i0}from"./chunk-gnvepc4p.js";import{Ma as Y8,Oa as AQ,Qa as CQ,Ra as VZ,hb as MQ}from"./chunk-fpjhg6ce.js";import{Ab as W4,Cb as B5,Db as U4,Eb as X4,Gb as g9,Hb as G$,Nb as C4,Ob as TY,Pb as rJ,Rb as S2,Sb as BY,Xb as m7,_b as p7,ib as h$,jb as x1,kb as X7,lb as B1,mb as i3,nb as H7,ob as o3,pb as K7,qb as w7,rb as YJ,vb as V0,xb as u1}from"./chunk-fwmym1zk.js";import{Ac as X2,Bc as MZ,Bd as GZ,Cc as V2,Cd as r0,Dc as a4,Dd as h1,Ec as X1,Ed as HY,Fc as C1,Fd as KY,Gc as H2,Hc as M1,Ic as P1,Id as IY,Jc as Q6,Kc as R1,Lc as W6,Mc as U6,Md as d7,Nc as q$,Oc as X6,Pc as xZ,Qc as B2,Rc as V6,Rd as wY,Sc as H6,Sd as zY,Tc as K6,Uc as w6,Ud as t,Vc as hZ,Wc as gZ,Yc as uZ,ec as G9,fc as _0,gc as $2,hc as Z1,ic as t2,jc as BZ,kc as Y4,lc as Q4,mc as t3,nc as e3,oc as VY,pc as NZ,pd as b4,qc as U1,rc as OZ,rd as A0,sc as r4,sd as V$,tc as y$,uc as I$,vc as w2,wc as K2,xc as z2,yc as J6,zc as Y6}from"./chunk-863ynx9m.js";import{Vd as d,Wd as XJ,Xd as VJ,Yd as a9,_d as g1}from"./chunk-q265drks.js";import{$d as RQ,ce as TQ,le as fQ,re as SQ}from"./chunk-7dykmcjj.js";import{Ce as y9,De as k9}from"./chunk-twdfyk78.js";import{Pe as V4,Qe as B0,Re as y,Ue as L0,Ve as i6,We as d1,Xe as l$,Ye as E5,Ze as V1,_e as g7,df as y1}from"./chunk-szw16t85.js";import{ef as q1}from"./chunk-ye4wyq1k.js";import{if as F5,jf as u7,kf as x7,pf as EY,qf as n6}from"./chunk-kpqdfn9z.js";import{sf as y0,tf as e$}from"./chunk-b41den40.js";import{uf as SY}from"./chunk-8qp8v96d.js";import{wf as YY,xf as QY,yf as WY}from"./chunk-8myvrket.js";import{Af as e6,Bf as $4,Df as Z4,Ef as J4,Ff as s$,Gf as BJ,If as O$,Jf as H$,Kf as Y$,Lf as Z8,Mf as S1,Nf as j4,Of as b1,Pf as N1,Qf as XY,Uf as d5,Wf as I0,Xf as D$,Zf as r6,_f as GY,zf as t6}from"./chunk-e2b6d9mw.js";import{ag as n$,cg as B$,dg as I6,eg as J9,fg as Y9,gg as _2,hg as Q9,ig as W9,jg as L6,kg as U9,lg as _6}from"./chunk-0zzh482s.js";import{mg as sY,og as UY,pg as O4,qg as I9}from"./chunk-adkpwx6c.js";import{sg as JZ,ug as T0}from"./chunk-b1rqfaea.js";import{vg as c2,wg as zZ,xg as l2,yg as E1}from"./chunk-2t6b962t.js";import{$g as D1,Ag as L9,Ah as JY,Bh as H0,Fg as O9,Hg as s5,Mg as uY,Qg as b9,Sg as eJ,Ug as W7,Vg as U7,ch as a3,mh as M7,nh as P7,oh as R7,ph as T7,qh as b5,rh as f7,sh as c$,th as S7,uh as k7,vh as v7,xh as w9,zh as _Y}from"./chunk-88krdjg8.js";import{Eh as x$}from"./chunk-kz15jy62.js";import{Fh as z6,Gh as F6,Hh as z,Ih as iZ,Jh as f,Kh as I}from"./chunk-9fgkg1vr.js";import{Mh as iJ,Oh as nJ}from"./chunk-pykxe413.js";import{Rh as E6,Th as M}from"./chunk-kzzty3v5.js";import{ti as a}from"./chunk-w4xqaw4h.js";import{yi as $Y,zi as ZY}from"./chunk-r6svhe3w.js";import{Ai as eY,Di as aY}from"./chunk-a4dmw23t.js";import{Hi as YQ}from"./chunk-dw9wcrtp.js";import{Ni as DY,Oi as d0}from"./chunk-ncqagb27.js";import{Si as s2,Ui as m$,Wi as tJ,Xi as Z9,Zi as s}from"./chunk-spxb931p.js";import{$i as a0}from"./chunk-m7b779kd.js";import{randomUUID as u4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=String.raw`
1
+ import{Aa as EZ}from"./chunk-dabq8kdx.js";import{Da as A,Ea as n0,Ja as dY,Ka as A7,La as i0}from"./chunk-cqg8xkmd.js";import{Ma as Y8,Oa as AQ,Qa as CQ,Ra as VZ,hb as MQ}from"./chunk-fpjhg6ce.js";import{Ab as W4,Cb as B5,Db as U4,Eb as X4,Gb as g9,Hb as G$,Nb as C4,Ob as TY,Pb as rJ,Rb as S2,Sb as BY,Xb as m7,_b as p7,ib as h$,jb as x1,kb as X7,lb as B1,mb as i3,nb as H7,ob as o3,pb as K7,qb as w7,rb as YJ,vb as V0,xb as u1}from"./chunk-gqfa43gv.js";import{Ac as X2,Bc as MZ,Bd as GZ,Cc as V2,Cd as r0,Dc as a4,Dd as h1,Ec as X1,Ed as HY,Fc as C1,Fd as KY,Gc as H2,Hc as M1,Ic as P1,Id as IY,Jc as Q6,Kc as R1,Lc as W6,Mc as U6,Md as d7,Nc as q$,Oc as X6,Pc as xZ,Qc as B2,Rc as V6,Rd as wY,Sc as H6,Sd as zY,Tc as K6,Uc as w6,Ud as t,Vc as hZ,Wc as gZ,Yc as uZ,ec as G9,fc as _0,gc as $2,hc as Z1,ic as t2,jc as BZ,kc as Y4,lc as Q4,mc as t3,nc as e3,oc as VY,pc as NZ,pd as b4,qc as U1,rc as OZ,rd as A0,sc as r4,sd as V$,tc as y$,uc as I$,vc as w2,wc as K2,xc as z2,yc as J6,zc as Y6}from"./chunk-2kgp4h99.js";import{Vd as d,Wd as XJ,Xd as VJ,Yd as a9,_d as g1}from"./chunk-q265drks.js";import{$d as RQ,ce as TQ,le as fQ,re as SQ}from"./chunk-7dykmcjj.js";import{Ce as y9,De as k9}from"./chunk-twdfyk78.js";import{Pe as V4,Qe as B0,Re as y,Ue as L0,Ve as i6,We as d1,Xe as l$,Ye as E5,Ze as V1,_e as g7,df as y1}from"./chunk-4jt2gxzt.js";import{ef as q1}from"./chunk-ye4wyq1k.js";import{if as F5,jf as u7,kf as x7,pf as EY,qf as n6}from"./chunk-kpqdfn9z.js";import{sf as y0,tf as e$}from"./chunk-b41den40.js";import{uf as SY}from"./chunk-8qp8v96d.js";import{wf as YY,xf as QY,yf as WY}from"./chunk-1dscrttm.js";import{Af as e6,Bf as $4,Df as Z4,Ef as J4,Ff as s$,Gf as BJ,If as O$,Jf as H$,Kf as Y$,Lf as Z8,Mf as S1,Nf as j4,Of as b1,Pf as N1,Qf as XY,Uf as d5,Wf as I0,Xf as D$,Zf as r6,_f as GY,zf as t6}from"./chunk-khewsbnt.js";import{ag as n$,cg as B$,dg as I6,eg as J9,fg as Y9,gg as _2,hg as Q9,ig as W9,jg as L6,kg as U9,lg as _6}from"./chunk-0zzh482s.js";import{mg as sY,og as UY,pg as O4,qg as I9}from"./chunk-adkpwx6c.js";import{sg as JZ,ug as T0}from"./chunk-j19j9ypt.js";import{vg as c2,wg as zZ,xg as l2,yg as E1}from"./chunk-2t6b962t.js";import{$g as D1,Ag as L9,Ah as JY,Bh as H0,Fg as O9,Hg as s5,Mg as uY,Qg as b9,Sg as eJ,Ug as W7,Vg as U7,ch as a3,mh as M7,nh as P7,oh as R7,ph as T7,qh as b5,rh as f7,sh as c$,th as S7,uh as k7,vh as v7,xh as w9,zh as _Y}from"./chunk-jg81tz55.js";import{Eh as x$}from"./chunk-kz15jy62.js";import{Fh as z6,Gh as F6,Hh as z,Ih as iZ,Jh as f,Kh as I}from"./chunk-9fgkg1vr.js";import{Mh as iJ,Oh as nJ}from"./chunk-pykxe413.js";import{Rh as E6,Th as M}from"./chunk-kzzty3v5.js";import{ti as a}from"./chunk-w4xqaw4h.js";import{yi as $Y,zi as ZY}from"./chunk-r6svhe3w.js";import{Ai as eY,Di as aY}from"./chunk-a4dmw23t.js";import{Hi as YQ}from"./chunk-5n1ymw0p.js";import{Ni as DY,Oi as d0}from"./chunk-ncqagb27.js";import{Si as s2,Ui as m$,Wi as tJ,Xi as Z9,Zi as s}from"./chunk-spxb931p.js";import{$i as a0}from"./chunk-m7b779kd.js";import{randomUUID as u4}from"crypto";import{randomUUID as sQ}from"node:crypto";var iQ=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);
@@ -848,7 +848,7 @@ ${$1}
848
848
  </approved-plan>
849
849
 
850
850
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof q==="string")F0=q+M$;else F0=[...q,{type:"text",text:M$}]}S=yield*this.runLoop(F0,b,{...k,inputMessageId:void 0})}if(!this.sessionRuntime||!v)return S;let r=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,prematureStopPattern:S.success?Q7(S.finalMessage):void 0});if(r)yield{kind:"goal_updated",goal:r};if(!S.success||b.signal?.aborted){if(r=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),r)yield{kind:"goal_updated",goal:r}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(v,b.signal);let $0=S.success&&!b.signal?.aborted&&h<20,p=GH(S);if(x=await this.sessionRuntime.finishTurn(v,{continuePending:$0,...p?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),x){h++,N=!0,E=!1,O=null,q="",R=void 0,T="",C=void 0,j=m(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:e()};continue}if(!S.success||b.signal?.aborted)return S;if(r=await this.sessionRuntime.getGoal(),!r||r.status!=="active"&&r.status!=="verifying")return S;let Q$=await this.sessionRuntime.beginGoalContinuation();if(!Q$)return S;let Y0=await this.sessionRuntime.prepareGoalContinuation(Q$);if(!Y0.ok){if(Y0.goal)yield{kind:"goal_updated",goal:Y0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:Y0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}O=Y0.goal,_=Y0,x=await this.sessionRuntime.beginTurn("goal"),N=!1,E=!0,q=P8(O),R=void 0,j=void 0,yield{kind:"goal_frontier_updated",goal:Y0.goal,frontier:Y0.frontier,tasks:Y0.tasks},yield{kind:"goal_continuation_started",goal:O,continuation:O.continuationCount,...O.prematureStop?{prematureStopPattern:O.prematureStop.pattern,prematureStopCount:O.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:O}}}finally{if(this.sessionRuntime&&x)await this.sessionRuntime.finishTurn(x)}}let D=typeof K==="string"?K:K.filter((q)=>q.type==="text").map((q)=>q.text).join(`
851
- `),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-z2w3d9gy.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,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}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,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 Q=this.buildLoopDependencies();return p7(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={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}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,n.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
851
+ `),F={id:this.generateTaskId(),type:"simple",prompt:D};return{success:!0,finalMessage:(await this.executeTask(F)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-yyp7awr7.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await g$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:S2,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}),Q;if(typeof $==="string")Q=L2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:L2(U.text)}:X)}else Q=[{type:"text",text:L2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){n.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||M());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await g$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:S2,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 Q=this.buildLoopDependencies();return p7(Q,$,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)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,W=J.error===void 0,U=J.output,X={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}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:X}],H=m7(Y,X);if(H)V.push(H);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}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=$,n.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((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);n.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);n.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){n.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){n.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await g$({projectPath:this.sessionRuntime?.workspaceRoot??M(),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("系统提示配置验证成功"),n.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await a6({sessionId:"default",configDir:s(),workspaceRoot:M(),resourceRoot:M(),agentResources:this.agentResources});n.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;n.debug(`Builtin tools registered: ${Z} tools`),n.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw n.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await j6({workspaceRoot:M(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){n.debug("No MCP servers configured");return}let Z=i0.createIsolated({artifactWriter:new F2(`legacy-${BH()}`)});this.legacyMcpRegistry=Z;for(let[W,U]of Object.entries($))try{n.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,U),n.debug(`MCP server "${W}" connected`)}catch(X){n.warn(`Warning: MCP server "${W}" connection failed:`,X)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(j2(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.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)n.debug(`Registered ${Y.tools.length} MCP tools`),n.debug(`[MCP Tools] ${Y.tools.map((W)=>W.name).join(", ")}`)}catch($){n.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await I0(M());if(this.agentResources=r6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)n.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else n.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;n.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let W=Q.match(/^(\w+)\(.*\)$/);if(W&&W[1]===Y.name)return!0;return!1})});return n.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)n.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(`
852
852
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;n.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return n.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let W=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${W?` range="${W}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
853
853
 
854
854
  <system-reminder>
@@ -1658,7 +1658,7 @@ ${J}
1658
1658
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1659
1659
  `)}}case"create":{let X=xB(W);if("error"in X)return Y.sendMessage(`创建失败:${X.error}`),{success:!1,error:X.error};let V={prompt:X.prompt,projectPath:U,trigger:X.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(V),K=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1660
1660
  ${VZ(H.trigger)} · 下次运行: ${K}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let K=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${K}`),{success:!1,error:K}}}case"remove":case"rm":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(X);return Y.sendMessage(V?`[OK] 已删除 \`${X}\``:`未找到 \`${X}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let X=W[0];if(!X)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(X,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${X}\``:`未找到 \`${X}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let X=W[0];if(!X)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await hB(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let H=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
1661
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-v1cmz2bw.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-wgv86d7e.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
1661
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var PQ=gB();import*as t1 from"node:fs/promises";import*as e1 from"node:path";async function kQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??s2(Q??M());if(!W){let B=await uB($,Q??M(),J,Y);if(B)return B}let X;try{X=(await t1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>e1.join(U,G))}catch{return[]}let H=(await Promise.all(X.map(async(B)=>{try{let G=await t1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),K=[],w=Y?$:$.toLowerCase();for(let B of H){if(K.length>=J)break;let G=e1.basename(B,".jsonl"),_=await dB(B,w,Y,G);if(K.push(..._),K.length>=J){K.length=J;break}}return K}async function uB($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-v1cmz2bw.js"),W=await fQ();if(!W)return null;let{SessionService:U}=await import("./chunk-tyvzbbwd.js");await Q(W,U.projectionDeriverForSearch());let X=e1.resolve(Z),V=SQ(W,$,X,J*4),H=Y?$:$.toLowerCase(),K=[];for(let w of V){if(w.role!=="user"&&w.role!=="assistant")continue;let B=HZ(w.text,H,Y,w.session_id,w.role,w.timestamp??void 0,0);if(B)K.push(B);if(K.length>=J)break}return K}catch{return null}}async function dB($,Z,J,Y){try{let Q=await t1.readFile($,"utf8"),U=Q.split(`
1662
1662
  `).flatMap((w,B)=>{if(!w.trim())return[];try{return[{event:JSON.parse(w),index:B}]}catch{return[]}});if(!U.some(({event:w})=>w.type==="session_created"))return mB(U,Z,J,Y);let V=new Map(U.flatMap(({event:w,index:B})=>typeof w.id==="string"?[[w.id,B+1]]:[])),H=RQ(TQ(Q,$)),K=new Map;for(let w of H){if(w.type==="message_created"&&(w.data.role==="user"||w.data.role==="assistant"))K.set(w.data.messageId,{role:w.data.role,content:[],timestamp:w.timestamp,lineNumber:V.get(w.id)??0});if(w.type==="part_created"&&w.data.partType==="text"){let B=K.get(w.data.messageId),G=w.data.payload.text;if(B&&typeof G==="string")B.content.push(G)}}return[...K.values()].flatMap((w)=>{let B=HZ(w.content.join(" "),Z,J,Y,w.role,w.timestamp,w.lineNumber);return B?[B]:[]})}catch{return[]}}function mB($,Z,J,Y){return $.flatMap(({event:Q,index:W})=>{if(Q.type!=="message")return[];let U=Q.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let X=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",V=HZ(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function HZ($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),H=Math.max(0,V-80),K=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,K).replace(/\n/g," ")+(K<$.length?"...":""),timestamp:W,lineNumber:U}}function vQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1663
1663
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1664
1664
  `)}var pB={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=g(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await kQ(Y,{maxResults:15,projectPath:Z.cwd}),W=vQ(Q);return J.sendMessage(W),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let W=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${W}`),{success:!1,error:W}}}},yQ=pB;var cB={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await D$(J,async(Y)=>{await Y.skills.refresh(),N1(J),await b1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return y().addAssistantMessage(Y),{success:!1,error:Y}}}},IQ=cB;import lB from"node:path";function v4($){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 xQ($){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 hQ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function iB($,Z){let J=g(Z),Y=$[0],Q=Z0.getInstance(),W=K0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:lB.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let G=$[1],_=$.slice(2).join(" ").trim();if(!G||!_)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 D=await Z.subagents.resume(G,_),F=`Resumed \`${G}\` as \`${D.session.id}\` (depth ${D.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:G,subagent:D.session}}}if(Y==="clean"){let G=W.cleanupExpiredSessionsForParent(X??U,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let V=[`**后台任务列表**
@@ -1 +1 @@
1
- import{Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g}from"./chunk-863ynx9m.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-8qp8v96d.js";import"./chunk-adkpwx6c.js";import"./chunk-2t6b962t.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-w4xqaw4h.js";import"./chunk-a4dmw23t.js";import"./chunk-dw9wcrtp.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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{Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g}from"./chunk-2kgp4h99.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-8qp8v96d.js";import"./chunk-adkpwx6c.js";import"./chunk-2t6b962t.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-w4xqaw4h.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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,4 +1,4 @@
1
- import{e as w$,f as Q$}from"./chunk-anjpwev3.js";import{g as H1}from"./chunk-nq0w1j1a.js";import{s as A0,t as k4,u as q4,v as f4,w as C4}from"./chunk-ymaxdwy1.js";import{x as G0}from"./chunk-vsr1g5ke.js";import{A as Fx,B as Lx,C as iO,D as Dx,y as A4,z as _x}from"./chunk-n1t4vdw5.js";import{G as K4,H as cx,I as K$,L as U4,M as S0,N as e1,O as _1,P as ux,Q as d1,R as F4,S as cO,T as L4,U as D4,V as bx,W as i0,X as v1,Y as x0,Z as V0,aa as Q1,ba as Z1,ca as R$,da as H4,ea as b4,fa as d4,ga as v4,ha as i4,ia as l4,ja as c4,ka as a4,la as o4,ma as n4,na as t4,qa as $$,ta as h$,ya as U$}from"./chunk-w9gj8etn.js";import{Fa as Cx,La as kO}from"./chunk-gnvepc4p.js";import{$a as J$,Pa as S1,Sa as F$,Ta as Ox,Ua as j4,Va as M4,Wa as L$,Xa as D$,Ya as xx,Za as H$,_a as U0,ab as Y$,bb as N$,cb as T4,db as S4,eb as I4,fb as R4,gb as Bx,hb as Yx}from"./chunk-fpjhg6ce.js";import{Hb as u1,Qb as K0,sb as w0,tb as P,vb as k,wb as _4}from"./chunk-fwmym1zk.js";import{$b as c1}from"./chunk-sca5q3tt.js";import{Ad as z4,Bc as J4,Cc as m1,Dc as Y4,Ec as n0,Fc as N4,Gd as V4,Hd as G4,Ic as f1,Jd as M0,Md as h1,Rd as B4,Sd as g1,Td as p1,Ud as E,Vc as W4,ed as X4,od as r0,pd as B0,uc as Z4,wd as $1,xd as a1,yd as w1}from"./chunk-863ynx9m.js";import{Qe as S$,Ue as BO,Ye as mx,df as PO}from"./chunk-szw16t85.js";import{ef as P1}from"./chunk-ye4wyq1k.js";import{vf as w4}from"./chunk-8qp8v96d.js";import{xf as B1}from"./chunk-8myvrket.js";import{Ff as I$,Hf as z$,Kf as u4,Of as c0,Pf as a0,Tf as l$,Wf as gO,Xf as o0,_f as c$}from"./chunk-e2b6d9mw.js";import{og as hx,pg as Q4}from"./chunk-adkpwx6c.js";import{tg as Rx,ug as b0}from"./chunk-b1rqfaea.js";import{Bh as l0,Mg as fx,eh as O4,hh as x4,jh as $4,wh as kx}from"./chunk-88krdjg8.js";import{Eh as E1}from"./chunk-kz15jy62.js";import{Fh as y,Hh as W,Ih as pO,Kh as YO}from"./chunk-9fgkg1vr.js";import{Mh as L1,Ph as y1}from"./chunk-pykxe413.js";import{Th as s}from"./chunk-kzzty3v5.js";import{ti as $O}from"./chunk-w4xqaw4h.js";import{zi as X0}from"./chunk-r6svhe3w.js";import{Bi as yx,Ci as rx,Ei as Px,Fi as ex}from"./chunk-a4dmw23t.js";import{Hi as H0}from"./chunk-dw9wcrtp.js";import{Oi as Jx}from"./chunk-ncqagb27.js";import{Ui as z1,Yi as jx,Zi as F1}from"./chunk-spxb931p.js";import{$i as wx}from"./chunk-m7b779kd.js";var V5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function G5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as Nx,readFileSync as Y1}from"node:fs";import{createServer as d3}from"node:http";import{networkInterfaces as v3}from"node:os";import{dirname as i3,extname as l3,join as Y0}from"node:path";import{fileURLToPath as c3}from"node:url";import{brotliCompressSync as a3,gzipSync as o3,constants as n3}from"node:zlib";import{Hono as t3}from"hono";import{cors as s3}from"hono/cors";import{WebSocketServer as r3}from"ws";var D0=$O("Service"),w2=30000,Q2=new Set(["completed","failed","cancelled","interrupted"]);class I1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??Bx.getInstance(),this.tickMs=O.tickMs??w2}start(){if(this.timer)return;D0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=k.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!Q2.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,D0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){D0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),D0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??Z2(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:S1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),k.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),D0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);D0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:S1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:J,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((J)=>J.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function Z2(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class JO extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class g extends JO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class F extends JO{constructor(O){super("BAD_REQUEST",O,400)}}class C extends JO{constructor(O){super("CONFLICT",O,409)}}class tO extends JO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class MO extends JO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class W1 extends JO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class yO extends JO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class wO extends JO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var H5=W.Object({error:W.Object({code:W.String(),message:W.String(),details:W.Optional(W.Record(W.String(),W.Unknown()))})});import{Hono as J2}from"hono";var R1=$O("Service"),Y2=W.Object({updates:W.Record(W.String(),W.Any()),options:W.Optional(W.Object({scope:W.Optional(YO(["local","project","global"])),immediate:W.Optional(W.Boolean())}))});function N2(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var Kx=()=>{let O=new J2;return O.get("/",async(x)=>{try{let $=BO();return x.json($?N2($):{})}catch($){return R1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=y(Y2,$);if(!w.success)throw new F("Invalid config update format");let{updates:Q,options:J}=w.data;return await PO().updateConfig(Q,J),x.json({success:!0,updates:Q})}catch($){throw R1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=BO();return x.json($?.permissions||{})}catch($){return R1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as W2}from"hono";import{streamSSE as X2}from"hono/streaming";function Ux(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
1
+ import{e as w$,f as Q$}from"./chunk-anjpwev3.js";import{g as H1}from"./chunk-nq0w1j1a.js";import{s as A0,t as k4,u as q4,v as f4,w as C4}from"./chunk-7w1z4hdy.js";import{x as G0}from"./chunk-9vrsygd9.js";import{A as Fx,B as Lx,C as iO,D as Dx,y as A4,z as _x}from"./chunk-0axgw6c3.js";import{G as K4,H as cx,I as K$,L as U4,M as S0,N as e1,O as _1,P as ux,Q as d1,R as F4,S as cO,T as L4,U as D4,V as bx,W as i0,X as v1,Y as x0,Z as V0,aa as Q1,ba as Z1,ca as R$,da as H4,ea as b4,fa as d4,ga as v4,ha as i4,ia as l4,ja as c4,ka as a4,la as o4,ma as n4,na as t4,qa as $$,ta as h$,ya as U$}from"./chunk-qk0yyvgk.js";import{Fa as Cx,La as kO}from"./chunk-cqg8xkmd.js";import{$a as J$,Pa as S1,Sa as F$,Ta as Ox,Ua as j4,Va as M4,Wa as L$,Xa as D$,Ya as xx,Za as H$,_a as U0,ab as Y$,bb as N$,cb as T4,db as S4,eb as I4,fb as R4,gb as Bx,hb as Yx}from"./chunk-fpjhg6ce.js";import{Hb as u1,Qb as K0,sb as w0,tb as P,vb as k,wb as _4}from"./chunk-gqfa43gv.js";import{$b as c1}from"./chunk-sca5q3tt.js";import{Ad as z4,Bc as J4,Cc as m1,Dc as Y4,Ec as n0,Fc as N4,Gd as V4,Hd as G4,Ic as f1,Jd as M0,Md as h1,Rd as B4,Sd as g1,Td as p1,Ud as E,Vc as W4,ed as X4,od as r0,pd as B0,uc as Z4,wd as $1,xd as a1,yd as w1}from"./chunk-2kgp4h99.js";import{Qe as S$,Ue as BO,Ye as mx,df as PO}from"./chunk-4jt2gxzt.js";import{ef as P1}from"./chunk-ye4wyq1k.js";import{vf as w4}from"./chunk-8qp8v96d.js";import{xf as B1}from"./chunk-1dscrttm.js";import{Ff as I$,Hf as z$,Kf as u4,Of as c0,Pf as a0,Tf as l$,Wf as gO,Xf as o0,_f as c$}from"./chunk-khewsbnt.js";import{og as hx,pg as Q4}from"./chunk-adkpwx6c.js";import{tg as Rx,ug as b0}from"./chunk-j19j9ypt.js";import{Bh as l0,Mg as fx,eh as O4,hh as x4,jh as $4,wh as kx}from"./chunk-jg81tz55.js";import{Eh as E1}from"./chunk-kz15jy62.js";import{Fh as y,Hh as W,Ih as pO,Kh as YO}from"./chunk-9fgkg1vr.js";import{Mh as L1,Ph as y1}from"./chunk-pykxe413.js";import{Th as s}from"./chunk-kzzty3v5.js";import{ti as $O}from"./chunk-w4xqaw4h.js";import{zi as X0}from"./chunk-r6svhe3w.js";import{Bi as yx,Ci as rx,Ei as Px,Fi as ex}from"./chunk-a4dmw23t.js";import{Hi as H0}from"./chunk-5n1ymw0p.js";import{Oi as Jx}from"./chunk-ncqagb27.js";import{Ui as z1,Yi as jx,Zi as F1}from"./chunk-spxb931p.js";import{$i as wx}from"./chunk-m7b779kd.js";var V5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function G5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as Nx,readFileSync as Y1}from"node:fs";import{createServer as d3}from"node:http";import{networkInterfaces as v3}from"node:os";import{dirname as i3,extname as l3,join as Y0}from"node:path";import{fileURLToPath as c3}from"node:url";import{brotliCompressSync as a3,gzipSync as o3,constants as n3}from"node:zlib";import{Hono as t3}from"hono";import{cors as s3}from"hono/cors";import{WebSocketServer as r3}from"ws";var D0=$O("Service"),w2=30000,Q2=new Set(["completed","failed","cancelled","interrupted"]);class I1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??Bx.getInstance(),this.tickMs=O.tickMs??w2}start(){if(this.timer)return;D0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=k.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!Q2.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,D0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){D0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),D0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let w=x.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??Z2(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),J=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:S1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:J?J.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),k.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:w,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),D0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);D0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:S1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:w,lastStatus:"error",lastError:J,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Q=(await this.store.list()).find((J)=>J.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function Z2(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class JO extends Error{code;statusCode;details;constructor(O,x,$=500,w){super(x);this.code=O;this.statusCode=$;this.details=w;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class g extends JO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class F extends JO{constructor(O){super("BAD_REQUEST",O,400)}}class C extends JO{constructor(O){super("CONFLICT",O,409)}}class tO extends JO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class MO extends JO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class W1 extends JO{constructor(O){super("SESSION_WORKSPACE_UNAVAILABLE","This session workspace is no longer available",409,{reason:O})}}class yO extends JO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class wO extends JO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var H5=W.Object({error:W.Object({code:W.String(),message:W.String(),details:W.Optional(W.Record(W.String(),W.Unknown()))})});import{Hono as J2}from"hono";var R1=$O("Service"),Y2=W.Object({updates:W.Record(W.String(),W.Any()),options:W.Optional(W.Object({scope:W.Optional(YO(["local","project","global"])),immediate:W.Optional(W.Boolean())}))});function N2(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var Kx=()=>{let O=new J2;return O.get("/",async(x)=>{try{let $=BO();return x.json($?N2($):{})}catch($){return R1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),w=y(Y2,$);if(!w.success)throw new F("Invalid config update format");let{updates:Q,options:J}=w.data;return await PO().updateConfig(Q,J),x.json({success:!0,updates:Q})}catch($){throw R1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=BO();return x.json($?.permissions||{})}catch($){return R1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as W2}from"hono";import{streamSSE as X2}from"hono/streaming";function Ux(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)x+=`event: ${O.event}
3
3
  `;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
4
4
  `;if(O.retry!==void 0)x+=`retry: ${O.retry}
@@ -1 +1 @@
1
- import{Bb as c,Fb as d,Gb as e,Hb as f,Ib as g,Jb as h,Kb as i,Lb as j,Mb as k,Tb as l,Ub as m,Vb as n,Wb as o,Yb as p,Zb as q,_b as r,yb as a,zb as b}from"./chunk-fwmym1zk.js";import"./chunk-sca5q3tt.js";import"./chunk-863ynx9m.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-8qp8v96d.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-b1rqfaea.js";import"./chunk-2t6b962t.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-dw9wcrtp.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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{Bb as c,Fb as d,Gb as e,Hb as f,Ib as g,Jb as h,Kb as i,Lb as j,Mb as k,Tb as l,Ub as m,Vb as n,Wb as o,Yb as p,Zb as q,_b as r,yb as a,zb as b}from"./chunk-gqfa43gv.js";import"./chunk-sca5q3tt.js";import"./chunk-2kgp4h99.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-8qp8v96d.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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{La as H}from"./chunk-gnvepc4p.js";import"./chunk-sca5q3tt.js";import"./chunk-q265drks.js";import{Ze as $,df as T}from"./chunk-szw16t85.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-b1rqfaea.js";import"./chunk-2t6b962t.js";import"./chunk-88krdjg8.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-dw9wcrtp.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{La as H}from"./chunk-cqg8xkmd.js";import"./chunk-sca5q3tt.js";import"./chunk-q265drks.js";import{Ze as $,df as T}from"./chunk-4jt2gxzt.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-j19j9ypt.js";import"./chunk-2t6b962t.js";import"./chunk-jg81tz55.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as k}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5n1ymw0p.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.121",
3
+ "version": "0.10.122",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",