blade-code 0.11.4 → 0.11.5
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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-7m07qp5c.js → chunk-03rdr8mr.js} +1 -1
- package/dist/{chunk-vv6r417h.js → chunk-0bzhkqpe.js} +1 -1
- package/dist/{chunk-6m81sxfz.js → chunk-0ykg98p7.js} +1 -1
- package/dist/{chunk-bw3920qg.js → chunk-14mtvq2m.js} +1 -1
- package/dist/{chunk-m61cx42n.js → chunk-27cw0k2s.js} +1 -1
- package/dist/{chunk-w8dxjbm8.js → chunk-2x63c1gx.js} +1 -1
- package/dist/{chunk-3gbteqvh.js → chunk-3054z3md.js} +1 -1
- package/dist/{chunk-4077g2fm.js → chunk-39pjywan.js} +1 -1
- package/dist/{chunk-5ce8ydjq.js → chunk-4cywnksk.js} +1 -1
- package/dist/{chunk-a1vvg4yf.js → chunk-5j824kxz.js} +1 -1
- package/dist/{chunk-49jbxty9.js → chunk-6eznxwsv.js} +1 -1
- package/dist/{chunk-r9egmztq.js → chunk-6wzwkjep.js} +1 -1
- package/dist/{chunk-vsmnzhhz.js → chunk-87bak5n5.js} +1 -1
- package/dist/chunk-8r6xncb3.js +1 -0
- package/dist/{chunk-rwm2e0r4.js → chunk-amzpb8s5.js} +1 -1
- package/dist/{chunk-egqep8py.js → chunk-c08qbh8h.js} +1 -1
- package/dist/{chunk-c33wff11.js → chunk-cc9vbgqc.js} +1 -1
- package/dist/{chunk-kj20ad32.js → chunk-ccpejbed.js} +1 -1
- package/dist/{chunk-nfdtrn3t.js → chunk-cmk9vr5m.js} +1 -1
- package/dist/{chunk-p4j7gxjk.js → chunk-eefqxc4t.js} +1 -1
- package/dist/{chunk-r8rvkas8.js → chunk-fj06d4kk.js} +1 -1
- package/dist/{chunk-js7fre4w.js → chunk-g4k4tnsq.js} +1 -1
- package/dist/{chunk-myznexy5.js → chunk-gmparnqt.js} +1 -1
- package/dist/{chunk-1hknjamx.js → chunk-gpj33m14.js} +1 -1
- package/dist/{chunk-vmhcc7f9.js → chunk-j08fc7cy.js} +1 -1
- package/dist/{chunk-q534f3j5.js → chunk-mjqwnekv.js} +1 -1
- package/dist/{chunk-ty3gwnwq.js → chunk-n0v7ce3r.js} +1 -1
- package/dist/{chunk-hfbw50pk.js → chunk-n39gsnzc.js} +1 -1
- package/dist/{chunk-e4q0rcmz.js → chunk-nefvj18m.js} +1 -1
- package/dist/{chunk-hfwn38rm.js → chunk-nmbgg7j5.js} +1 -1
- package/dist/{chunk-5kmxe14c.js → chunk-qk7n9j5k.js} +1 -1
- package/dist/{chunk-ydtsh19k.js → chunk-tj7ytet5.js} +1 -1
- package/dist/{chunk-qzsmbk13.js → chunk-v63e33me.js} +2 -2
- package/dist/{chunk-hbkpavbp.js → chunk-v7pw7a8q.js} +1 -1
- package/dist/{chunk-v5t3kcac.js → chunk-wr5qr81z.js} +1 -1
- package/dist/{chunk-n62b30d1.js → chunk-xcy0tfmt.js} +1 -1
- package/dist/chunk-xez8apfk.js +1 -0
- package/dist/{chunk-phch3t6v.js → chunk-yscyr8zw.js} +4 -4
- package/package.json +1 -1
- package/dist/chunk-d7frbjn7.js +0 -1
- package/dist/chunk-g2kqz1mm.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ka as QJ}from"./chunk-nad5spvc.js";import{Na as T,Oa as t0,Ta as DW,Ua as PY,Va as o0}from"./chunk-
|
|
1
|
+
import{Ka as QJ}from"./chunk-nad5spvc.js";import{Na as T,Oa as t0,Ta as DW,Ua as PY,Va as o0}from"./chunk-wr5qr81z.js";import{Ab as JV,Wa as t8,Za as u3,bb as n3,cb as KX,db as DX,fb as eW,hb as $V,ib as b9}from"./chunk-whxkwaz1.js";import{Bb as i5,Cb as I7,Db as J1,Eb as d7,Fb as G2,Gb as KY,Hb as S1,Ib as t7,Jb as qY,Kb as YY,Lb as wY,Mb as FY,Nb as zQ,Pb as WX,Rb as V0,Tb as w2,Wb as u6,Yb as G3,Zb as d6,_b as m6,ac as jZ,bc as T$,hc as $W,ic as V8,jc as JW,kc as ZW,lc as XX,nc as x1,oc as IX,tc as nY,wc as aY}from"./chunk-n39gsnzc.js";import{$c as h4,Cc as k$,Dc as fX,Ec as lJ,Fc as PJ,Gc as M1,Hc as eJ,Ic as L0,Jc as S2,Kc as L1,Lc as P4,Mc as T9,Nc as h6,Oc as g6,Pc as XY,Qc as WY,Rc as PX,Sc as YJ,Sd as Z8,Tc as j1,Uc as JJ,Ud as f0,Vc as u8,Vd as _$,Wc as e$,Xc as $1,Yc as l2,Zc as c2,_c as i2,ad as g4,bd as d2,be as UW,cd as UJ,ce as GX,dd as m2,ed as d8,fd as E1,fe as rY,gd as s1,hd as p2,id as o1,jd as t1,kd as u4,ke as vX,ld as e1,le as yX,md as d4,nd as m4,ne as o,od as S$,pd as p4,qd as LJ,rd as r2,sd as c4,td as l4,ud as i4,vd as r4,wd as OJ,xd as _J,zd as NJ}from"./chunk-v7pw7a8q.js";import{oe as l,pe as DQ,qe as qQ,re as yZ,te as q2}from"./chunk-skktstg8.js";import{Me as R9,Ne as $$,Oe as K2,Pe as s3,Qe as SX,Re as kX,_e as XV,lf as WV,ve as YV,ye as QV}from"./chunk-s14zayxp.js";import{Hf as LZ,If as wZ}from"./chunk-crv3sghv.js";import{$f as F2,Uf as p6,Vf as N0,Wf as g,Zf as E0,_f as C6,ag as H1,bg as b3,cg as A2,dg as lY,eg as U2}from"./chunk-qk7n9j5k.js";import{fg as h1}from"./chunk-x6k5ye1z.js";import{hg as eX,jg as F3,kg as iY,pg as pY,qg as iX,rg as T6}from"./chunk-1g7c3f82.js";import{sg as c3}from"./chunk-3v9epq9s.js";import{vg as u0,wg as F1}from"./chunk-eexs73bz.js";import{xg as QW}from"./chunk-pm163dfm.js";import{Ag as EX,Bg as AX,Cg as MX,zg as jX}from"./chunk-2x63c1gx.js";import{$g as R6,Dg as k6,Eg as v6,Fg as y6,Hg as I6,Ig as x6,Jg as q1,Kg as I$,Lg as N$,Mg as H$,Ng as n8,Og as Q2,Pg as X8,Qg as m1,Rg as p1,Sg as TX,Wg as t3,Yg as d0,Zg as R$,ah as RX,bh as xX}from"./chunk-nefvj18m.js";import{dh as B1,fh as C$,gh as L6}from"./chunk-kehgewqh.js";import{hh as gJ,ih as Y2,jh as uJ,kh as s2,lh as dJ,mh as mJ,nh as $6,oh as e4,ph as pJ,qh as cJ,rh as t4}from"./chunk-kkzznz4w.js";import{sh as EW,uh as CX,vh as J8,wh as OZ}from"./chunk-1cy4ab77.js";import{Ah as y0,yh as q9}from"./chunk-c08qbh8h.js";import{Bh as j4,Ch as C9,Dh as E4,Eh as c1}from"./chunk-ys8gysg8.js";import{Fi as kY,Gi as vY,Hh as YZ,Hi as yY,Ih as F$,Ii as IY,Ji as _3,Ki as xY,Li as U1,Mi as hY,Nh as QZ,Ni as gY,Oi as uY,Ph as z9,Qi as sJ,Si as gX,Ti as bX,Uh as KW,Ui as B0,Yh as XZ,_h as OX,ai as BY,bi as GY,si as v1,vi as ZY}from"./chunk-6wzwkjep.js";import{Xi as Q6,Zi as C}from"./chunk-b22ab7yw.js";import{xj as YX,zj as QX}from"./chunk-m2x6pb4f.js";import{Ej as $0,Gj as n4,Hj as Z2,Ij as K,Jj as CJ,Kj as S,Lj as h}from"./chunk-saz6mwpq.js";import{Pj as _X,Qj as NX}from"./chunk-xhwdac1j.js";import{Rj as MW,Uj as bW}from"./chunk-0eajnhrj.js";import{Xj as fW}from"./chunk-cc9vbgqc.js";import{bk as hX,ck as r0}from"./chunk-asgmmaec.js";import{Ek as hJ,dk as e,ek as O$,fk as B$,gk as a1,hk as a9,ik as u2,jk as Y$,kk as JY,nk as I4,wk as f4,zk as b$}from"./chunk-ed2hdrwe.js";import{Jk as J$}from"./chunk-gmpsfkgg.js";import{randomUUID as _8}from"crypto";import{randomUUID as EV}from"node:crypto";var OV=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);
|
|
@@ -867,7 +867,7 @@ ${l$}
|
|
|
867
867
|
</approved-plan>
|
|
868
868
|
|
|
869
869
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof b==="string")P2=b+A9;else P2=[...b,{type:"text",text:A9}]}k=yield*this.runLoop(P2,_,{...I,inputMessageId:void 0})}}finally{this.clearSkillContext()}if(!this.sessionRuntime||!y)return k;let a=v??await this.sessionRuntime.getGoal(),u=await this.sessionRuntime.recordGoalProgress({tokens:k.metadata?.tokensUsed??0,elapsedMs:k.metadata?.duration??0,turnId:y.id,...a?{goalId:a.goalId,objective:a.objective}:{},executionHostFailureCategory:k.metadata?.executionHostFailureCategory,prematureStopPattern:k.success?zY(k.finalMessage):void 0});if(u)yield{kind:"goal_updated",goal:u};if(!k.success||_.signal?.aborted){if(u=await this.sessionRuntime.pauseActiveGoal(_.signal?.aborted?"goal paused after user cancellation":k.error?.message??"goal paused after turn failure"),u)yield{kind:"goal_updated",goal:u}}if(k.success&&!_.signal?.aborted&&m<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(y,_.signal);let m0=k.success&&!_.signal?.aborted&&m<20,z0=UG(k)||!k.success&&k.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(y,{continuePending:m0,...z0?{acknowledgeInput:!0}:{},outcome:k.success&&!_.signal?.aborted?{status:"completed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0,...k.metadata?.usage?{usage:k.metadata.usage}:{}}:{status:"aborted",cause:_.signal?.aborted?"cancelled":"failed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0,...k.metadata?.usage?{usage:k.metadata.usage}:{}}}),R){m++,N=!0,A=!1,j=null,b="",c=void 0,M="",P=void 0,E=J0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:t(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!k.success||_.signal?.aborted)return k;if(u=await this.sessionRuntime.getGoal(),!u||u.status!=="active"&&u.status!=="verifying")return k;let F0=await this.sessionRuntime.prepareGoalContinuation(u);if(!F0.ok){if(F0.goal)yield{kind:"goal_updated",goal:F0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:F0.error.message},metadata:{turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,duration:k.metadata?.duration??0}}}let P$=await this.sessionRuntime.beginGoalTurn(F0.goal);if(!P$)return k;j=P$.goal,w={...F0,goal:P$.goal},R=P$.handle,N=!1,A=!0,b=C5(j),c=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:F0.frontier,tasks:F0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let L=typeof z==="string"?z:z.filter((b)=>b.type==="text").map((b)=>b.text).join(`
|
|
870
|
-
`),O={id:this.generateTaskId(),type:"simple",prompt:L};return{success:!0,finalMessage:(await this.executeTask(O)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,J,Z){let{drainLoop:Y}=await import("./chunk-4077g2fm.js");return Y(this.chatStream($,J,Z))}async*runPlanLoop($,J,Z){s.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...J.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:J.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:J.executionRoot??J.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...J.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,J,Z,Y)}async*runLoop($,J,Z){s.debug("Processing enhanced chat message...");let Y=J.systemPrompt??await this.buildSystemPromptOnDemand(J);return yield*this.executeLoop($,J,Z,Y)}async buildSystemPromptOnDemand($){let J=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:J,append:Z,includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,J,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,J,Z,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:J,result:Z})=>{let Y={id:J.toolCallId,type:"function",function:{name:J.toolName,arguments:JSON.stringify(J.input)}},Q=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0,X=Z.error===void 0,W=Z.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?Z.error?`Subagent execution failed: ${Z.error}.`:"":String(W),...Z.error?{error:{type:"execution_error",message:Z.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=nY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),J=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),Z=J&&J.state!=="none"?[{kind:"turn_recovery",assessment:J}]:[];return Z.push(...this.takeStartupAdoptedToolResultEvents()),Z}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=$,s.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?($,J,Z,Y)=>this.sessionRuntime.resolveContextualProjectRules($,J,Z,Y):void 0}}async chatWithSystem($,J){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:J}];return(await this.chatService.chat(Z)).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 J=this.toolExecutor.getRegistry(),Y=J.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)J.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let J=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of J.getAll())if(Z.has(Y.name))J.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),J=new Map;return $.forEach((Z)=>{let Y=J.get(Z.kind)||0;J.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(J),toolNames:$.map((Z)=>Z.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($,J){s.debug(`[MainAgent] ${$}`,J||"")}error($,J){s.error(`[MainAgent] ${$}`,J||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt,Z=await Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:J,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...x1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(Z.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f6({sessionId:"default",configDir:e(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let J=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${J} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await X6({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let J=o0.createIsolated({artifactWriter:new o2(`legacy-${VG()}`)});this.legacyMcpRegistry=J;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await J.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let Z=this.toolExecutor.getRegistry();Z.setMcpCatalogBarrier(()=>J.waitForCatalogIdle());let Y=J.getCatalogSnapshot();Z.replaceMcpTools(Y.tools),Z.registerAll(Z4(J));let Q=J.getInstructionsSnapshot();if(Z.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),J.on("catalogChanged",(X)=>{Z.replaceMcpTools(X.tools,X)}),J.on("contentCatalogChanged",(X)=>{Z.queueMcpContentChange(X)}),J.on("resourceUpdated",(X)=>{Z.queueMcpResourceUpdated(X)}),J.on("connectionLifecycleChanged",(X)=>{Z.queueMcpConnectionChange(X)}),J.on("log",(X)=>{Z.queueMcpLog(X)}),J.on("instructionsChanged",(X)=>{Z.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await d0(C());if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let J=this.subagentRegistry.getAllNames().length;if(J>0)s.debug(`Loaded ${J} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let J=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${J.join(", ")}`);let Z=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return J.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let J=[];for(let Y of $)if(Y.type==="text")J.push(Y.text);if(J.length===0)return $;let Z=J.join(`
|
|
870
|
+
`),O={id:this.generateTaskId(),type:"simple",prompt:L};return{success:!0,finalMessage:(await this.executeTask(O)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,J,Z){let{drainLoop:Y}=await import("./chunk-39pjywan.js");return Y(this.chatStream($,J,Z))}async*runPlanLoop($,J,Z){s.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...J.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:J.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:J.executionRoot??J.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...J.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,J,Z,Y)}async*runLoop($,J,Z){s.debug("Processing enhanced chat message...");let Y=J.systemPrompt??await this.buildSystemPromptOnDemand(J);return yield*this.executeLoop($,J,Z,Y)}async buildSystemPromptOnDemand($){let J=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:J,append:Z,includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,J,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,J,Z,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:J,result:Z})=>{let Y={id:J.toolCallId,type:"function",function:{name:J.toolName,arguments:JSON.stringify(J.input)}},Q=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0,X=Z.error===void 0,W=Z.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?Z.error?`Subagent execution failed: ${Z.error}.`:"":String(W),...Z.error?{error:{type:"execution_error",message:Z.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=nY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),J=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),Z=J&&J.state!=="none"?[{kind:"turn_recovery",assessment:J}]:[];return Z.push(...this.takeStartupAdoptedToolResultEvents()),Z}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=$,s.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?($,J,Z,Y)=>this.sessionRuntime.resolveContextualProjectRules($,J,Z,Y):void 0}}async chatWithSystem($,J){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:J}];return(await this.chatService.chat(Z)).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 J=this.toolExecutor.getRegistry(),Y=J.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)J.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let J=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of J.getAll())if(Z.has(Y.name))J.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),J=new Map;return $.forEach((Z)=>{let Y=J.get(Z.kind)||0;J.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(J),toolNames:$.map((Z)=>Z.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($,J){s.debug(`[MainAgent] ${$}`,J||"")}error($,J){s.error(`[MainAgent] ${$}`,J||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt,Z=await Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:J,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...x1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(Z.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f6({sessionId:"default",configDir:e(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let J=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${J} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await X6({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let J=o0.createIsolated({artifactWriter:new o2(`legacy-${VG()}`)});this.legacyMcpRegistry=J;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await J.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let Z=this.toolExecutor.getRegistry();Z.setMcpCatalogBarrier(()=>J.waitForCatalogIdle());let Y=J.getCatalogSnapshot();Z.replaceMcpTools(Y.tools),Z.registerAll(Z4(J));let Q=J.getInstructionsSnapshot();if(Z.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),J.on("catalogChanged",(X)=>{Z.replaceMcpTools(X.tools,X)}),J.on("contentCatalogChanged",(X)=>{Z.queueMcpContentChange(X)}),J.on("resourceUpdated",(X)=>{Z.queueMcpResourceUpdated(X)}),J.on("connectionLifecycleChanged",(X)=>{Z.queueMcpConnectionChange(X)}),J.on("log",(X)=>{Z.queueMcpLog(X)}),J.on("instructionsChanged",(X)=>{Z.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await d0(C());if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let J=this.subagentRegistry.getAllNames().length;if(J>0)s.debug(`Loaded ${J} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let J=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${J.join(", ")}`);let Z=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return J.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let J=[];for(let Y of $)if(Y.type==="text")J.push(Y.text);if(J.length===0)return $;let Z=J.join(`
|
|
871
871
|
`);try{let Y=await this.attachmentCollector.collect(Z);if(Y.length===0)return $;s.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 s.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let J=[],Z=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";J.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")J.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")Z.push(`- @${Q.path}: ${Q.error}`);let Y="";if(J.length>0)Y+=`
|
|
872
872
|
|
|
873
873
|
<system-reminder>
|
|
@@ -893,7 +893,7 @@ Warning: Some files could not be loaded:
|
|
|
893
893
|
`);return Q}}import{execFile as HG}from"node:child_process";import{createHash as QQ,randomBytes as zG}from"node:crypto";import{createReadStream as BG}from"node:fs";import{lstat as j3,mkdir as sY,mkdtemp as GG,readdir as KG,readFile as DG,readlink as qG,realpath as E$,rm as wG,stat as FG,writeFile as LG}from"node:fs/promises";import{basename as OG,isAbsolute as XQ,join as A$,relative as _G,resolve as z4}from"pathe";var oY=64,NG=/^[a-zA-Z0-9._-]+$/,bG=/^(?:agent|task)\+[a-zA-Z0-9_-]{1,40}$/,jG=2592000000,EG=100,tY=1048576,AG=2097152,eY=52428800,MG="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";class I0 extends Error{reason;constructor($,J){super(J);this.reason=$;this.name="WorktreeDeliveryConflict"}}class P6 extends Error{reason;constructor($){super("Task worktree is no longer available");this.reason=$;this.name="WorktreeUnavailableError"}}function $Q($){if(!$||$.length>oY)throw Error(`Worktree name must contain 1-${oY} characters`);for(let J of $.split("/"))if(J==="."||J===".."||!NG.test(J))throw Error(`Invalid worktree name "${$}": use letters, digits, dots, underscores, dashes, and optional "/" separators`)}function JQ($,J=12){return QQ("sha256").update($).digest("hex").slice(0,J)}function CG($){return $.replaceAll("/","+")}function S6($){if(!$||XQ($)||$.includes("\x00"))return!1;return!$.split("/").some((J)=>J==="..")}function TG($){let J=0,Z=0;for(let Y of $.split(`
|
|
894
894
|
`)){if(Y.startsWith("+")&&!Y.startsWith("+++"))J++;if(Y.startsWith("-")&&!Y.startsWith("---"))Z++}return{additions:J,deletions:Z}}function ZQ($,J){let Z=Buffer.from($);if(Z.byteLength<=J)return{patch:$,truncated:!1};let Y=`
|
|
895
895
|
[diff truncated]
|
|
896
|
-
`;if(J<=Buffer.byteLength(Y))return{patch:"",truncated:!0};let Q=Math.max(0,J-Buffer.byteLength(Y));return{patch:`${Z.subarray(0,Q).toString("utf8")}${Y}`,truncated:!0}}async function n($,J,Z={}){return new Promise((Y)=>{HG("git",J,{cwd:$,encoding:"utf-8",maxBuffer:Z.maxBuffer??10485760,env:{...process.env,...Z.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""}},(Q,X,W)=>{Y({code:Q==null?0:typeof Q.code==="number"?Q.code:1,stdout:X||"",stderr:W||""})})})}function RG($,J){return new Promise((Z,Y)=>{let Q=BG(J);Q.on("data",(X)=>$.update(X)),Q.on("error",Y),Q.on("end",Z)})}async function YQ($){let J=await n($,["--no-optional-locks","status","--porcelain=v1","-z","--untracked-files=all"]);_0(J,"Inspect source worktree");let Z=QQ("sha256");Z.update(J.stdout);let Y=J.stdout.split("\x00").filter(Boolean),Q=new Set;for(let X=0;X<Y.length;X++){let W=Y[X];if(W.length<4)continue;let V=W.slice(0,2),U=W.slice(3);if(S6(U))Q.add(U);if(/[RC]/.test(V)){let H=Y[++X];if(H&&S6(H))Q.add(H)}}for(let X of[...Q].sort()){Z.update(`\x00${X}\x00`);let W=A$($,X);try{let V=await j3(W);if(Z.update(`${V.mode}:${V.size}:`),V.isSymbolicLink())Z.update(await qG(W));else if(V.isFile())await RG(Z,W)}catch(V){if(V.code!=="ENOENT")throw V;Z.update("missing")}}return Z.digest("hex")}function _0($,J){if($.code!==0)throw Error(`${J} failed: ${$.stderr.trim()||$.stdout.trim()||"unknown git error"}`);return $.stdout.trim()}class WQ{storageRoot;sessions=new Map;sessionLocks=new F$;constructor($={}){this.storageRoot=$.storageRoot??e()}getActiveSession($){return this.sessions.get($)}getManagedRoot($){let J=z4($),Z=`${OG(J)}-${JQ(J)}`;return A$(this.storageRoot,"worktrees",Z)}async enter($){return this.sessionLocks.runExclusive($.sessionId,async()=>{if(this.sessions.has($.sessionId))throw Error("This session is already inside a managed worktree");let J=z4($.workspaceRoot),Z=await n(J,["rev-parse","--show-toplevel"]),[Y,Q]=await Promise.all([E$(J),E$(_0(Z,"Resolve repository root"))]),X=_G(Q,Y);if(X===".."||X.startsWith("../")||XQ(X))throw Error("Workspace is outside the resolved git repository");let W=$.name??`session-${Date.now().toString(36)}-${zG(3).toString("hex")}`;$Q(W);let[V,U,H,z]=await Promise.all([n(Q,["rev-parse","HEAD"]),n(Q,["branch","--show-current"]),n(Q,["status","--porcelain"]),YQ(Q)]),G=_0(V,"Resolve worktree base commit"),B=_0(U,"Resolve current branch");_0(H,"Inspect source worktree");let D=CG(W),q=`blade-worktree-${D}-${JQ($.sessionId,8)}`,w=this.getManagedRoot(Q),L=A$(w,D);await sY(w,{recursive:!0});let O=await n(Q,["worktree","add","-b",q,L,G]);_0(O,"Create worktree");let F={sessionId:$.sessionId,name:W,branch:q,baseCommit:G,originalBranch:B,repositoryRoot:Q,originalWorkspaceRoot:Y,worktreeRoot:L,workspaceRoot:X?A$(L,X):L,sourceHadChanges:H.stdout.trim().length>0,sourceStateFingerprint:z};return this.sessions.set($.sessionId,F),F})}async restoreSession($){return this.sessionLocks.runExclusive($.sessionId,async()=>{let J=this.sessions.get($.sessionId);if(J)return J;$Q($.name);let Z,Y,Q;try{[Z,Y,Q]=await Promise.all([E$($.worktreeRoot),E$($.workspaceRoot),E$($.repositoryRoot)])}catch(D){if(D.code==="ENOENT"||D.code==="ENOTDIR")throw new P6("missing");throw D}let[X,W,V,U]=await Promise.all([n(Z,["rev-parse","--show-toplevel"]),n(Z,["branch","--show-current"]),n(Z,["cat-file","-e",`${$.baseCommit}^{commit}`]),n(Q,["worktree","list","--porcelain"])]),H=await E$(_0(X,"Resolve restored worktree")),z=_0(W,"Resolve restored branch");if(_0(V,"Resolve restored base commit"),_0(U,"List restored worktrees"),H!==Z||z!==$.branch)throw new P6("metadata_mismatch");if(!U.stdout.split(`
|
|
896
|
+
`;if(J<=Buffer.byteLength(Y))return{patch:"",truncated:!0};let Q=Math.max(0,J-Buffer.byteLength(Y));return{patch:`${Z.subarray(0,Q).toString("utf8")}${Y}`,truncated:!0}}async function n($,J,Z={}){return new Promise((Y)=>{HG("git",J,{cwd:$,encoding:"utf-8",maxBuffer:Z.maxBuffer??10485760,env:{...process.env,...Z.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"",LC_ALL:"C"}},(Q,X,W)=>{Y({code:Q==null?0:typeof Q.code==="number"?Q.code:1,stdout:X||"",stderr:W||""})})})}function RG($,J){return new Promise((Z,Y)=>{let Q=BG(J);Q.on("data",(X)=>$.update(X)),Q.on("error",Y),Q.on("end",Z)})}async function YQ($){let J=await n($,["--no-optional-locks","status","--porcelain=v1","-z","--untracked-files=all"]);_0(J,"Inspect source worktree");let Z=QQ("sha256");Z.update(J.stdout);let Y=J.stdout.split("\x00").filter(Boolean),Q=new Set;for(let X=0;X<Y.length;X++){let W=Y[X];if(W.length<4)continue;let V=W.slice(0,2),U=W.slice(3);if(S6(U))Q.add(U);if(/[RC]/.test(V)){let H=Y[++X];if(H&&S6(H))Q.add(H)}}for(let X of[...Q].sort()){Z.update(`\x00${X}\x00`);let W=A$($,X);try{let V=await j3(W);if(Z.update(`${V.mode}:${V.size}:`),V.isSymbolicLink())Z.update(await qG(W));else if(V.isFile())await RG(Z,W)}catch(V){if(V.code!=="ENOENT")throw V;Z.update("missing")}}return Z.digest("hex")}function _0($,J){if($.code!==0)throw Error(`${J} failed: ${$.stderr.trim()||$.stdout.trim()||"unknown git error"}`);return $.stdout.trim()}class WQ{storageRoot;sessions=new Map;sessionLocks=new F$;constructor($={}){this.storageRoot=$.storageRoot??e()}getActiveSession($){return this.sessions.get($)}getManagedRoot($){let J=z4($),Z=`${OG(J)}-${JQ(J)}`;return A$(this.storageRoot,"worktrees",Z)}async enter($){return this.sessionLocks.runExclusive($.sessionId,async()=>{if(this.sessions.has($.sessionId))throw Error("This session is already inside a managed worktree");let J=z4($.workspaceRoot),Z=await n(J,["rev-parse","--show-toplevel"]),[Y,Q]=await Promise.all([E$(J),E$(_0(Z,"Resolve repository root"))]),X=_G(Q,Y);if(X===".."||X.startsWith("../")||XQ(X))throw Error("Workspace is outside the resolved git repository");let W=$.name??`session-${Date.now().toString(36)}-${zG(3).toString("hex")}`;$Q(W);let[V,U,H,z]=await Promise.all([n(Q,["rev-parse","HEAD"]),n(Q,["branch","--show-current"]),n(Q,["status","--porcelain"]),YQ(Q)]),G=_0(V,"Resolve worktree base commit"),B=_0(U,"Resolve current branch");_0(H,"Inspect source worktree");let D=CG(W),q=`blade-worktree-${D}-${JQ($.sessionId,8)}`,w=this.getManagedRoot(Q),L=A$(w,D);await sY(w,{recursive:!0});let O=await n(Q,["worktree","add","-b",q,L,G]);_0(O,"Create worktree");let F={sessionId:$.sessionId,name:W,branch:q,baseCommit:G,originalBranch:B,repositoryRoot:Q,originalWorkspaceRoot:Y,worktreeRoot:L,workspaceRoot:X?A$(L,X):L,sourceHadChanges:H.stdout.trim().length>0,sourceStateFingerprint:z};return this.sessions.set($.sessionId,F),F})}async restoreSession($){return this.sessionLocks.runExclusive($.sessionId,async()=>{let J=this.sessions.get($.sessionId);if(J)return J;$Q($.name);let Z,Y,Q;try{[Z,Y,Q]=await Promise.all([E$($.worktreeRoot),E$($.workspaceRoot),E$($.repositoryRoot)])}catch(D){if(D.code==="ENOENT"||D.code==="ENOTDIR")throw new P6("missing");throw D}let[X,W,V,U]=await Promise.all([n(Z,["rev-parse","--show-toplevel"]),n(Z,["branch","--show-current"]),n(Z,["cat-file","-e",`${$.baseCommit}^{commit}`]),n(Q,["worktree","list","--porcelain"])]),H=await E$(_0(X,"Resolve restored worktree")),z=_0(W,"Resolve restored branch");if(_0(V,"Resolve restored base commit"),_0(U,"List restored worktrees"),H!==Z||z!==$.branch)throw new P6("metadata_mismatch");if(!U.stdout.split(`
|
|
897
897
|
`).filter((D)=>D.startsWith("worktree ")).map((D)=>D.slice(9)).includes(Z))throw new P6("not_registered");let B={...$,repositoryRoot:Q,worktreeRoot:Z,workspaceRoot:Y};return this.sessions.set($.sessionId,B),B})}async getChangeSummary($){let J=this.sessions.get($);if(!J)return;return this.inspectChanges(J)}async getDiffArtifact($){let J=this.sessions.get($);if(!J)return;return this.inspectDiffArtifact(J)}async apply($){return this.sessionLocks.runExclusive($,async()=>{let J=this.sessions.get($);if(!J)throw new I0("artifact_unavailable","Task worktree is unavailable");let Z;try{Z=await E$(J.repositoryRoot)}catch{throw new I0("source_unavailable","Source workspace is unavailable")}if(Z!==J.repositoryRoot)throw new I0("source_unavailable","Source workspace identity changed");let Y=await n(Z,["rev-parse","HEAD"]),Q=_0(Y,"Resolve source HEAD");if(Q!==J.baseCommit)throw new I0("source_head_changed","Source branch advanced after this task started");if(!J.sourceStateFingerprint&&J.sourceHadChanges)throw new I0("legacy_dirty_source","This older task started from a modified source workspace and cannot be applied automatically");let X=await YQ(Z);if(J.sourceStateFingerprint&&X!==J.sourceStateFingerprint)throw new I0("source_state_changed","Source workspace changed after this task started");if(!J.sourceStateFingerprint&&X!==MG)throw new I0("source_state_changed","Source workspace has local changes");let W=await this.inspectChanges(J);if(!W)throw new I0("artifact_unavailable","Task changes could not be inspected");if(W.changedFiles===0)throw new I0("no_changes","Task has no changes to apply");await sY(this.storageRoot,{recursive:!0});let V=await GG(A$(this.storageRoot,"delivery-")),U=A$(V,"index"),H=A$(V,"changes.patch"),z={env:{GIT_INDEX_FILE:U}};try{_0(await n(J.worktreeRoot,["read-tree","HEAD"],z),"Prepare task delivery index"),_0(await n(J.worktreeRoot,["add","-A","--"],z),"Collect task changes");let G=_0(await n(J.worktreeRoot,["write-tree"],z),"Create task delivery tree"),B=await n(J.worktreeRoot,["diff","--binary","--full-index","--no-ext-diff",J.baseCommit,G,"--"],{maxBuffer:eY+1024});_0(B,"Generate task delivery patch");let D=B.stdout;if(!D)throw new I0("no_changes","Task has no changes to apply");if(Buffer.byteLength(D)>eY)throw new I0("artifact_unavailable","Task changes exceed the 50 MiB delivery limit");if(await LG(H,D,{mode:384}),(await n(Z,["apply","--check","--binary","--whitespace=nowarn",H])).code!==0)throw new I0("patch_conflict","Task changes conflict with the source workspace");if((await n(Z,["apply","--binary","--whitespace=nowarn",H])).code!==0)throw new I0("patch_conflict","Task changes could not be applied")}finally{await wG(V,{recursive:!0,force:!0})}return{action:"apply",workspaceRoot:J.originalWorkspaceRoot,worktreeRoot:J.worktreeRoot,branch:J.branch,sourceCommit:Q,...W}})}async cleanupStaleAgentWorktrees($){let J={scanned:0,removed:0,preserved:0,skipped:0,errors:[]},Z=$.maxAgeMs??jG;if(!Number.isFinite(Z)||Z<0)throw Error("maxAgeMs must be a finite non-negative number");let Y=await n(z4($.workspaceRoot),["rev-parse","--show-toplevel"]);if(Y.code!==0){let H=Y.stderr.trim()||Y.stdout.trim();if(!/not a git repository|not a git work tree/i.test(H))J.errors.push(`Resolve cleanup repository failed: ${H}`);return J}let Q;try{Q=await E$(Y.stdout.trim())}catch(H){return J.errors.push(`Resolve cleanup repository path failed: ${H instanceof Error?H.message:String(H)}`),J}let X=this.getManagedRoot(Q),W;try{W=await KG(X,{withFileTypes:!0})}catch(H){if(H.code!=="ENOENT")J.errors.push(`Read managed worktrees failed: ${H instanceof Error?H.message:String(H)}`);return J}let V=new Set([...this.sessions.values()].map((H)=>z4(H.worktreeRoot))),U=($.now??Date.now())-Z;for(let H of W){if(!H.isDirectory()||!bG.test(H.name)){J.skipped++;continue}let z=A$(X,H.name);if(J.scanned++,V.has(z4(z))){J.skipped++;continue}let G;try{G=(await FG(z)).mtimeMs}catch(N){J.errors.push(`Inspect stale worktree "${H.name}" failed: ${N instanceof Error?N.message:String(N)}`);continue}if(G>=U){J.skipped++;continue}let[B,D,q,w]=await Promise.all([n(z,["rev-parse","--show-toplevel"]),n(z,["branch","--show-current"]),n(z,["--no-optional-locks","status","--porcelain"]),n(z,["rev-list","--max-count=1","HEAD","--not","--remotes"])]);if(B.code!==0||D.code!==0||q.code!==0||w.code!==0){J.errors.push(`Git inspection failed for stale worktree "${H.name}"`);continue}let L=D.stdout.trim(),O,F;try{[O,F]=await Promise.all([E$(z),E$(B.stdout.trim())])}catch(N){J.errors.push(`Canonical path inspection failed for "${H.name}": ${N instanceof Error?N.message:String(N)}`);continue}if(O!==F||!/^blade-worktree-(?:agent|task)\+/.test(L)){J.errors.push(`Managed worktree identity mismatch for "${H.name}"`);continue}if(q.stdout.trim().length>0||w.stdout.trim().length>0){J.preserved++;continue}let b=await n(Q,["worktree","remove","--force",z]);if(b.code!==0){J.errors.push(`Remove stale worktree "${H.name}" failed: ${b.stderr.trim()||b.stdout.trim()}`);continue}J.removed++;let _=await n(Q,["branch","-D",L]);if(_.code!==0)J.errors.push(`Delete stale branch "${L}" failed: ${_.stderr.trim()||_.stdout.trim()}`)}if(J.removed>0){let H=await n(Q,["worktree","prune"]);if(H.code!==0)J.errors.push(`Prune stale worktree registrations failed: ${H.stderr.trim()||H.stdout.trim()}`)}return J}async exit($){return this.sessionLocks.runExclusive($.sessionId,async()=>{let J=this.sessions.get($.sessionId);if(!J)return{action:$.action,workspaceRoot:$.workspaceRoot??"",removed:!1,noop:!0};if($.action==="keep")return this.sessions.delete($.sessionId),{action:"keep",workspaceRoot:J.originalWorkspaceRoot,worktreeRoot:J.worktreeRoot,branch:J.branch,removed:!1};let Z=await this.inspectChanges(J);if(!Z&&!$.discardChanges)throw Error("Could not verify worktree state. Refusing removal without discard_changes=true");let{changedFiles:Y,commits:Q}=Z??{changedFiles:0,commits:0};if(!$.discardChanges&&(Y>0||Q>0)){let U=[Y>0?`${Y} uncommitted ${Y===1?"file":"files"}`:"",Q>0?`${Q} unmerged ${Q===1?"commit":"commits"}`:""].filter(Boolean);throw Error(`Worktree has ${U.join(" and ")}. Use action="keep" or confirm discard_changes=true`)}let X=["worktree","remove"];if($.discardChanges)X.push("--force");X.push(J.worktreeRoot);let W=await n(J.repositoryRoot,X);_0(W,"Remove worktree");let V=await n(J.repositoryRoot,["branch","-D",J.branch]);return this.sessions.delete($.sessionId),_0(V,"Delete worktree branch"),{action:"remove",workspaceRoot:J.originalWorkspaceRoot,worktreeRoot:J.worktreeRoot,branch:J.branch,removed:!0,discardedFiles:$.discardChanges?Y:void 0,discardedCommits:$.discardChanges?Q:void 0}})}releaseSession($){this.sessions.delete($)}coordinationStatsForTests(){return this.sessionLocks.getStats()}async inspectDiffArtifact($){let[J,Z]=await Promise.all([n($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),n($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(J.code!==0||Z.code!==0)return null;let Y=new Set(J.stdout.split("\x00").filter(S6)),Q=new Set(Z.stdout.split("\x00").filter(S6)),X=[...new Set([...Y,...Q])].sort(),W=X.slice(0,EG),V=await Promise.all(W.map(async(G)=>{let B=!Y.has(G)&&Q.has(G);try{let F=await j3(A$($.worktreeRoot,G));if(F.size>tY)return{path:G,patch:"",additions:0,deletions:0,binary:!1,truncated:!0};if(B&&!F.isFile())return{path:G,patch:"",additions:0,deletions:0,binary:!0,truncated:!1}}catch(F){if(F.code!=="ENOENT")throw F}let D=B?await n($.worktreeRoot,["diff","--no-index","--no-ext-diff","--no-color","--unified=3","--","/dev/null",G]):await n($.worktreeRoot,["diff","--no-ext-diff","--no-color","--unified=3",$.baseCommit,"--",G]);if(!B&&D.code!==0||B&&![0,1].includes(D.code))throw Error(`Generate task diff failed for ${G}`);let q=B&&D.stdout.length===0?[`diff --git a/${G} b/${G}`,"new file mode 100644","--- /dev/null",`+++ b/${G}`,""].join(`
|
|
898
898
|
`):D.stdout,w=/^Binary files .+ differ$/m.test(q)||q.includes("GIT binary patch"),L=w?{additions:0,deletions:0}:TG(q),O=ZQ(q,tY);return{path:G,patch:O.patch,...L,binary:w,truncated:O.truncated}})),U=AG,H=X.length>W.length,z=V.map((G)=>{let B=ZQ(G.patch,U);return U=Math.max(0,U-Buffer.byteLength(B.patch)),H||=B.truncated,B.truncated?{...G,patch:B.patch,truncated:!0}:G});return{baseCommit:$.baseCommit,files:z,truncated:H}}async inspectChanges($){let[J,Z,Y,Q]=await Promise.all([n($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),n($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`]),n($.worktreeRoot,["diff","--numstat",$.baseCommit,"--"]),n($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(J.code!==0||Z.code!==0||Y.code!==0||Q.code!==0)return null;let X=0,W=0;for(let V of Y.stdout.split(`
|
|
899
899
|
`)){let[U,H]=V.split("\t");if(/^\d+$/.test(U??""))X+=Number(U);if(/^\d+$/.test(H??""))W+=Number(H)}for(let V of Q.stdout.split("\x00").filter(Boolean))try{let U=A$($.worktreeRoot,V),H=await j3(U);if(!H.isFile()||H.size>10485760)continue;let z=await DG(U);if(z.includes(0))continue;let G=z.toString("utf8");if(G.length>0)X+=G.split(`
|
|
@@ -1684,7 +1684,7 @@ ${Z}
|
|
|
1684
1684
|
`)),{success:!0,message:"Schedules listed",content:U.join(`
|
|
1685
1685
|
`)}}case"create":{let V=tw(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let U={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(U),z=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
|
|
1686
1686
|
${b9(H.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let z=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let U=await $.remove(V);return Y.sendMessage(U?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:U,message:U?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let U=await $.setEnabled(V,Q==="enable");return Y.sendMessage(U?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(U),message:U?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await ew(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1687
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var ZV=$F();import*as R2 from"node:fs/promises";import*as f2 from"node:path";async function VV($,J={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=J,W=X??f4(Q??C());if(!X){let B=await JF($,Q??C(),Z,Y);if(B)return B}let V;try{V=(await R2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>f2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(B)=>{try{let D=await R2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of H){if(z.length>=Z)break;let D=f2.basename(B,".jsonl"),q=await ZF(B,G,Y,D);if(z.push(...q),z.length>=Z){z.length=Z;break}}return z}async function JF($,J,Z,Y){try{let{syncAll:Q}=await import("./chunk-hb680ebj.js"),X=await XV();if(!X)return null;let{SessionService:W}=await import("./chunk-
|
|
1687
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var ZV=$F();import*as R2 from"node:fs/promises";import*as f2 from"node:path";async function VV($,J={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=J,W=X??f4(Q??C());if(!X){let B=await JF($,Q??C(),Z,Y);if(B)return B}let V;try{V=(await R2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>f2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(B)=>{try{let D=await R2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of H){if(z.length>=Z)break;let D=f2.basename(B,".jsonl"),q=await ZF(B,G,Y,D);if(z.push(...q),z.length>=Z){z.length=Z;break}}return z}async function JF($,J,Z,Y){try{let{syncAll:Q}=await import("./chunk-hb680ebj.js"),X=await XV();if(!X)return null;let{SessionService:W}=await import("./chunk-j08fc7cy.js");await Q(X,W.projectionDeriverForSearch());let V=f2.resolve(J),U=WV(X,$,V,Z*4),H=Y?$:$.toLowerCase(),z=[];for(let G of U){if(G.role!=="user"&&G.role!=="assistant")continue;let B=j9(G.text,H,Y,G.session_id,G.role,G.timestamp??void 0,0);if(B)z.push(B);if(z.length>=Z)break}return z}catch{return null}}async function ZF($,J,Z,Y){try{let Q=await R2.readFile($,"utf8"),W=Q.split(`
|
|
1688
1688
|
`).flatMap((G,B)=>{if(!G.trim())return[];try{return[{event:JSON.parse(G),index:B}]}catch{return[]}});if(!W.some(({event:G})=>G.type==="session_created"))return YF(W,J,Z,Y);let U=new Map(W.flatMap(({event:G,index:B})=>typeof G.id==="string"?[[G.id,B+1]]:[])),H=YV(QV(Q,$)),z=new Map;for(let G of H){if(G.type==="message_created"&&(G.data.role==="user"||G.data.role==="assistant"))z.set(G.data.messageId,{role:G.data.role,content:[],timestamp:G.timestamp,lineNumber:U.get(G.id)??0});if(G.type==="part_created"&&G.data.partType==="text"){let B=z.get(G.data.messageId),D=G.data.payload.text;if(B&&typeof D==="string")B.content.push(D)}}return[...z.values()].flatMap((G)=>{let B=j9(G.content.join(" "),J,Z,Y,G.role,G.timestamp,G.lineNumber);return B?[B]:[]})}catch{return[]}}function YF($,J,Z,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",U=j9(V,J,Z,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return U?[U]:[]})}function j9($,J,Z,Y,Q,X,W){if(!$)return;let V=Z?$:$.toLowerCase();if(!V.includes(J))return;let U=V.indexOf(J),H=Math.max(0,U-80),z=Math.min($.length,U+J.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function UV($){if($.length===0)return"没有找到匹配的历史记录";let J=[`**找到 ${$.length} 条匹配:**
|
|
1689
1689
|
`];for(let Z of $){let Y=Z.timestamp?new Date(Z.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=Z.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";J.push(`${Q} \`${Z.sessionId.slice(0,8)}\` (${Y})`),J.push(` ${Z.content}`),J.push("")}return J.join(`
|
|
1690
1690
|
`)}var QF={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($,J){let Z=i(J);if($.length===0)return Z.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");Z.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await VV(Y,{maxResults:15,projectPath:J.cwd}),X=UV(Q);return Z.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return Z.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},HV=QF;var XF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,J)=>{try{let Z=J.workspaceRoot??J.cwd;return await R$(Z,async(Y)=>{await Y.skills.refresh(),p1(Z),await m1(Z)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(Z){let Y=`获取 Skills 失败: ${Z instanceof Error?Z.message:"未知错误"}`;return g().addAssistantMessage(Y),{success:!1,error:Y}}}},zV=XF;import WF from"node:path";function D8($){if($<1000)return`${$}ms`;let J=Math.floor($/1000);if(J<60)return`${J}s`;let Z=Math.floor(J/60);if(Z<60)return`${Z}m ${J%60}s`;return`${Math.floor(Z/60)}h ${Z%60}m`}function BV($){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 GV($,J){if($.length<=J)return $;return $.slice(0,J-3)+"..."}async function VF($,J){let Z=i(J),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=J.sessionId??"",V=J.sessionId?{sessionId:J.sessionId,projectPath:WF.resolve(J.workspaceRoot??J.cwd)}:void 0;if(Y==="resume"){let D=$[1],q=$.slice(2).join(" ").trim();if(!D||!q)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!J.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let w=await J.subagents.resume(D,q),L=`Resumed \`${D}\` as \`${w.session.id}\` (depth ${w.session.resumeDepth}).`;return Z.sendMessage(L),{success:!0,message:L,data:{action:"subagent_resumed",sourceAgentId:D,subagent:w.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return Z.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let U=[`**后台任务列表**
|
package/package.json
CHANGED
package/dist/chunk-d7frbjn7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{xf as a,yf as b}from"./chunk-3gbteqvh.js";import"./chunk-c33wff11.js";import"./chunk-gmpsfkgg.js";export{a as globalOptions,b as cliConfig};
|
package/dist/chunk-g2kqz1mm.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-nfdtrn3t.js";import"./chunk-c33wff11.js";import"./chunk-gmpsfkgg.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|