blade-code 0.10.87 → 0.10.88

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-kvw91990.js → chunk-28pywda6.js} +1 -1
  3. package/dist/{chunk-qrsxw68t.js → chunk-48r0nbj0.js} +1 -1
  4. package/dist/{chunk-9zaxwfa5.js → chunk-4v0jqa9g.js} +1 -1
  5. package/dist/{chunk-wyk6yc02.js → chunk-4yf7b4ev.js} +1 -1
  6. package/dist/{chunk-51rayzy2.js → chunk-5d1mmf11.js} +1 -1
  7. package/dist/{chunk-kpmaxt15.js → chunk-5fbasngx.js} +1 -1
  8. package/dist/{chunk-pknksqe8.js → chunk-5j1pfevy.js} +1 -1
  9. package/dist/{chunk-8wp4px6b.js → chunk-6f4zxqcg.js} +1 -1
  10. package/dist/{chunk-dtq9t14j.js → chunk-7x82wtvn.js} +1 -1
  11. package/dist/{chunk-1ajybpd8.js → chunk-84te16y6.js} +1 -1
  12. package/dist/{chunk-yv1p4bcd.js → chunk-93q3t4jk.js} +1 -1
  13. package/dist/{chunk-kz40nxhm.js → chunk-96ma25s6.js} +1 -1
  14. package/dist/{chunk-37x3xyqk.js → chunk-9e96b872.js} +1 -1
  15. package/dist/{chunk-am6pzb5h.js → chunk-a3eynw8a.js} +1 -1
  16. package/dist/{chunk-b7k56qfy.js → chunk-crzktq2e.js} +1 -1
  17. package/dist/{chunk-hgzs14b2.js → chunk-cx3ghkdn.js} +1 -1
  18. package/dist/chunk-d0wn5caz.js +1 -0
  19. package/dist/{chunk-07hn8br0.js → chunk-dst8h9c7.js} +1 -1
  20. package/dist/{chunk-3dsggcwt.js → chunk-e6adb7n8.js} +1 -1
  21. package/dist/{chunk-0mrh85yz.js → chunk-eexw1r8q.js} +1 -1
  22. package/dist/{chunk-k1t91vp3.js → chunk-em42qzg6.js} +1 -1
  23. package/dist/{chunk-azpkmttg.js → chunk-hdgee5xk.js} +1 -1
  24. package/dist/{chunk-78x3z8cf.js → chunk-hrzfmdhp.js} +1 -1
  25. package/dist/{chunk-q2t49c64.js → chunk-jpbj8h8f.js} +1 -1
  26. package/dist/{chunk-dp72xx4j.js → chunk-k358j1vk.js} +2 -2
  27. package/dist/{chunk-w2tcjj0w.js → chunk-m7y3rvxj.js} +1 -1
  28. package/dist/{chunk-m3xycm44.js → chunk-mgnjmbwq.js} +1 -1
  29. package/dist/{chunk-9ap72kq4.js → chunk-mjx5epcb.js} +1 -1
  30. package/dist/{chunk-029q49wd.js → chunk-n9y19kem.js} +3 -3
  31. package/dist/{chunk-xn8kfrry.js → chunk-r5zejm8a.js} +1 -1
  32. package/dist/chunk-rhgaymf2.js +1 -0
  33. package/dist/{chunk-4amesx3y.js → chunk-rx60xs95.js} +1 -1
  34. package/dist/{chunk-rjbxqscc.js → chunk-w19aw6n3.js} +1 -1
  35. package/dist/{chunk-d1m21wr4.js → chunk-wtj4ft4m.js} +1 -1
  36. package/dist/{chunk-78cjfm2t.js → chunk-xcp4zpby.js} +1 -1
  37. package/dist/{chunk-t9xtxg1a.js → chunk-y1vpje4h.js} +1 -1
  38. package/dist/{chunk-9fxvqbve.js → chunk-zd028k7y.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-17s7gvqm.js +0 -1
  41. package/dist/chunk-6gnerzt5.js +0 -1
@@ -1,4 +1,4 @@
1
- import{ta as G5}from"./chunk-943vkrwc.js";import{Ca as LY,Da as o3,Ea as c0,wa as C,xa as l0}from"./chunk-9ap72kq4.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-07hn8br0.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-azpkmttg.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-wyk6yc02.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-dtq9t14j.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-kz40nxhm.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-51rayzy2.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-3dsggcwt.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-kvw91990.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-943vkrwc.js";import{Ca as LY,Da as o3,Ea as c0,wa as C,xa as l0}from"./chunk-mjx5epcb.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-dst8h9c7.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-hdgee5xk.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-4yf7b4ev.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-7x82wtvn.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-96ma25s6.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-5d1mmf11.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-e6adb7n8.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-28pywda6.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-t9xtxg1a.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-y1vpje4h.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-yv1p4bcd.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-93q3t4jk.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{a as T,b as W,c as X,d as Y}from"./chunk-4amesx3y.js";import"./chunk-xxk5d2v6.js";import"./chunk-rj49h1x1.js";import"./chunk-78x3z8cf.js";import"./chunk-m3xycm44.js";import"./chunk-qrsxw68t.js";import"./chunk-029q49wd.js";import"./chunk-943vkrwc.js";import"./chunk-9ap72kq4.js";import"./chunk-f7p7tzx2.js";import"./chunk-07hn8br0.js";import"./chunk-7avnhnjn.js";import"./chunk-azpkmttg.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as R}from"./chunk-k1t91vp3.js";import"./chunk-dm1knbf8.js";import{Ke as Q}from"./chunk-wyk6yc02.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import"./chunk-q8jfwyr4.js";import"./chunk-dtq9t14j.js";import"./chunk-kz40nxhm.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-51rayzy2.js";import"./chunk-ckqz2btx.js";import"./chunk-3dsggcwt.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import{ui as M}from"./chunk-kvw91990.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import m from"chalk";import K from"open";var A=`
1
+ import{a as T,b as W,c as X,d as Y}from"./chunk-rx60xs95.js";import"./chunk-xxk5d2v6.js";import"./chunk-rj49h1x1.js";import"./chunk-hrzfmdhp.js";import"./chunk-mgnjmbwq.js";import"./chunk-48r0nbj0.js";import"./chunk-n9y19kem.js";import"./chunk-943vkrwc.js";import"./chunk-mjx5epcb.js";import"./chunk-f7p7tzx2.js";import"./chunk-dst8h9c7.js";import"./chunk-7avnhnjn.js";import"./chunk-hdgee5xk.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as R}from"./chunk-em42qzg6.js";import"./chunk-dm1knbf8.js";import{Ke as Q}from"./chunk-4yf7b4ev.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import"./chunk-q8jfwyr4.js";import"./chunk-7x82wtvn.js";import"./chunk-96ma25s6.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-5d1mmf11.js";import"./chunk-ckqz2btx.js";import"./chunk-e6adb7n8.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import{ui as M}from"./chunk-28pywda6.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -0,0 +1 @@
1
+ import{h as a,i as b,j as c,k as d,l as e}from"./chunk-9e96b872.js";import"./chunk-28pywda6.js";import"./chunk-m5hnyxf3.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,4 +1,4 @@
1
- import{e as b4,f as C4}from"./chunk-xxk5d2v6.js";import{g as O1}from"./chunk-rj49h1x1.js";import{s as J0,t as x4}from"./chunk-78x3z8cf.js";import{u as oO}from"./chunk-m3xycm44.js";import{A as x$,v as n$,w as e1,x as O$,y as $$,z as x0}from"./chunk-qrsxw68t.js";import{$ as K4,C as p$,D as h4,G as v$,H as N0,I as k1,J as n0,K as w1,L as EO,M as l$,N as i$,O as c$,P as A1,Q as mO,R as S0,U as y0,V as f0,X as r4,Y as a$,Z as o$,_ as N4,aa as W4,ba as F4,ca as U4,da as _4,ea as D4,fa as H4,ga as L4,ja as j4,ma as zx,ra as g4}from"./chunk-029q49wd.js";import{Ea as UO,ya as W$}from"./chunk-9ap72kq4.js";import{$a as t1,Ia as z1,La as p4,Ma as q1,Na as t$,Oa as s$,Pa as v4,Qa as d4,Ra as I1,Sa as l4,Ta as sO,Ua as R4,Va as E4,Wa as k4,Xa as r$,Ya as e$,Za as O4,_a as $4,ab as g1}from"./chunk-f7p7tzx2.js";import{Ab as B1,Jb as nO,lb as gO,mb as p,ob as S,pb as d$}from"./chunk-07hn8br0.js";import{Ub as k$}from"./chunk-7avnhnjn.js";import{Ad as z0,Dd as D1,Id as u$,Jd as H1,Kd as L1,Ld as R,Nc as y$,Yc as f$,hd as t0,nc as q$,nd as I0,od as j1,pd as P0,rd as m$,uc as I$,vc as U1,wc as P$,xc as _1,xd as h$,yd as g$}from"./chunk-azpkmttg.js";import{Fe as t4,Je as QO,Ne as D$,Ue as BO}from"./chunk-wyk6yc02.js";import{Ve as F1}from"./chunk-3aejg2jy.js";import{kf as R$}from"./chunk-q8jfwyr4.js";import{mf as o0}from"./chunk-dtq9t14j.js";import{Df as j0,Ef as b0,If as Fx,Lf as jO,Mf as C0,Pf as Ux,uf as s4,wf as P4,zf as V4}from"./chunk-kz40nxhm.js";import{bg as H$,cg as E$}from"./chunk-q15sm6vj.js";import{gg as X$,hg as Z0}from"./chunk-51rayzy2.js";import{Tg as b$,Wg as C$,Yg as S$,jh as V$,oh as T0,zg as K$}from"./chunk-3dsggcwt.js";import{rh as K1}from"./chunk-ne5w9ds8.js";import{sh as q,uh as V,vh as eO,xh as JO}from"./chunk-45a1tsk1.js";import{Ch as W1,zh as r0}from"./chunk-12e2yj9p.js";import{Gh as c}from"./chunk-1g5s5vf3.js";import{gi as o}from"./chunk-hkh2nsam.js";import{mi as cO}from"./chunk-rxjyc6ff.js";import{oi as U$,pi as T$,ri as _$,si as j$}from"./chunk-7a8j14gg.js";import{ui as Q0}from"./chunk-kvw91990.js";import{Bi as h1}from"./chunk-bvp5wpz8.js";import{Hi as i0,Li as Z$,Mi as s0}from"./chunk-1mb2y0e0.js";import{Oi as y1}from"./chunk-m5hnyxf3.js";var A3={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function M3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as u1,readFileSync as g0}from"node:fs";import{createServer as e2}from"node:http";import{networkInterfaces as O3}from"node:os";import{dirname as $3,extname as x3,join as dO}from"node:path";import{fileURLToPath as Q3}from"node:url";import{brotliCompressSync as Z3,gzipSync as J3,constants as Y3}from"node:zlib";import{Hono as z3}from"hono";import{cors as G3}from"hono/cors";import{WebSocketServer as X3}from"ws";var $0=o("Service"),Hx=30000,Lx=new Set(["completed","failed","cancelled","interrupted"]);class G1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??t1.getInstance(),this.tickMs=O.tickMs??Hx}start(){if(this.timer)return;$0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=S.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!Lx.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,$0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){$0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),$0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=x.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??Bx(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),S.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),$0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let G=Z instanceof Error?Z.message:String(Z);$0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:G,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Z=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function Bx(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,x,$=500,Q){super(x);this.code=O;this.statusCode=$;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends xO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class D extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class k extends xO{constructor(O){super("CONFLICT",O,409)}}class kO extends xO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class qO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var k3=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as wx}from"hono";var X1=o("Service"),Ax=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(JO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function Mx(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var s1=()=>{let O=new wx;return O.get("/",async(x)=>{try{let $=QO();return x.json($?Mx($):{})}catch($){return X1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),Q=q(Ax,$);if(!Q.success)throw new D("Invalid config update format");let{updates:Z,options:G}=Q.data;return await BO().updateConfig(Z,G),x.json({success:!0,updates:Z})}catch($){throw X1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=QO();return x.json($?.permissions||{})}catch($){return X1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as Tx}from"hono";import{streamSSE as jx}from"hono/streaming";function r1(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
1
+ import{e as b4,f as C4}from"./chunk-xxk5d2v6.js";import{g as O1}from"./chunk-rj49h1x1.js";import{s as J0,t as x4}from"./chunk-hrzfmdhp.js";import{u as oO}from"./chunk-mgnjmbwq.js";import{A as x$,v as n$,w as e1,x as O$,y as $$,z as x0}from"./chunk-48r0nbj0.js";import{$ as K4,C as p$,D as h4,G as v$,H as N0,I as k1,J as n0,K as w1,L as EO,M as l$,N as i$,O as c$,P as A1,Q as mO,R as S0,U as y0,V as f0,X as r4,Y as a$,Z as o$,_ as N4,aa as W4,ba as F4,ca as U4,da as _4,ea as D4,fa as H4,ga as L4,ja as j4,ma as zx,ra as g4}from"./chunk-n9y19kem.js";import{Ea as UO,ya as W$}from"./chunk-mjx5epcb.js";import{$a as t1,Ia as z1,La as p4,Ma as q1,Na as t$,Oa as s$,Pa as v4,Qa as d4,Ra as I1,Sa as l4,Ta as sO,Ua as R4,Va as E4,Wa as k4,Xa as r$,Ya as e$,Za as O4,_a as $4,ab as g1}from"./chunk-f7p7tzx2.js";import{Ab as B1,Jb as nO,lb as gO,mb as p,ob as S,pb as d$}from"./chunk-dst8h9c7.js";import{Ub as k$}from"./chunk-7avnhnjn.js";import{Ad as z0,Dd as D1,Id as u$,Jd as H1,Kd as L1,Ld as R,Nc as y$,Yc as f$,hd as t0,nc as q$,nd as I0,od as j1,pd as P0,rd as m$,uc as I$,vc as U1,wc as P$,xc as _1,xd as h$,yd as g$}from"./chunk-hdgee5xk.js";import{Fe as t4,Je as QO,Ne as D$,Ue as BO}from"./chunk-4yf7b4ev.js";import{Ve as F1}from"./chunk-3aejg2jy.js";import{kf as R$}from"./chunk-q8jfwyr4.js";import{mf as o0}from"./chunk-7x82wtvn.js";import{Df as j0,Ef as b0,If as Fx,Lf as jO,Mf as C0,Pf as Ux,uf as s4,wf as P4,zf as V4}from"./chunk-96ma25s6.js";import{bg as H$,cg as E$}from"./chunk-q15sm6vj.js";import{gg as X$,hg as Z0}from"./chunk-5d1mmf11.js";import{Tg as b$,Wg as C$,Yg as S$,jh as V$,oh as T0,zg as K$}from"./chunk-e6adb7n8.js";import{rh as K1}from"./chunk-ne5w9ds8.js";import{sh as q,uh as V,vh as eO,xh as JO}from"./chunk-45a1tsk1.js";import{Ch as W1,zh as r0}from"./chunk-12e2yj9p.js";import{Gh as c}from"./chunk-1g5s5vf3.js";import{gi as o}from"./chunk-hkh2nsam.js";import{mi as cO}from"./chunk-rxjyc6ff.js";import{oi as U$,pi as T$,ri as _$,si as j$}from"./chunk-7a8j14gg.js";import{ui as Q0}from"./chunk-28pywda6.js";import{Bi as h1}from"./chunk-bvp5wpz8.js";import{Hi as i0,Li as Z$,Mi as s0}from"./chunk-1mb2y0e0.js";import{Oi as y1}from"./chunk-m5hnyxf3.js";var A3={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function M3(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as u1,readFileSync as g0}from"node:fs";import{createServer as e2}from"node:http";import{networkInterfaces as O3}from"node:os";import{dirname as $3,extname as x3,join as dO}from"node:path";import{fileURLToPath as Q3}from"node:url";import{brotliCompressSync as Z3,gzipSync as J3,constants as Y3}from"node:zlib";import{Hono as z3}from"hono";import{cors as G3}from"hono/cors";import{WebSocketServer as X3}from"ws";var $0=o("Service"),Hx=30000,Lx=new Set(["completed","failed","cancelled","interrupted"]);class G1{dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??t1.getInstance(),this.tickMs=O.tickMs??Hx}start(){if(this.timer)return;$0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=S.subscribe((O)=>{if(O.type!=="task.status")return;let x=O.properties.taskStatus;if(typeof x!=="string"||!Lx.has(x))return;this.recordTerminalStatus(O.sessionId,x,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,$0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let x=await this.store.list();for(let $ of x)await this.evaluate($,O)}catch(x){$0.warn("[TaskScheduler] Tick failed:",x)}finally{this.ticking=!1}}async evaluate(O,x){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=x.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),$0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=x.getTime()))return;await this.fire(O,x)}async fire(O,x=new Date,$={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let Q=x.toISOString();try{let Z=await this.dispatch({prompt:O.prompt,title:O.title??Bx(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastRunSessionId:Z.session.sessionId,lastStatus:Z.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),S.publish({sessionId:Z.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:Q,sessionId:Z.session.sessionId,runId:Z.runId,status:Z.status}),$0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Z.session.sessionId} (${Z.status})`)}catch(Z){let G=Z instanceof Error?Z.message:String(Z);$0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Z);let Y=O.trigger.kind==="once"?null:$.manual?O.nextRunAt?new Date(O.nextRunAt):null:z1(O.trigger,x,x);await this.store.update(O.id,{lastRunAt:Q,lastStatus:"error",lastError:G,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,x,$){let Z=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Z)return;await this.store.update(Z.id,{lastStatus:x,...$?{lastError:$}:{lastError:void 0}})}}function Bx(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class xO extends Error{code;statusCode;details;constructor(O,x,$=500,Q){super(x);this.code=O;this.statusCode=$;this.details=Q;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends xO{constructor(O,x){super("NOT_FOUND",x?`${O} not found: ${x}`:`${O} not found`,404)}}class D extends xO{constructor(O){super("BAD_REQUEST",O,400)}}class k extends xO{constructor(O){super("CONFLICT",O,409)}}class kO extends xO{constructor(O,x){super("TOO_MANY_REQUESTS",O,429,x)}}class qO extends xO{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class LO extends xO{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class t extends xO{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var k3=V.Object({error:V.Object({code:V.String(),message:V.String(),details:V.Optional(V.Record(V.String(),V.Unknown()))})});import{Hono as wx}from"hono";var X1=o("Service"),Ax=V.Object({updates:V.Record(V.String(),V.Any()),options:V.Optional(V.Object({scope:V.Optional(JO(["local","project","global"])),immediate:V.Optional(V.Boolean())}))});function Mx(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,agentTeamsEnabled:O.agentTeamsEnabled===!0,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var s1=()=>{let O=new wx;return O.get("/",async(x)=>{try{let $=QO();return x.json($?Mx($):{})}catch($){return X1.error("[ConfigRoutes] Failed to get config:",$),x.json({})}}),O.put("/",async(x)=>{try{let $=await x.req.json(),Q=q(Ax,$);if(!Q.success)throw new D("Invalid config update format");let{updates:Z,options:G}=Q.data;return await BO().updateConfig(Z,G),x.json({success:!0,updates:Z})}catch($){throw X1.error("[ConfigRoutes] Failed to update config:",$),$}}),O.get("/permissions",async(x)=>{try{let $=QO();return x.json($?.permissions||{})}catch($){return X1.error("[ConfigRoutes] Failed to get permissions:",$),x.json({})}}),O};import{Hono as Tx}from"hono";import{streamSSE as jx}from"hono/streaming";function r1(O){let x="";if(O.id!==void 0)x+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)x+=`event: ${O.event}
3
3
  `;for(let $ of O.data.split(/\r\n|\r|\n/))x+=`data: ${$}
4
4
  `;if(O.retry!==void 0)x+=`retry: ${O.retry}
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-4amesx3y.js";import"./chunk-xxk5d2v6.js";import"./chunk-rj49h1x1.js";import"./chunk-78x3z8cf.js";import"./chunk-m3xycm44.js";import"./chunk-qrsxw68t.js";import"./chunk-029q49wd.js";import"./chunk-943vkrwc.js";import"./chunk-9ap72kq4.js";import"./chunk-f7p7tzx2.js";import"./chunk-07hn8br0.js";import"./chunk-7avnhnjn.js";import"./chunk-azpkmttg.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as n}from"./chunk-k1t91vp3.js";import"./chunk-dm1knbf8.js";import{Ke as s}from"./chunk-wyk6yc02.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import"./chunk-q8jfwyr4.js";import"./chunk-dtq9t14j.js";import"./chunk-kz40nxhm.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-51rayzy2.js";import"./chunk-ckqz2btx.js";import"./chunk-3dsggcwt.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-kvw91990.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{a,b as i,c as l,d as m}from"./chunk-rx60xs95.js";import"./chunk-xxk5d2v6.js";import"./chunk-rj49h1x1.js";import"./chunk-hrzfmdhp.js";import"./chunk-mgnjmbwq.js";import"./chunk-48r0nbj0.js";import"./chunk-n9y19kem.js";import"./chunk-943vkrwc.js";import"./chunk-mjx5epcb.js";import"./chunk-f7p7tzx2.js";import"./chunk-dst8h9c7.js";import"./chunk-7avnhnjn.js";import"./chunk-hdgee5xk.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import{oe as n}from"./chunk-em42qzg6.js";import"./chunk-dm1knbf8.js";import{Ke as s}from"./chunk-4yf7b4ev.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-vyk5nxsz.js";import"./chunk-q8jfwyr4.js";import"./chunk-7x82wtvn.js";import"./chunk-96ma25s6.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-5d1mmf11.js";import"./chunk-ckqz2btx.js";import"./chunk-e6adb7n8.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-28pywda6.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1 +1 @@
1
- import{Gf as a,Hf as b,If as c,Jf as d,Kf as e,Lf as f,Mf as g,Nf as h,Of as i,Pf as j}from"./chunk-kz40nxhm.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-51rayzy2.js";import"./chunk-ckqz2btx.js";import"./chunk-3dsggcwt.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-kvw91990.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{Gf as a,Hf as b,If as c,Jf as d,Kf as e,Lf as f,Mf as g,Nf as h,Of as i,Pf as j}from"./chunk-96ma25s6.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-tc1001nx.js";import"./chunk-5d1mmf11.js";import"./chunk-ckqz2btx.js";import"./chunk-e6adb7n8.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-28pywda6.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,4 +1,4 @@
1
- import{me as s}from"./chunk-x079eg84.js";import{Fe as o}from"./chunk-wyk6yc02.js";import{$g as E,Pg as y,Qg as D,Sg as N,Ug as j,Vg as F,Xg as R,ah as _,bh as f,ch as C,eh as S,fh as m,jh as c,oh as l,ph as n}from"./chunk-3dsggcwt.js";import{qh as Y}from"./chunk-ne5w9ds8.js";import{sh as x,uh as k,xh as Z}from"./chunk-45a1tsk1.js";import{Eh as X}from"./chunk-1g5s5vf3.js";import{Ih as h,Jh as A,Ph as P,Qh as T,Sh as $,Th as U,Uh as G,Wh as L,Xh as M,Zh as O,_h as I}from"./chunk-33g68zy1.js";import{gi as d}from"./chunk-hkh2nsam.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{me as s}from"./chunk-x079eg84.js";import{Fe as o}from"./chunk-4yf7b4ev.js";import{$g as E,Pg as y,Qg as D,Sg as N,Ug as j,Vg as F,Xg as R,ah as _,bh as f,ch as C,eh as S,fh as m,jh as c,oh as l,ph as n}from"./chunk-e6adb7n8.js";import{qh as Y}from"./chunk-ne5w9ds8.js";import{sh as x,uh as k,xh as Z}from"./chunk-45a1tsk1.js";import{Eh as X}from"./chunk-1g5s5vf3.js";import{Ih as h,Jh as A,Ph as P,Qh as T,Sh as $,Th as U,Uh as G,Wh as L,Xh as M,Zh as O,_h as I}from"./chunk-33g68zy1.js";import{gi as d}from"./chunk-hkh2nsam.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
@@ -1 +1 @@
1
- import{Ab as f,Bb as g,Cb as h,Db as i,Eb as j,Fb as k,Mb as l,Nb as m,Ob as n,Pb as o,Rb as p,Sb as q,Tb as r,rb as a,sb as b,ub as c,yb as d,zb as e}from"./chunk-07hn8br0.js";import"./chunk-7avnhnjn.js";import"./chunk-azpkmttg.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-q8jfwyr4.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-51rayzy2.js";import"./chunk-ckqz2btx.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-kvw91990.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
1
+ import{Ab as f,Bb as g,Cb as h,Db as i,Eb as j,Fb as k,Mb as l,Nb as m,Ob as n,Pb as o,Rb as p,Sb as q,Tb as r,rb as a,sb as b,ub as c,yb as d,zb as e}from"./chunk-dst8h9c7.js";import"./chunk-7avnhnjn.js";import"./chunk-hdgee5xk.js";import"./chunk-xhhgpbzs.js";import"./chunk-r2nzt9jm.js";import"./chunk-3aejg2jy.js";import"./chunk-y7dtdwqx.js";import"./chunk-q8jfwyr4.js";import"./chunk-d83meq4k.js";import"./chunk-q15sm6vj.js";import"./chunk-5d1mmf11.js";import"./chunk-ckqz2btx.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-28pywda6.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +1 @@
1
- import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j,Oe as k,Pe as l,Qe as m,Re as n,Se as o,Te as p,Ue as q}from"./chunk-wyk6yc02.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-3dsggcwt.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-kvw91990.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{Ee as a,Fe as b,Ge as c,He as d,Ie as e,Je as f,Ke as g,Le as h,Me as i,Ne as j,Oe as k,Pe as l,Qe as m,Re as n,Se as o,Te as p,Ue as q}from"./chunk-4yf7b4ev.js";import"./chunk-v508x7cg.js";import"./chunk-3aejg2jy.js";import"./chunk-e6adb7n8.js";import"./chunk-ne5w9ds8.js";import"./chunk-45a1tsk1.js";import"./chunk-12e2yj9p.js";import"./chunk-1g5s5vf3.js";import"./chunk-33g68zy1.js";import"./chunk-hkh2nsam.js";import"./chunk-rxjyc6ff.js";import"./chunk-7a8j14gg.js";import"./chunk-28pywda6.js";import"./chunk-bvp5wpz8.js";import"./chunk-8mee32xq.js";import"./chunk-1mb2y0e0.js";import"./chunk-m5hnyxf3.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blade-code",
3
- "version": "0.10.87",
3
+ "version": "0.10.88",
4
4
  "private": false,
5
5
  "description": "🗡️ Blade Code - 智能代码助手命令行工具",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- import{he as a,ie as b}from"./chunk-pknksqe8.js";import"./chunk-kvw91990.js";import"./chunk-m5hnyxf3.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{h as a,i as b,j as c,k as d,l as e}from"./chunk-37x3xyqk.js";import"./chunk-kvw91990.js";import"./chunk-m5hnyxf3.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};