blade-code 0.10.89 → 0.10.91

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-w1zqg432.js → chunk-11ajd6hj.js} +2 -2
  3. package/dist/{chunk-pqh2m0h4.js → chunk-1gnq2qz3.js} +1 -1
  4. package/dist/{chunk-hqamtpdx.js → chunk-3xpgkrnw.js} +1 -1
  5. package/dist/{chunk-71mh6e44.js → chunk-47xjtzq5.js} +1 -1
  6. package/dist/{chunk-f31b0htk.js → chunk-4vng4fc2.js} +1 -1
  7. package/dist/{chunk-w0nssbm4.js → chunk-50zkdamf.js} +1 -1
  8. package/dist/{chunk-jf0adakp.js → chunk-61sg8p2c.js} +1 -1
  9. package/dist/{chunk-p7n0c3rg.js → chunk-6wbhsgqd.js} +1 -1
  10. package/dist/{chunk-bbb0cfn3.js → chunk-7mj87nb9.js} +1 -1
  11. package/dist/{chunk-wtten4kb.js → chunk-7r2p609r.js} +1 -1
  12. package/dist/{chunk-9c1b7rh3.js → chunk-7zjzykx2.js} +1 -1
  13. package/dist/{chunk-hnmfmwr4.js → chunk-8zvjcxze.js} +1 -1
  14. package/dist/chunk-a1hvqk3r.js +1 -0
  15. package/dist/{chunk-wamp4m89.js → chunk-aj647rtw.js} +1 -1
  16. package/dist/{chunk-np454w8t.js → chunk-c0ecz59a.js} +1 -1
  17. package/dist/{chunk-x8da65v8.js → chunk-cwtj154q.js} +1 -1
  18. package/dist/{chunk-gepcqct7.js → chunk-e6gfpm6b.js} +1 -1
  19. package/dist/{chunk-grppg0j4.js → chunk-ff38sxd0.js} +1 -1
  20. package/dist/{chunk-57ajk4j4.js → chunk-hjkz6k6v.js} +1 -1
  21. package/dist/{chunk-c3ktp287.js → chunk-j0rkfsdy.js} +1 -1
  22. package/dist/{chunk-hmbemyfq.js → chunk-j6tp0ny9.js} +1 -1
  23. package/dist/{chunk-90m669b8.js → chunk-k38mgpj8.js} +1 -1
  24. package/dist/{chunk-bz9aaagw.js → chunk-kq9xrrhg.js} +1 -1
  25. package/dist/chunk-nvakshbb.js +1 -0
  26. package/dist/{chunk-j8jdc3x2.js → chunk-pxah309m.js} +1 -1
  27. package/dist/{chunk-vpfat6hy.js → chunk-qn8jacbk.js} +1 -1
  28. package/dist/{chunk-d4d554dn.js → chunk-s1xrzd14.js} +1 -1
  29. package/dist/{chunk-sbxjxswz.js → chunk-s8hdg5y9.js} +1 -1
  30. package/dist/{chunk-nnr4qd03.js → chunk-sa259vbs.js} +1 -1
  31. package/dist/{chunk-5phm3482.js → chunk-scdfsyfc.js} +1 -1
  32. package/dist/{chunk-jhc6ppp8.js → chunk-tja1sejx.js} +1 -1
  33. package/dist/{chunk-w2w0jz96.js → chunk-vs5bmzj8.js} +1 -1
  34. package/dist/{chunk-9gs5xzjs.js → chunk-vxa67kca.js} +1 -1
  35. package/dist/{chunk-djfayq5w.js → chunk-x4zy3sez.js} +3 -3
  36. package/dist/{chunk-31ystb68.js → chunk-xrpmfq5d.js} +1 -1
  37. package/dist/{chunk-16q3rx34.js → chunk-yr16h4mj.js} +1 -1
  38. package/dist/{chunk-a42crerk.js → chunk-zg73wrze.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-pvdkse5m.js +0 -1
  41. package/dist/chunk-x1s3bjn6.js +0 -1
@@ -1,4 +1,4 @@
1
- import{ta as G5}from"./chunk-ebxt5bv1.js";import{Ca as LY,Da as o3,Ea as c0,wa as C,xa as l0}from"./chunk-c3ktp287.js";import{Fa as n4,Ha as YQ,Ja as QQ,Ka as eZ,ab as WQ}from"./chunk-f7p7tzx2.js";import{Ab as K$,Gb as F4,Hb as VY,Ib as CJ,Kb as M2,Lb as lJ,Qb as z7,Tb as G7,bb as k$,cb as S1,db as y3,eb as B1,fb as O3,gb as x3,hb as j3,ib as h3,jb as g3,kb as R7,ob as U0,qb as I6,tb as a6,vb as QZ,wb as o6,xb as s6,zb as G9}from"./chunk-9gs5xzjs.js";import{$b as s1,Ac as j1,Bc as $6,Cc as A1,Dc as Z6,Dd as K7,Ec as J6,Fc as P$,Gc as Y6,Hc as C5,Ic as w2,Id as pJ,Jc as Q6,Jd as cJ,Kc as W6,Lc as U6,Ld as s,Mc as X6,Oc as M5,Qc as R5,Zb as c5,_b as D0,ac as o$,bc as n2,cc as Q5,dc as r6,ec as n6,fc as C3,gc as M3,hc as uJ,hd as K4,ic as z5,id as b0,jc as Y1,jd as U$,kc as H5,lc as h4,mc as T$,nc as f$,oc as V2,pc as X2,qc as B2,rc as t2,sc as e2,sd as W5,tc as Q2,td as r0,uc as q5,ud as k1,vc as W2,vd as dJ,wc as g4,wd as mJ,xc as C1,yc as N1,zc as U2,zd as GY}from"./chunk-grppg0j4.js";import{Md as m,Nd as S7,Od as k7,Pd as v1}from"./chunk-xhhgpbzs.js";import{Qd as XQ,Td as VQ,ae as BQ,ge as wQ}from"./chunk-r2nzt9jm.js";import{re as w9,se as V9}from"./chunk-dm1knbf8.js";import{Ee as t6,Fe as K0,Ge as y,Je as F0,Ke as x6,Le as y1,Me as u$,Ne as zZ,Oe as Q1,Pe as w7,Ue as T1}from"./chunk-p7n0c3rg.js";import{Ve as z1}from"./chunk-3aejg2jy.js";import{$e as V7,_e as H7,ef as ZY,ff as h6}from"./chunk-y7dtdwqx.js";import{hf as k0,if as a$}from"./chunk-vyk5nxsz.js";import{jf as wY}from"./chunk-q8jfwyr4.js";import{lf as yJ,mf as IJ,nf as xJ}from"./chunk-hmbemyfq.js";import{Af as i4,Bf as M1,Cf as D4,Df as F1,Ef as q1,Ff as gJ,Jf as SZ,Lf as v0,Mf as z$,Of as g6,Pf as iJ,of as m6,pf as p6,qf as c6,sf as l6,tf as i6,uf as i$,vf as h7,xf as F$,yf as X$,zf as J$}from"./chunk-16q3rx34.js";import{Rf as m$,Tf as H$,Uf as C6,Vf as k5,Wf as v5,Xf as H2,Yf as y5,Zf as I5,_f as B6}from"./chunk-d83meq4k.js";import{$f as PY,bg as hJ,cg as H4,dg as H9}from"./chunk-q15sm6vj.js";import{fg as rZ,hg as R0}from"./chunk-bbb0cfn3.js";import{ig as u2,jg as Y5,kg as d2,lg as O1}from"./chunk-ckqz2btx.js";import{$g as t3,Dg as s5,Fg as fJ,Hg as k3,Ig as v3,Og as H1,Rg as N3,ah as e3,bh as $7,ch as Z7,dh as HZ,eh as J7,fh as g$,gh as Y7,hh as Q7,ih as W7,kh as d5,mh as nJ,ng as a5,nh as vJ,oh as X0,sg as o5,ug as mZ,zg as qY}from"./chunk-j8jdc3x2.js";import{rh as S$}from"./chunk-ne5w9ds8.js";import{sh as V6,th as m4,uh as K,vh as p7,wh as T,xh as x}from"./chunk-45a1tsk1.js";import{Bh as AJ,zh as jJ}from"./chunk-12e2yj9p.js";import{Eh as z6,Gh as M}from"./chunk-1g5s5vf3.js";import{gi as o}from"./chunk-hkh2nsam.js";import{li as SJ,mi as kJ}from"./chunk-rxjyc6ff.js";import{ni as fY,qi as MY}from"./chunk-7a8j14gg.js";import{ui as yY}from"./chunk-w0nssbm4.js";import{Ai as rJ,Bi as g0}from"./chunk-bvp5wpz8.js";import{Fi as r2,Hi as x$,Ji as TJ,Ki as S5,Mi as J0}from"./chunk-1mb2y0e0.js";import{Oi as n0}from"./chunk-m5hnyxf3.js";import{randomUUID as f4}from"crypto";import{randomUUID as PQ}from"node:crypto";var jQ=String.raw`
1
+ import{ta as G5}from"./chunk-ebxt5bv1.js";import{Ca as LY,Da as o3,Ea as c0,wa as C,xa as l0}from"./chunk-j0rkfsdy.js";import{Fa as n4,Ha as YQ,Ja as QQ,Ka as eZ,ab as WQ}from"./chunk-f7p7tzx2.js";import{Ab as K$,Gb as F4,Hb as VY,Ib as CJ,Kb as M2,Lb as lJ,Qb as z7,Tb as G7,bb as k$,cb as S1,db as y3,eb as B1,fb as O3,gb as x3,hb as j3,ib as h3,jb as g3,kb as R7,ob as U0,qb as I6,tb as a6,vb as QZ,wb as o6,xb as s6,zb as G9}from"./chunk-vxa67kca.js";import{$b as s1,Ac as j1,Bc as $6,Cc as A1,Dc as Z6,Dd as K7,Ec as J6,Fc as P$,Gc as Y6,Hc as C5,Ic as w2,Id as pJ,Jc as Q6,Jd as cJ,Kc as W6,Lc as U6,Ld as s,Mc as X6,Oc as M5,Qc as R5,Zb as c5,_b as D0,ac as o$,bc as n2,cc as Q5,dc as r6,ec as n6,fc as C3,gc as M3,hc as uJ,hd as K4,ic as z5,id as b0,jc as Y1,jd as U$,kc as H5,lc as h4,mc as T$,nc as f$,oc as V2,pc as X2,qc as B2,rc as t2,sc as e2,sd as W5,tc as Q2,td as r0,uc as q5,ud as k1,vc as W2,vd as dJ,wc as g4,wd as mJ,xc as C1,yc as N1,zc as U2,zd as GY}from"./chunk-ff38sxd0.js";import{Md as m,Nd as S7,Od as k7,Pd as v1}from"./chunk-xhhgpbzs.js";import{Qd as XQ,Td as VQ,ae as BQ,ge as wQ}from"./chunk-r2nzt9jm.js";import{re as w9,se as V9}from"./chunk-dm1knbf8.js";import{Ee as t6,Fe as K0,Ge as y,Je as F0,Ke as x6,Le as y1,Me as u$,Ne as zZ,Oe as Q1,Pe as w7,Ue as T1}from"./chunk-6wbhsgqd.js";import{Ve as z1}from"./chunk-3aejg2jy.js";import{$e as V7,_e as H7,ef as ZY,ff as h6}from"./chunk-y7dtdwqx.js";import{hf as k0,if as a$}from"./chunk-vyk5nxsz.js";import{jf as wY}from"./chunk-q8jfwyr4.js";import{lf as yJ,mf as IJ,nf as xJ}from"./chunk-j6tp0ny9.js";import{Af as i4,Bf as M1,Cf as D4,Df as F1,Ef as q1,Ff as gJ,Jf as SZ,Lf as v0,Mf as z$,Of as g6,Pf as iJ,of as m6,pf as p6,qf as c6,sf as l6,tf as i6,uf as i$,vf as h7,xf as F$,yf as X$,zf as J$}from"./chunk-yr16h4mj.js";import{Rf as m$,Tf as H$,Uf as C6,Vf as k5,Wf as v5,Xf as H2,Yf as y5,Zf as I5,_f as B6}from"./chunk-d83meq4k.js";import{$f as PY,bg as hJ,cg as H4,dg as H9}from"./chunk-q15sm6vj.js";import{fg as rZ,hg as R0}from"./chunk-7mj87nb9.js";import{ig as u2,jg as Y5,kg as d2,lg as O1}from"./chunk-ckqz2btx.js";import{$g as t3,Dg as s5,Fg as fJ,Hg as k3,Ig as v3,Og as H1,Rg as N3,ah as e3,bh as $7,ch as Z7,dh as HZ,eh as J7,fh as g$,gh as Y7,hh as Q7,ih as W7,kh as d5,mh as nJ,ng as a5,nh as vJ,oh as X0,sg as o5,ug as mZ,zg as qY}from"./chunk-pxah309m.js";import{rh as S$}from"./chunk-ne5w9ds8.js";import{sh as V6,th as m4,uh as K,vh as p7,wh as T,xh as x}from"./chunk-45a1tsk1.js";import{Bh as AJ,zh as jJ}from"./chunk-12e2yj9p.js";import{Eh as z6,Gh as M}from"./chunk-1g5s5vf3.js";import{gi as o}from"./chunk-hkh2nsam.js";import{li as SJ,mi as kJ}from"./chunk-rxjyc6ff.js";import{ni as fY,qi as MY}from"./chunk-7a8j14gg.js";import{ui as yY}from"./chunk-50zkdamf.js";import{Ai as rJ,Bi as g0}from"./chunk-bvp5wpz8.js";import{Fi as r2,Hi as x$,Ji as TJ,Ki as S5,Mi as J0}from"./chunk-1mb2y0e0.js";import{Oi as n0}from"./chunk-m5hnyxf3.js";import{randomUUID as f4}from"crypto";import{randomUUID as PQ}from"node:crypto";var jQ=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);
@@ -838,7 +838,7 @@ ${a}
838
838
  </approved-plan>
839
839
 
840
840
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof F==="string")i0=F+B0;else i0=[...F,{type:"text",text:B0}]}v=yield*this.runLoop(i0,L,{...I,inputMessageId:void 0})}if(!this.sessionRuntime||!S)return v;let k=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,prematureStopPattern:v.success?S3(v.finalMessage):void 0});if(k)yield{kind:"goal_updated",goal:k};if(!v.success||L.signal?.aborted){if(k=await this.sessionRuntime.pauseActiveGoal(L.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),k)yield{kind:"goal_updated",goal:k}}if(v.success&&!L.signal?.aborted&&P<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(S,L.signal);let d=v.success&&!L.signal?.aborted&&P<20,Z0=RV(v);if(j=await this.sessionRuntime.finishTurn(S,{continuePending:d,...Z0?{acknowledgeInput:!0}:{},outcome:v.success&&!L.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:L.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),j){P++,q=!0,b=!1,N=null,F="",R=void 0,A="",O=void 0,E=g(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:p()};continue}if(!v.success||L.signal?.aborted)return v;if(k=await this.sessionRuntime.getGoal(),!k||k.status!=="active"&&k.status!=="verifying")return v;if(N=await this.sessionRuntime.beginGoalContinuation(),!N)return v;j=await this.sessionRuntime.beginTurn("goal"),q=!1,b=!0,F=L8(N),R=void 0,E=void 0,yield{kind:"goal_continuation_started",goal:N,continuation:N.continuationCount,...N.prematureStop?{prematureStopPattern:N.prematureStop.pattern,prematureStopCount:N.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:N}}}finally{if(this.sessionRuntime&&j)await this.sessionRuntime.finishTurn(j)}}let G=typeof B==="string"?B:B.filter((F)=>F.type==="text").map((F)=>F.text).join(`
841
- `),_={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-jhc6ppp8.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await v$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:M2,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=G2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:G2(U.text)}:X)}else Q=[{type:"text",text:G2("")},...$]}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 v$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:M2,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 G7(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}],B=z7(Y,X);if(B)V.push(B);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=$,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 v$({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 u6({sessionId:"default",configDir:J0(),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 G6({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=c0.createIsolated({artifactWriter:new z2(`legacy-${MV()}`)});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(L2(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 v0(M());if(this.agentResources=g6($),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(`
841
+ `),_={id:this.generateTaskId(),type:"simple",prompt:G};return{success:!0,finalMessage:(await this.executeTask(_)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-tja1sejx.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){n.debug("Processing Plan mode message...");let{prompt:Y}=await v$({projectPath:Z.workspaceRoot||M(),mode:"plan",includeEnvironment:!0,environmentOptions:M2,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=G2($);else{let W=$.filter((U)=>U.type==="text");if(W.length>0){let U=W[0];Q=$.map((X)=>X===U?{type:"text",text:G2(U.text)}:X)}else Q=[{type:"text",text:G2("")},...$]}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 v$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:M2,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 G7(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}],B=z7(Y,X);if(B)V.push(B);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=$,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 v$({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 u6({sessionId:"default",configDir:J0(),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 G6({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=c0.createIsolated({artifactWriter:new z2(`legacy-${MV()}`)});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(L2(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 v0(M());if(this.agentResources=g6($),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(`
842
842
  `);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+=`
843
843
 
844
844
  <system-reminder>
@@ -1649,7 +1649,7 @@ ${J}
1649
1649
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1650
1650
  `)}}case"create":{let X=Uz(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 B=await $.create(V),w=B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${B.id}\`
1651
1651
  ${eZ(B.trigger)} · 下次运行: ${w}`),{success:!0,message:`Schedule ${B.id} created`}}catch(B){let w=B instanceof Error?B.message:String(B);return Y.sendMessage(`创建失败:${w}`),{success:!1,error:w}}}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 Xz(X),Y.sendMessage(`[OK] 已触发 \`${X}\``),{success:!0,message:"Schedule triggered"}}catch(V){let B=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${B}`),{success:!1,error:B}}}default:return Y.sendMessage(`未知子命令: ${Q}
1652
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var UQ=Vz();import*as n1 from"node:fs/promises";import*as a1 from"node:path";async function HQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let z=await Bz($,Q??M(),J,Y);if(z)return z}let X;try{X=(await n1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>a1.join(U,G))}catch{return[]}let B=(await Promise.all(X.map(async(z)=>{try{let G=await n1.stat(z);return{path:z,mtime:G.mtimeMs}}catch{return null}}))).filter((z)=>z!==null).sort((z,G)=>G.mtime-z.mtime).map((z)=>z.path),w=[],H=Y?$:$.toLowerCase();for(let z of B){if(w.length>=J)break;let G=a1.basename(z,".jsonl"),_=await wz(z,H,Y,G);if(w.push(..._),w.length>=J){w.length=J;break}}return w}async function Bz($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-kbgsbq7k.js"),W=await BQ();if(!W)return null;let{SessionService:U}=await import("./chunk-pqh2m0h4.js");await Q(W,U.projectionDeriverForSearch());let X=a1.resolve(Z),V=wQ(W,$,X,J*4),B=Y?$:$.toLowerCase(),w=[];for(let H of V){if(H.role!=="user"&&H.role!=="assistant")continue;let z=$5(H.text,B,Y,H.session_id,H.role,H.timestamp??void 0,0);if(z)w.push(z);if(w.length>=J)break}return w}catch{return null}}async function wz($,Z,J,Y){try{let Q=await n1.readFile($,"utf8"),U=Q.split(`
1652
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var UQ=Vz();import*as n1 from"node:fs/promises";import*as a1 from"node:path";async function HQ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:W}=Z,U=W??r2(Q??M());if(!W){let z=await Bz($,Q??M(),J,Y);if(z)return z}let X;try{X=(await n1.readdir(U)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>a1.join(U,G))}catch{return[]}let B=(await Promise.all(X.map(async(z)=>{try{let G=await n1.stat(z);return{path:z,mtime:G.mtimeMs}}catch{return null}}))).filter((z)=>z!==null).sort((z,G)=>G.mtime-z.mtime).map((z)=>z.path),w=[],H=Y?$:$.toLowerCase();for(let z of B){if(w.length>=J)break;let G=a1.basename(z,".jsonl"),_=await wz(z,H,Y,G);if(w.push(..._),w.length>=J){w.length=J;break}}return w}async function Bz($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-kbgsbq7k.js"),W=await BQ();if(!W)return null;let{SessionService:U}=await import("./chunk-1gnq2qz3.js");await Q(W,U.projectionDeriverForSearch());let X=a1.resolve(Z),V=wQ(W,$,X,J*4),B=Y?$:$.toLowerCase(),w=[];for(let H of V){if(H.role!=="user"&&H.role!=="assistant")continue;let z=$5(H.text,B,Y,H.session_id,H.role,H.timestamp??void 0,0);if(z)w.push(z);if(w.length>=J)break}return w}catch{return null}}async function wz($,Z,J,Y){try{let Q=await n1.readFile($,"utf8"),U=Q.split(`
1653
1653
  `).flatMap((H,z)=>{if(!H.trim())return[];try{return[{event:JSON.parse(H),index:z}]}catch{return[]}});if(!U.some(({event:H})=>H.type==="session_created"))return Hz(U,Z,J,Y);let V=new Map(U.flatMap(({event:H,index:z})=>typeof H.id==="string"?[[H.id,z+1]]:[])),B=XQ(VQ(Q,$)),w=new Map;for(let H of B){if(H.type==="message_created"&&(H.data.role==="user"||H.data.role==="assistant"))w.set(H.data.messageId,{role:H.data.role,content:[],timestamp:H.timestamp,lineNumber:V.get(H.id)??0});if(H.type==="part_created"&&H.data.partType==="text"){let z=w.get(H.data.messageId),G=H.data.payload.text;if(z&&typeof G==="string")z.content.push(G)}}return[...w.values()].flatMap((H)=>{let z=$5(H.content.join(" "),Z,J,Y,H.role,H.timestamp,H.lineNumber);return z?[z]:[]})}catch{return[]}}function Hz($,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((B)=>typeof B==="object"&&B!==null&&B.type==="text"&&typeof B.text==="string").map((B)=>B.text).join(" "):"",V=$5(X,Z,J,Y,U.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,W+1);return V?[V]:[]})}function $5($,Z,J,Y,Q,W,U){if(!$)return;let X=J?$:$.toLowerCase();if(!X.includes(Z))return;let V=X.indexOf(Z),B=Math.max(0,V-80),w=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(B>0?"...":"")+$.slice(B,w).replace(/\n/g," ")+(w<$.length?"...":""),timestamp:W,lineNumber:U}}function KQ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1654
1654
  `];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(`
1655
1655
  `)}var Kz={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=u(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await HQ(Y,{maxResults:15,projectPath:Z.cwd}),W=KQ(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}}}},zQ=Kz;var zz={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await z$(J,async(Y)=>{await Y.skills.refresh(),q1(J),await F1(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}}}},GQ=zz;import Gz from"node:path";function A4($){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 DQ($){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 _Q($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function Dz($,Z){let J=u(Z),Y=$[0],Q=e.getInstance(),W=V0.getInstance(),U=Z.sessionId??"",X=Z.sessionId?{sessionId:Z.sessionId,projectPath:Gz.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,4 +1,4 @@
1
- import{S as P}from"./chunk-djfayq5w.js";import{qb as K}from"./chunk-9gs5xzjs.js";import{Ld as B,Vc as G,Wc as N,Xc as S,Yc as O,Zc as s}from"./chunk-grppg0j4.js";import{Ud as j}from"./chunk-r2nzt9jm.js";import{Ve as q}from"./chunk-3aejg2jy.js";import{rf as v}from"./chunk-16q3rx34.js";import{Ii as z}from"./chunk-1mb2y0e0.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{S as P}from"./chunk-x4zy3sez.js";import{qb as K}from"./chunk-vxa67kca.js";import{Ld as B,Vc as G,Wc as N,Xc as S,Yc as O,Zc as s}from"./chunk-ff38sxd0.js";import{Ud as j}from"./chunk-r2nzt9jm.js";import{Ve as q}from"./chunk-3aejg2jy.js";import{rf as v}from"./chunk-yr16h4mj.js";import{Ii as z}from"./chunk-1mb2y0e0.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,4 +1,4 @@
1
- import{Qf as b1,Rf as L0,Sf as z1,Xf as N0}from"./chunk-d83meq4k.js";import{ag as jO,bg as wO}from"./chunk-q15sm6vj.js";import{eg as A1}from"./chunk-tc1001nx.js";import{fg as b0,hg as J0}from"./chunk-bbb0cfn3.js";import{jh as S0,kh as GO,oh as I0}from"./chunk-j8jdc3x2.js";import{sh as u,uh as L,xh as c1}from"./chunk-45a1tsk1.js";import{Gh as M}from"./chunk-1g5s5vf3.js";import{gi as k,hi as S}from"./chunk-hkh2nsam.js";import{ui as u0}from"./chunk-w0nssbm4.js";import{Bi as N}from"./chunk-bvp5wpz8.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
1
+ import{Qf as b1,Rf as L0,Sf as z1,Xf as N0}from"./chunk-d83meq4k.js";import{ag as jO,bg as wO}from"./chunk-q15sm6vj.js";import{eg as A1}from"./chunk-tc1001nx.js";import{fg as b0,hg as J0}from"./chunk-7mj87nb9.js";import{jh as S0,kh as GO,oh as I0}from"./chunk-pxah309m.js";import{sh as u,uh as L,xh as c1}from"./chunk-45a1tsk1.js";import{Gh as M}from"./chunk-1g5s5vf3.js";import{gi as k,hi as S}from"./chunk-hkh2nsam.js";import{ui as u0}from"./chunk-50zkdamf.js";import{Bi as N}from"./chunk-bvp5wpz8.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -1,4 +1,4 @@
1
- import{s as hz,t as Sz}from"./chunk-vpfat6hy.js";import{u as b}from"./chunk-31ystb68.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-np454w8t.js";import{F as N,M as $z,N as Qz,R as Wz,U as Yz,V as Hz,Z as jz,na as Fz,oa as Uz,pa as Vz,qa as wz}from"./chunk-djfayq5w.js";import"./chunk-ebxt5bv1.js";import{Ea as Tz}from"./chunk-c3ktp287.js";import{Ga as Zz}from"./chunk-f7p7tzx2.js";import{Ab as zz,Jb as Jz,ob as e}from"./chunk-9gs5xzjs.js";import{Ub as I}from"./chunk-7avnhnjn.js";import{Ad as x,Dd as t,Id as q,Ld as U,Yc as l,gd as i,hd as r,md as a,pd as o,rd as n,xd as C,yd as s}from"./chunk-grppg0j4.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as Mz}from"./chunk-sbxjxswz.js";import"./chunk-dm1knbf8.js";import{Je as Nz,Ke as Ez}from"./chunk-p7n0c3rg.js";import"./chunk-v508x7cg.js";import{Ve as f}from"./chunk-3aejg2jy.js";import{_e as v}from"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import{jf as xz}from"./chunk-q8jfwyr4.js";import"./chunk-hmbemyfq.js";import"./chunk-16q3rx34.js";import"./chunk-d83meq4k.js";import{$f as bz}from"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-bbb0cfn3.js";import"./chunk-ckqz2btx.js";import{Tg as qz,Wg as Pz}from"./chunk-j8jdc3x2.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import{Bh as M,Ch as k,yh as S,zh as d}from"./chunk-12e2yj9p.js";import{Gh as Oz}from"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import{gi as T}from"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import{ni as Az,qi as Rz}from"./chunk-7a8j14gg.js";import"./chunk-w0nssbm4.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import{Mi as m}from"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as hz,t as Sz}from"./chunk-qn8jacbk.js";import{u as b}from"./chunk-xrpmfq5d.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-c0ecz59a.js";import{F as N,M as $z,N as Qz,R as Wz,U as Yz,V as Hz,Z as jz,na as Fz,oa as Uz,pa as Vz,qa as wz}from"./chunk-x4zy3sez.js";import"./chunk-ebxt5bv1.js";import{Ea as Tz}from"./chunk-j0rkfsdy.js";import{Ga as Zz}from"./chunk-f7p7tzx2.js";import{Ab as zz,Jb as Jz,ob as e}from"./chunk-vxa67kca.js";import{Ub as I}from"./chunk-7avnhnjn.js";import{Ad as x,Dd as t,Id as q,Ld as U,Yc as l,gd as i,hd as r,md as a,pd as o,rd as n,xd as C,yd as s}from"./chunk-ff38sxd0.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as Mz}from"./chunk-s8hdg5y9.js";import"./chunk-dm1knbf8.js";import{Je as Nz,Ke as Ez}from"./chunk-6wbhsgqd.js";import"./chunk-v508x7cg.js";import{Ve as f}from"./chunk-3aejg2jy.js";import{_e as v}from"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import{jf as xz}from"./chunk-q8jfwyr4.js";import"./chunk-j6tp0ny9.js";import"./chunk-yr16h4mj.js";import"./chunk-d83meq4k.js";import{$f as bz}from"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-7mj87nb9.js";import"./chunk-ckqz2btx.js";import{Tg as qz,Wg as Pz}from"./chunk-pxah309m.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import{Bh as M,Ch as k,yh as S,zh as d}from"./chunk-12e2yj9p.js";import{Gh as Oz}from"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import{gi as T}from"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import{ni as Az,qi as Rz}from"./chunk-7a8j14gg.js";import"./chunk-50zkdamf.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import{Mi as m}from"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function pz(z){if(!v(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...i("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Gz({maxPendingItems:Xz,maxPendingBytes:Dz,writeTimeoutMs:Lz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return jz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?uz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Wz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(D)=>Q.onOutput?.("stdout",D)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Uz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=e.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:D}=W.properties,X=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof D==="string"&&Qz(X,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(D,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:X});if(!L?.accepted)return;if(await new $z(Q,m()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!n(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of gz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=!1,X,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(D)L(B);else X=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),D=!0,X)L(X);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,D)},complete:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,D)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),X=await D.completion,L=(await b.list(this.cwd,this.id)).find((F)=>F.start.reviewId===D.reviewId);if(!L)throw Error(`Review not found: ${D.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:D.reviewId,status:X.status,findings:X.findings.length,content:l(L.start,X)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,D)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(D);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Vz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=wz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Zz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController,X=!1,L,F=new Promise((B)=>{L=B});this.pendingPrompt=D,this.pendingPromptCompletion=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Fz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,D.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await zz(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let P=JSON.parse(V.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")w=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,kz=Hz(o(Yz(K,O),a));R.push({type:"content",content:{type:"text",text:kz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let P=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:P,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.89",
3
+ "version": "0.10.91",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{h as a,i as b,j as c,k as d,l as e}from"./chunk-71mh6e44.js";import"./chunk-w0nssbm4.js";import"./chunk-m5hnyxf3.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +0,0 @@
1
- import{he as a,ie as b}from"./chunk-f31b0htk.js";import"./chunk-w0nssbm4.js";import"./chunk-m5hnyxf3.js";export{a as globalOptions,b as cliConfig};