blade-code 0.10.166 → 0.10.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-6nd3vk8t.js → chunk-06p1xnh2.js} +1 -1
  3. package/dist/{chunk-dkqqzbx7.js → chunk-30yg6x35.js} +1 -1
  4. package/dist/{chunk-nyr7d91w.js → chunk-3b8hd8m3.js} +1 -1
  5. package/dist/{chunk-c0c5cs05.js → chunk-3kfa7jqj.js} +1 -1
  6. package/dist/{chunk-stnjkq5d.js → chunk-5vjg37rf.js} +1 -1
  7. package/dist/{chunk-xm3jf679.js → chunk-88fhmxky.js} +1 -1
  8. package/dist/{chunk-cvpztb8x.js → chunk-am85zf7r.js} +1 -1
  9. package/dist/{chunk-0m0dws6z.js → chunk-bk2mqcq6.js} +1 -1
  10. package/dist/{chunk-jqrnsx2r.js → chunk-cvr444pe.js} +1 -1
  11. package/dist/{chunk-m1sfdcf4.js → chunk-daj4efys.js} +1 -1
  12. package/dist/{chunk-1df3hhav.js → chunk-dw02rwxk.js} +2 -2
  13. package/dist/{chunk-8gdkw120.js → chunk-e3j64ysw.js} +1 -1
  14. package/dist/{chunk-cbck2j1y.js → chunk-gqe8tyzb.js} +1 -1
  15. package/dist/{chunk-md30ev61.js → chunk-hspgpbt5.js} +1 -1
  16. package/dist/{chunk-rvy5g0nh.js → chunk-jezvmhgp.js} +1 -1
  17. package/dist/{chunk-7wk76jf5.js → chunk-jmpcycaf.js} +1 -1
  18. package/dist/{chunk-8mf7z5yp.js → chunk-jntqevks.js} +4 -4
  19. package/dist/{chunk-3dr32kq0.js → chunk-jrsep7j2.js} +1 -1
  20. package/dist/chunk-k049bxtv.js +1 -0
  21. package/dist/chunk-k3t566kx.js +1 -0
  22. package/dist/{chunk-1enqexqe.js → chunk-mndzdq5c.js} +1 -1
  23. package/dist/{chunk-3p672np8.js → chunk-nbsvmqf9.js} +1 -1
  24. package/dist/{chunk-awq84da1.js → chunk-nhtq6gee.js} +1 -1
  25. package/dist/{chunk-ktwxgkht.js → chunk-nsdq8vwq.js} +1 -1
  26. package/dist/{chunk-7mkt0gzn.js → chunk-nwq0ttdc.js} +1 -1
  27. package/dist/{chunk-2q027yq5.js → chunk-p5233z7a.js} +1 -1
  28. package/dist/{chunk-qqte012h.js → chunk-pmsc4v5c.js} +1 -1
  29. package/dist/{chunk-7t2vwn4g.js → chunk-q06st5c8.js} +1 -1
  30. package/dist/{chunk-8dwg3pwe.js → chunk-rcq8vh21.js} +1 -1
  31. package/dist/{chunk-b23aa6zn.js → chunk-rtgbcq5r.js} +1 -1
  32. package/dist/{chunk-21sv4g1y.js → chunk-sgyyy9g7.js} +1 -1
  33. package/dist/{chunk-wxn3b653.js → chunk-sjcjdjae.js} +1 -1
  34. package/dist/{chunk-tjp34txf.js → chunk-smcwh4a3.js} +1 -1
  35. package/dist/{chunk-8mthb8hh.js → chunk-tws1c1q5.js} +1 -1
  36. package/dist/{chunk-fezkpken.js → chunk-v8dp0nme.js} +2 -2
  37. package/dist/{chunk-sv9p66tx.js → chunk-x9xm6by7.js} +1 -1
  38. package/dist/{chunk-xa3vgred.js → chunk-xzzbejay.js} +1 -1
  39. package/dist/{chunk-11d6vk8g.js → chunk-yw558b1h.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-a90fyv91.js +0 -1
  42. package/dist/chunk-k3bt41jn.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-7mkt0gzn.js";import{$a as HX,Sa as Y5,Va as pZ,Za as tZ,_a as UX,bb as rz,db as nz,eb as A9,wb as az}from"./chunk-30x3mcsb.js";import{Ab as c7,Bb as D2,Cb as BY,Db as x1,Eb as a7,Fb as KY,Gb as $Y,Hb as DY,Ib as qY,Jb as WQ,Lb as JX,Nb as W0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as AJ,Zb as R$,dc as aX,ec as G8,fc as sX,gc as ZX,ic as u1,jc as SX,oc as iY,rc as rY,xb as s5,yb as h7,zb as J1}from"./chunk-tjp34txf.js";import{$c as r8,$d as lY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as JY,Lc as YY,Mc as CX,Nc as X3,Nd as W8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as Jz,Yc as d2,Yd as VX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as fX,fd as d6,fe as PX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as MX,zc as r3}from"./chunk-2q027yq5.js";import{ie as l,je as BQ,ke as GQ,le as IJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as TX,Le as RX,Ue as ez,ff as $W,pe as oz,se as tz}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as cY,cg as B2}from"./chunk-nyr7d91w.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as pY,ng as dY,og as mX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as tX}from"./chunk-50vwafn5.js";import{Ag as bX,xg as LX,yg as OX,zg as NX}from"./chunk-7wk76jf5.js";import{$g as AX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as W2,Og as H8,Pg as l1,Qg as i1,Rg as EX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as kX}from"./chunk-11d6vk8g.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as z2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as _z,th as jX,uh as z8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-stnjkq5d.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as PY,Di as SY,Ei as kY,Fh as XJ,Fi as vY,Gi as AZ,Hi as yY,Ii as B1,Ji as xY,Kh as zJ,Ki as IY,Li as hY,Mh as D9,Ni as t3,Pi as yX,Qi as _X,Rh as Wz,Ri as B0,Vh as WJ,Xh as qX,Zh as UY,_h as HY,pi as h1,si as e7}from"./chunk-sv9p66tx.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as eQ,Yi as $X}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as wX,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as Oz,Tj as wz}from"./chunk-4cdk4mds.js";import{Xj as Ez}from"./chunk-md30ev61.js";import{bk as vX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as t7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=String.raw`
1
+ import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-nwq0ttdc.js";import{$a as HX,Sa as Y5,Va as pZ,Za as tZ,_a as UX,bb as rz,db as nz,eb as A9,wb as az}from"./chunk-30x3mcsb.js";import{Ab as c7,Bb as D2,Cb as BY,Db as x1,Eb as a7,Fb as KY,Gb as $Y,Hb as DY,Ib as qY,Jb as WQ,Lb as JX,Nb as W0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as AJ,Zb as R$,dc as aX,ec as G8,fc as sX,gc as ZX,ic as u1,jc as SX,oc as iY,rc as rY,xb as s5,yb as h7,zb as J1}from"./chunk-smcwh4a3.js";import{$c as r8,$d as lY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as JY,Lc as YY,Mc as CX,Nc as X3,Nd as W8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as Jz,Yc as d2,Yd as VX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as fX,fd as d6,fe as PX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as MX,zc as r3}from"./chunk-p5233z7a.js";import{ie as l,je as BQ,ke as GQ,le as IJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as TX,Le as RX,Ue as ez,ff as $W,pe as oz,se as tz}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as cY,cg as B2}from"./chunk-3b8hd8m3.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as pY,ng as dY,og as mX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as tX}from"./chunk-50vwafn5.js";import{Ag as bX,xg as LX,yg as OX,zg as NX}from"./chunk-jmpcycaf.js";import{$g as AX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as W2,Og as H8,Pg as l1,Qg as i1,Rg as EX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as kX}from"./chunk-yw558b1h.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as z2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as _z,th as jX,uh as z8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-5vjg37rf.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as PY,Di as SY,Ei as kY,Fh as XJ,Fi as vY,Gi as AZ,Hi as yY,Ii as B1,Ji as xY,Kh as zJ,Ki as IY,Li as hY,Mh as D9,Ni as t3,Pi as yX,Qi as _X,Rh as Wz,Ri as B0,Vh as WJ,Xh as qX,Zh as UY,_h as HY,pi as h1,si as e7}from"./chunk-x9xm6by7.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as eQ,Yi as $X}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as wX,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as Oz,Tj as wz}from"./chunk-4cdk4mds.js";import{Xj as Ez}from"./chunk-hspgpbt5.js";import{bk as vX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as t7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=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);
@@ -859,7 +859,7 @@ ${A0}
859
859
  </approved-plan>
860
860
 
861
861
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}v=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return v;let p=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,...k?{goalId:k.goalId,objective:k.objective,turnId:I.id}:{},executionHostFailureCategory:v.metadata?.executionHostFailureCategory,prematureStopPattern:v.success?VY(v.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!v.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(v.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=v.success&&!b.signal?.aborted&&h<20,p0=XG(v)||!v.success&&v.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:v.success&&!b.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!v.success||b.signal?.aborted)return v;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return v;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,duration:v.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return v;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.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 _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
862
- `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-6nd3vk8t.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,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($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(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,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.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);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.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 X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
862
+ `),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-06p1xnh2.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,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($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(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,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.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);a.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);a.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){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.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)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.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 X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.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(`
863
863
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.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 a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];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}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,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+=`
864
864
 
865
865
  <system-reminder>
@@ -1108,7 +1108,7 @@ ${U}
1108
1108
  `+` /model add
1109
1109
 
1110
1110
  `+`或运行初始化向导:
1111
- `+" /init");if(!G&&Q&&Q!=="inherit"&&!b.some((A)=>A.id===Q))Q=void 0;let M=await z4({workspaceRoot:F,...w?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:_.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...O.config,permissionMode:X??O.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:w?structuredClone(O.config.permissions):await L.loadWorkspacePermissions(F,O.config.permissions),hooks:w?{enabled:!1}:await L.loadWorkspaceHooks(F,O.config.hooks??{})};L.validateConfig(E,O.catalog);let j=new q1(E,{...$,modelResources:O,lspResources:N,mcpServers:M,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:z,serviceTier:W,responseVerbosity:V,communicationStyle:U,...H?{communicationStyleDigest:H}:{},...B?{projectInstructionsDigest:B}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(w){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(w instanceof m4)){let q=J?await C$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await q1.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",q??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((_)=>{if(_.code!=="ENOENT")E0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,_)})}throw w}}static async hasPendingInbox($,Z,J=v$($)){if(await T1(J,Z,async({inboxPath:X})=>{try{return(await BX(X)).size>0}catch(z){if(z.code!=="ENOENT")throw z;return!1}}))return!0;if(J.kind==="acp-remote")return!1;if(j0()?.agentTeamsEnabled!==!0)return!1;let Q=(await B$.getInstance(t()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===Z&&X.workspaceRoot===$);for(let X of Q)if((await new H$(X.name,t()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,Z,J=v$($)){return T1(J,Z,async({inboxPath:Y})=>{try{return await BX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,Z,J=v$($)){return V0.hasActiveGoal($,Z,J)}static async hasRecoverableTurn($,Z,J=v$($)){return new _2($,100,void 0,J).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??C()}get executionRoot(){return this.workspace.executionRoot}get resourceRoot(){return this.workspace.resourceRoot}isRemoteWorkspace(){return this.workspace.kind==="acp-remote"}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return V2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=g1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Q.taskStatus,...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:g1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=g1.getStats();W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}beginProviderRecovery(){let $=this.providerRecovery.begin();return this.providerRecoveryGeneration=$,this.publishProviderRecovery(this.providerRecovery.snapshot()),$}observeProviderRecovery($,Z){let J=this.providerRecovery.observe($,Z);if(J)this.publishProviderRecovery(J);return J}clearProviderRecovery($){let Z=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(Z)this.publishProviderRecovery(Z);return Z}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,Z){let J=this.turnActivity.observe($,Z);if(J)this.publishTurnActivity(J);return J}clearTurnActivity($){let Z=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(Z)this.publishTurnActivity(Z);return Z}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"turn.activity",{activity:$})}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return this.workspace.kind==="acp-remote"?s.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):s.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(J.signal);let[z,W]=await Promise.all([this.loadModelContext(),Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:this.executionRoot},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot}})]);if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let V=SX(W.prompt,X);if(!V)throw Error("Side conversation system prompt is empty");return await MJ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:V,messages:z,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return E3(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0,await this.activeTurnMailbox?.setRecoveryProtectedIds([])}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((z)=>z.role==="assistant"&&DX(z)?.turnId===$.turnId&&JSON.stringify(DX(z))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,X=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...X?{structuredOutput:X}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new f("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return z8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return z8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??jX}getProjectRuleCatalog(){return this.agentResources?.projectRules??EX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let U of V?.getAffectedPaths()??[])if(U)Q.add(U)}catch{}let X=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(z?.affected_paths))for(let V of z.affected_paths)X(V);if(Array.isArray(z?.changes)){for(let V of z.changes)if(V&&typeof V==="object")X(V.path)}let W=[...Q].map((V)=>F0.isAbsolute(V)?F0.resolve(V):F0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let U=F0.relative(this.workspaceRoot,V);if(U===""||!U.startsWith("..")&&!F0.isAbsolute(U))return[F0.resolve(this.projectRoot,U)];let H=F0.relative(this.projectRoot,V);return H===""||!H.startsWith("..")&&!F0.isAbsolute(H)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await o6($,{configDir:t(),stateStorage:this.stateStorage}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:y3($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){E0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${X instanceof Error?X.message:String(X)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await C$.getChangeSummary(this.sessionId):void 0;return q1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,Z,J,Y,Q,X){let z=new Date().toISOString(),W=J==="failed"&&Y!==void 0?W8(Y):void 0,V=W?.message??(typeof Y==="string"?Y.slice(0,500):void 0),U={taskStatus:J,taskStatusReason:V??null,taskFailure:W??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:z,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:z,taskOwnerPid:null}},H=X?await s.updateRemoteSessionMetadata($,Z,X,U):await s.updateSessionMetadata($,Z,U);return W0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:H.taskStatus,...V?{taskStatusReason:V}:{},...W?{taskFailure:W}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskCompletedAt?{taskCompletedAt:H.taskCompletedAt}:{},...H.taskDiffStat?{taskDiffStat:H.taskDiffStat}:{},...H.taskQueuePosition?{taskQueuePosition:H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{taskQueueDepth:H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:H.taskConcurrencyLimit}:{},updatedAt:H.lastMessageTime}),H}createGoal($,Z){return this.goalStore.create($,Z)}async beginGoalTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.beginTurn(),Y=await this.goalStore.prepareTurnBinding(J.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await Z.finishTurn(J).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(J,"goal",[],{goalId:Y.goalId,...Y.lineage}),Q=!0;let X=await this.goalStore.commitTurnBinding(Y);if(!X)throw Error("Goal changed before turn lineage commit");return{handle:J,goal:X}}catch(X){throw await this.releaseFailedTurnStart(J,Q),X}}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),s.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await s.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return $$.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return $$.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=D0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let z=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!z)throw Error(`Subagent cannot be resumed: ${Y.id}`);let W=Z.getAgent(z.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${z.agentId}`);return{source:z.source,session:W}}async beginTurn($="goal"){let Z=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,Z?.metadata),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await J.reservedMessageIds(Q.handle),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before user turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q.handle,X),z}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},...Z.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let z=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},z),await this.getActiveTurnMailbox().acknowledge(z)}else{let z=this.startupTurnRecovery,W=Z.preserveStartupRecovery&&z?.outcome==="aborted"?{hadSuccessfulToolResult:z.hadSuccessfulToolResult,interruptedToolCallCount:z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:z.allSuccessfulToolResultsSafeForResume,correctionSpent:z.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),V=await this.getActiveTurnMailbox().claimedMessageIds($),U=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:3,inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:W.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:V}:void 0);if(this.startupTurnRecovery=U.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(U.recovery?.inputMessageIds??[]),Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(U.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before pending turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q,X),z}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;let J=!1;try{let Y=await this.goalStore.prepareTurnBinding(Z.id,!1);if(await this.saveTurnStart(Z,"pending",await $.reservedMessageIds(Z),Y?{goalId:Y.goalId,...Y.lineage}:void 0),J=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return Z}catch(Y){throw await this.releaseFailedTurnStart(Z,J),Y}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}async getFollowUpQueueSnapshot(){return this.getActiveTurnMailbox().getFollowUpQueueSnapshot()}async mutateFollowUpQueue($){return this.getActiveTurnMailbox().mutateFollowUpQueue($)}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(!this.isRemoteWorkspace()&&Y0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!$$.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await iZ.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.reconcileBackgroundSubagentCompletions(),this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=y0.getInstance().listSessions().filter((J)=>t0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await iZ.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=y0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((z)=>Boolean(z)):J.listSessions().filter((z)=>t0(z,Y)),X=0;for(let z of Q){if(!this.backgroundTaskChildIds.has(z.id)||this.backgroundTaskCompletionSettledIds.has(z.id)||z.status==="running")continue;let W=z.resumedFrom?J.loadSession(z.resumedFrom):void 0,V=lQ(z,Y,W);if(!V){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let U=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!U.eligible||U.acknowledged){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let H=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!H.accepted){E0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${z.id}`);continue}if(H.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);if(this.backgroundTaskCompletionSettledIds.add(z.id),H.duplicate)continue;if(X++,H.queue)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:H.queue});W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:z.id,inboxMessageId:V.inboxMessageId,status:z.status,type:z.subagentType,description:z.description,summary:V.subagentRef.subagentSummary,resumedFrom:z.resumedFrom,rootAgentId:z.rootAgentId,resumeDepth:z.resumeDepth,verificationVerdict:z.result?.verificationVerdict,queued:H.queued,delivery:H.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[])}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await B$.getInstance(t()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new H$(Z.name,t()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(N2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:Z8(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=mD(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,X=async(G)=>{let D=G.type==="started"?{executionId:G.executionId,command:G.command,auxiliary:Y}:G.type==="output"?{executionId:G.executionId,stream:G.stream,chunk:G.chunk,streamedBytes:G.streamedBytes,streamTruncated:G.streamTruncated,auxiliary:Y}:{executionId:G.executionId,messageId:G.messageId,record:G.record,auxiliary:Y,delivery:G.delivery,queued:G.queued};W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${G.type}`,D),await Z.onEvent?.(G)},z=await TX($,{executionId:J,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??$9():$9():this.options.userShellExecutor,onEvent:async(G)=>{if(G.type!=="completed")await X({...G,auxiliary:Y})}}),W=RX(z),U=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(z))},this.options.subagentInfo),H=Y?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0,origin:"user_shell"}):void 0;if(H?.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);let B={executionId:J,messageId:U,record:z,modelContent:W,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{},...H?.queue?{queue:H.queue}:{}};return await X({type:"completed",executionId:J,messageId:U,record:z,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await c4.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new b1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await vJ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await cD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let W=x0.getInstance();if(W.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),W.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)W.inheritProjectConfig(this.projectRoot,this.workspaceRoot);W.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??W.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??W.getConfig(this.projectRoot));let V=await W.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!V.proceed)throw Error(V.warning||"SessionStart hook blocked initialization");if(V.warning)E0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${V.warning}`);let U=_X(V.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...U}),this.config.env=this.sessionEnvironment,W.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new e8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new cZ({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let $=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await $.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Z=await $.loadInterruptedToolCalls(this.sessionId),J=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let W=y0.getInstance();for(let V of Z){if(V.toolName!=="Task"||!V.input||typeof V.input!=="object"||Array.isArray(V.input))continue;let U=V.input.subagent_session_id;if(typeof U!=="string")continue;let H=W.loadSession(U);if(!H)continue;let B=HQ(V,H,Y);if(B)J.set(V.toolCallId,B)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:J});if(Q)this.startupAdoptedToolResults=Z.flatMap((W)=>{let V=J.get(W.toolCallId);return V?[{call:W,result:V}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),z=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(z?.finalized)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:z.goal});if(this.startupTurnRecovery=Q??(X&&z?.finalized?{turnId:X.turnId,outcome:"completed",inputMessageIds:X.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:X.finalization}:void 0),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[]),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(!this.isRemoteWorkspace())await this.recoverTeamLeadMessages(),await this.attachBackgroundSubagentCompletionDispatcher();if(Q)E0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,E0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,z=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(z8(W,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||z!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,z);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=z,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new H1;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((B)=>B!==J),X=Y?new Set(Y):null,z=Q?new Set(Q):null;for(let B of this.baseRegistry.getBuiltinTools()){if(z?.has(B.name))continue;if(!X||X.has(B.name))Z.register(B)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,z));let W=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((B)=>!z?.has(B)&&(!X||X.has(B))))for(let B of $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:G,...D}=B;Z.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(Z,{allowed:X,blocked:z});let U={...this.config.permissions,...$.permissions},H=$.permissionMode??this.config.permissionMode??"default";return new z6(Z,{permissionConfig:U,permissionMode:H,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,workspaceToolPolicy:this.workspaceToolPolicy,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,executionRoot:this.executionRoot,workspaceKind:this.workspace.kind,environment:this.sessionEnvironment,permissionMode:H,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(B)=>this.notifyBackgroundSubagentCompleted(B),registerBackgroundSubagent:(B)=>this.registerBackgroundSubagent(B)},...this.lspManager?{lspManager:this.lspManager}:{},...H==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,Z=async(_,L)=>{try{await L()}catch(F){$??=F,E0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${_} during cleanup`,F)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,z=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,V=this.mcpLogListener,U=this.mcpInstructionsListener,H=this.mcpTaskListener,B=this.sessionLease,G=this.autoVerifyRuntime,D=this.lspManager,w=this.browserRuntime,q=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>w?.dispose()),await Z("dispose the background subagent completion registration",()=>q?.dispose()),this.backgroundSubagentCompletionRegistration=void 0,this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new H1,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,!this.isRemoteWorkspace())await Z("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>G?.dispose()),await Z("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await Z("release the session hook model resources",()=>x0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>C$.releaseSession(this.sessionId));if(await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>$$.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&z)Y.off("resourceUpdated",z);if(Y&&W)Y.off("connectionLifecycleChanged",W);if(Y&&V)Y.off("log",V);if(Y&&U)Y.off("instructionsChanged",U);if(H)$$.getInstance().off("taskChanged",H);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,Z){if(Z)try{await this.finishTurn($,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}});return}catch{}await this.getActiveTurnMailbox().finishTurn($).catch(()=>{return})}assertRewindIdle(){if(this.isRemoteWorkspace())throw Error("Rewind is unavailable for ACP remote workspaces");if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Y0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let X=m0($,this.config,J,this.modelResources.catalog,Y,Q);E0.debug(`${Z} ${X.displayName} (${$.model})`);let z=X.model.contextWindow,W=await S4(X.chat),V=this.initialized?this.chatService:void 0,U=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new V6(W,U,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=z,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let H=V;try{await H?.dispose?.()}catch(B){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(!this.options.auxiliaryReadOnly&&this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&!this.options.auxiliaryReadOnly&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot},environmentOptions:{...u1,workingDirectory:this.executionRoot}})}catch(J){E0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof fX||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await s.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new n8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposeArtifactPaths:!U0(this.sessionId)});let $=await v4({sessionId:this.sessionId,configDir:t(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,stateStorage:this.stateStorage,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime}),Z=iJ($.filter((J)=>!J.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=e0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new o2(`${this.stateStorage.kind==="acp-remote"?this.workspaceRoot:this.projectRoot}\x00${this.sessionId}`,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(U)=>{this.applyMcpCatalog(U,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(U)=>{this.applyMcpContentCatalog(U)},Q=(U)=>{this.applyMcpResourceUpdated(U)},X=(U)=>{this.applyMcpConnectionChange(U)},z=(U)=>{this.applyMcpLog(U)},W=(U)=>{this.applyMcpInstructions(U)},V=(U)=>{if(U.owner.sessionId!==this.sessionId||F0.resolve(U.owner.projectPath)!==F0.resolve(this.workspaceRoot))return;this.applyMcpTask(U);let{owner:H,result:B,...G}=U;W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",G)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=z,this.mcpInstructionsListener=W,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",X),Z.on("log",z),Z.on("instructionsChanged",W),$$.getInstance().on("taskChanged",V);for(let[U,H]of Object.entries($))try{let B=H.type==="stdio"?{...this.sessionEnvironment,...H.env}:void 0;await Z.registerServer(U,H.type==="stdio"?{...H,...B&&Object.keys(B).length>0?{env:B}:{}}:H)}catch(B){E0.warn(`Warning: MCP server "${U}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Y6(Z)),this.baseRegistry.registerAll(KZ(Z))}catch($){E0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),z={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},W=z.added.length>0||z.removed.length>0||z.updated.length>0;J.replaceMcpTools(Q,Z&&W?z:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!X.blocked?.has(W)&&(!X.allowed||X.allowed.has(W))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return qX(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?AX(this.resourceRoot):await c0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function Z9(){let $=await B0.getInstance().reload();q0().config.actions.setConfig($),await e0.getInstance().disconnectAll(),kX(),await c0(C())}import KF from"fuse.js";import c$ from"node:path";import{Mutex as pD}from"async-mutex";var p$=new pD;async function xX($){let Z=$.getWorkspaceRoot();await f$(Z,async(J)=>{await $.reapplyEnabledSettings(),i1(Z),await l1(Z),await J9(J)})}async function lD($){let Z=$.getWorkspaceRoot();return f$(Z,async(J)=>{i1(Z);let Y=await $.refresh();return await l1(Z),await J9(J),Y})}async function Y9($){return f$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...W2.getInitializedInstances()])),Y;for(let Q of J){let X=await lD(Q);if(Q===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function iD($,Z){let J=c$.resolve($),Y=h1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function rD($){return c$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function IX($,Z){if(rD(Z)&&!vX(await a0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function V8($,Z,J,Y="local"){return p$.runExclusive(async()=>{let Q=c$.resolve($);return f$(Q,async(X)=>{let z=X.plugins.get(Z);if(!z)throw Error(`Plugin not found: ${Z}`);if(z.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await h1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let W=Y==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let H of W)await xX(H);let V=X.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let U=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:U.settings[Z]?.effectiveScope??"default"}})})}async function U8($){return p$.runExclusive(()=>f$($,async(Z)=>{i1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function Q9($,Z,J="global"){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q={...Z,...yX(Z)};return await h1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),f$(Y,async(X)=>{let z=J==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let W of z)await xX(W);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function X9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function z9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function W9($,Z,J=!1){return p$.runExclusive(async()=>{let Y=c$.resolve($);return f$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let z=await G$().uninstall(Z,J);if(!z.success)return{result:z};await iD(Y,Z);let W=await Y9(Y);return{result:z,discovery:W}})})}async function V9($,Z,J){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return G$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function U9($,Z){return p$.runExclusive(async()=>{let J=c$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(J);return G$().refreshMarketplace(Z,Y)})}async function H9($,Z=!1){return p$.runExclusive(()=>G$().removeMarketplace($,Z))}var nD={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
1111
+ `+" /init");if(!G&&Q&&Q!=="inherit"&&!b.some((A)=>A.id===Q))Q=void 0;let M=await z4({workspaceRoot:F,...w?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:_.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...O.config,permissionMode:X??O.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:w?structuredClone(O.config.permissions):await L.loadWorkspacePermissions(F,O.config.permissions),hooks:w?{enabled:!1}:await L.loadWorkspaceHooks(F,O.config.hooks??{})};L.validateConfig(E,O.catalog);let j=new q1(E,{...$,modelResources:O,lspResources:N,mcpServers:M,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:z,serviceTier:W,responseVerbosity:V,communicationStyle:U,...H?{communicationStyleDigest:H}:{},...B?{projectInstructionsDigest:B}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(w){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(w instanceof m4)){let q=J?await C$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await q1.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",q??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((_)=>{if(_.code!=="ENOENT")E0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,_)})}throw w}}static async hasPendingInbox($,Z,J=v$($)){if(await T1(J,Z,async({inboxPath:X})=>{try{return(await BX(X)).size>0}catch(z){if(z.code!=="ENOENT")throw z;return!1}}))return!0;if(J.kind==="acp-remote")return!1;if(j0()?.agentTeamsEnabled!==!0)return!1;let Q=(await B$.getInstance(t()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===Z&&X.workspaceRoot===$);for(let X of Q)if((await new H$(X.name,t()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,Z,J=v$($)){return T1(J,Z,async({inboxPath:Y})=>{try{return await BX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,Z,J=v$($)){return V0.hasActiveGoal($,Z,J)}static async hasRecoverableTurn($,Z,J=v$($)){return new _2($,100,void 0,J).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??C()}get executionRoot(){return this.workspace.executionRoot}get resourceRoot(){return this.workspace.resourceRoot}isRemoteWorkspace(){return this.workspace.kind==="acp-remote"}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return V2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=g1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Q.taskStatus,...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:g1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=g1.getStats();W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}beginProviderRecovery(){let $=this.providerRecovery.begin();return this.providerRecoveryGeneration=$,this.publishProviderRecovery(this.providerRecovery.snapshot()),$}observeProviderRecovery($,Z){let J=this.providerRecovery.observe($,Z);if(J)this.publishProviderRecovery(J);return J}clearProviderRecovery($){let Z=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(Z)this.publishProviderRecovery(Z);return Z}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,Z){let J=this.turnActivity.observe($,Z);if(J)this.publishTurnActivity(J);return J}clearTurnActivity($){let Z=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(Z)this.publishTurnActivity(Z);return Z}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"turn.activity",{activity:$})}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return this.workspace.kind==="acp-remote"?s.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):s.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(J.signal);let z=[this.loadModelContext(),Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:this.executionRoot},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot}})],[W,V]=await Promise.all(z).catch(async(H)=>{throw await Promise.allSettled(z),H});if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let U=SX(V.prompt,X);if(!U)throw Error("Side conversation system prompt is empty");return await MJ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:U,messages:W,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return E3(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0,await this.activeTurnMailbox?.setRecoveryProtectedIds([])}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((z)=>z.role==="assistant"&&DX(z)?.turnId===$.turnId&&JSON.stringify(DX(z))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,X=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...X?{structuredOutput:X}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new f("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return z8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return z8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??jX}getProjectRuleCatalog(){return this.agentResources?.projectRules??EX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let U of V?.getAffectedPaths()??[])if(U)Q.add(U)}catch{}let X=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(z?.affected_paths))for(let V of z.affected_paths)X(V);if(Array.isArray(z?.changes)){for(let V of z.changes)if(V&&typeof V==="object")X(V.path)}let W=[...Q].map((V)=>F0.isAbsolute(V)?F0.resolve(V):F0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let U=F0.relative(this.workspaceRoot,V);if(U===""||!U.startsWith("..")&&!F0.isAbsolute(U))return[F0.resolve(this.projectRoot,U)];let H=F0.relative(this.projectRoot,V);return H===""||!H.startsWith("..")&&!F0.isAbsolute(H)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await o6($,{configDir:t(),stateStorage:this.stateStorage}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:y3($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){E0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${X instanceof Error?X.message:String(X)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await C$.getChangeSummary(this.sessionId):void 0;return q1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,Z,J,Y,Q,X){let z=new Date().toISOString(),W=J==="failed"&&Y!==void 0?W8(Y):void 0,V=W?.message??(typeof Y==="string"?Y.slice(0,500):void 0),U={taskStatus:J,taskStatusReason:V??null,taskFailure:W??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:z,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:z,taskOwnerPid:null}},H=X?await s.updateRemoteSessionMetadata($,Z,X,U):await s.updateSessionMetadata($,Z,U);return W0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:H.taskStatus,...V?{taskStatusReason:V}:{},...W?{taskFailure:W}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskCompletedAt?{taskCompletedAt:H.taskCompletedAt}:{},...H.taskDiffStat?{taskDiffStat:H.taskDiffStat}:{},...H.taskQueuePosition?{taskQueuePosition:H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{taskQueueDepth:H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:H.taskConcurrencyLimit}:{},updatedAt:H.lastMessageTime}),H}createGoal($,Z){return this.goalStore.create($,Z)}async beginGoalTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.beginTurn(),Y=await this.goalStore.prepareTurnBinding(J.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await Z.finishTurn(J).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(J,"goal",[],{goalId:Y.goalId,...Y.lineage}),Q=!0;let X=await this.goalStore.commitTurnBinding(Y);if(!X)throw Error("Goal changed before turn lineage commit");return{handle:J,goal:X}}catch(X){throw await this.releaseFailedTurnStart(J,Q),X}}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),s.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await s.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return $$.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return $$.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=D0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let z=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!z)throw Error(`Subagent cannot be resumed: ${Y.id}`);let W=Z.getAgent(z.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${z.agentId}`);return{source:z.source,session:W}}async beginTurn($="goal"){let Z=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,Z?.metadata),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await J.reservedMessageIds(Q.handle),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before user turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q.handle,X),z}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},...Z.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let z=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},z),await this.getActiveTurnMailbox().acknowledge(z)}else{let z=this.startupTurnRecovery,W=Z.preserveStartupRecovery&&z?.outcome==="aborted"?{hadSuccessfulToolResult:z.hadSuccessfulToolResult,interruptedToolCallCount:z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:z.allSuccessfulToolResultsSafeForResume,correctionSpent:z.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),V=await this.getActiveTurnMailbox().claimedMessageIds($),U=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:3,inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:W.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:V}:void 0);if(this.startupTurnRecovery=U.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(U.recovery?.inputMessageIds??[]),Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(U.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before pending turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q,X),z}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;let J=!1;try{let Y=await this.goalStore.prepareTurnBinding(Z.id,!1);if(await this.saveTurnStart(Z,"pending",await $.reservedMessageIds(Z),Y?{goalId:Y.goalId,...Y.lineage}:void 0),J=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return Z}catch(Y){throw await this.releaseFailedTurnStart(Z,J),Y}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}async getFollowUpQueueSnapshot(){return this.getActiveTurnMailbox().getFollowUpQueueSnapshot()}async mutateFollowUpQueue($){return this.getActiveTurnMailbox().mutateFollowUpQueue($)}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(!this.isRemoteWorkspace()&&Y0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!$$.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await iZ.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.reconcileBackgroundSubagentCompletions(),this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=y0.getInstance().listSessions().filter((J)=>t0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await iZ.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=y0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((z)=>Boolean(z)):J.listSessions().filter((z)=>t0(z,Y)),X=0;for(let z of Q){if(!this.backgroundTaskChildIds.has(z.id)||this.backgroundTaskCompletionSettledIds.has(z.id)||z.status==="running")continue;let W=z.resumedFrom?J.loadSession(z.resumedFrom):void 0,V=lQ(z,Y,W);if(!V){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let U=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!U.eligible||U.acknowledged){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let H=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!H.accepted){E0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${z.id}`);continue}if(H.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);if(this.backgroundTaskCompletionSettledIds.add(z.id),H.duplicate)continue;if(X++,H.queue)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:H.queue});W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:z.id,inboxMessageId:V.inboxMessageId,status:z.status,type:z.subagentType,description:z.description,summary:V.subagentRef.subagentSummary,resumedFrom:z.resumedFrom,rootAgentId:z.rootAgentId,resumeDepth:z.resumeDepth,verificationVerdict:z.result?.verificationVerdict,queued:H.queued,delivery:H.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[])}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await B$.getInstance(t()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new H$(Z.name,t()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(N2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:Z8(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=mD(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,X=async(G)=>{let D=G.type==="started"?{executionId:G.executionId,command:G.command,auxiliary:Y}:G.type==="output"?{executionId:G.executionId,stream:G.stream,chunk:G.chunk,streamedBytes:G.streamedBytes,streamTruncated:G.streamTruncated,auxiliary:Y}:{executionId:G.executionId,messageId:G.messageId,record:G.record,auxiliary:Y,delivery:G.delivery,queued:G.queued};W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${G.type}`,D),await Z.onEvent?.(G)},z=await TX($,{executionId:J,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??$9():$9():this.options.userShellExecutor,onEvent:async(G)=>{if(G.type!=="completed")await X({...G,auxiliary:Y})}}),W=RX(z),U=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(z))},this.options.subagentInfo),H=Y?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0,origin:"user_shell"}):void 0;if(H?.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);let B={executionId:J,messageId:U,record:z,modelContent:W,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{},...H?.queue?{queue:H.queue}:{}};return await X({type:"completed",executionId:J,messageId:U,record:z,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await c4.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new b1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await vJ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await cD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let W=x0.getInstance();if(W.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),W.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)W.inheritProjectConfig(this.projectRoot,this.workspaceRoot);W.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??W.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??W.getConfig(this.projectRoot));let V=await W.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!V.proceed)throw Error(V.warning||"SessionStart hook blocked initialization");if(V.warning)E0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${V.warning}`);let U=_X(V.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...U}),this.config.env=this.sessionEnvironment,W.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new e8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new cZ({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let $=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await $.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Z=await $.loadInterruptedToolCalls(this.sessionId),J=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let W=y0.getInstance();for(let V of Z){if(V.toolName!=="Task"||!V.input||typeof V.input!=="object"||Array.isArray(V.input))continue;let U=V.input.subagent_session_id;if(typeof U!=="string")continue;let H=W.loadSession(U);if(!H)continue;let B=HQ(V,H,Y);if(B)J.set(V.toolCallId,B)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:J});if(Q)this.startupAdoptedToolResults=Z.flatMap((W)=>{let V=J.get(W.toolCallId);return V?[{call:W,result:V}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),z=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(z?.finalized)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:z.goal});if(this.startupTurnRecovery=Q??(X&&z?.finalized?{turnId:X.turnId,outcome:"completed",inputMessageIds:X.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:X.finalization}:void 0),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[]),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(!this.isRemoteWorkspace())await this.recoverTeamLeadMessages(),await this.attachBackgroundSubagentCompletionDispatcher();if(Q)E0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,E0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,z=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(z8(W,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||z!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,z);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=z,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new H1;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((B)=>B!==J),X=Y?new Set(Y):null,z=Q?new Set(Q):null;for(let B of this.baseRegistry.getBuiltinTools()){if(z?.has(B.name))continue;if(!X||X.has(B.name))Z.register(B)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,z));let W=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((B)=>!z?.has(B)&&(!X||X.has(B))))for(let B of $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:G,...D}=B;Z.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(Z,{allowed:X,blocked:z});let U={...this.config.permissions,...$.permissions},H=$.permissionMode??this.config.permissionMode??"default";return new z6(Z,{permissionConfig:U,permissionMode:H,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,workspaceToolPolicy:this.workspaceToolPolicy,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,executionRoot:this.executionRoot,workspaceKind:this.workspace.kind,environment:this.sessionEnvironment,permissionMode:H,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(B)=>this.notifyBackgroundSubagentCompleted(B),registerBackgroundSubagent:(B)=>this.registerBackgroundSubagent(B)},...this.lspManager?{lspManager:this.lspManager}:{},...H==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,Z=async(_,L)=>{try{await L()}catch(F){$??=F,E0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${_} during cleanup`,F)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,z=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,V=this.mcpLogListener,U=this.mcpInstructionsListener,H=this.mcpTaskListener,B=this.sessionLease,G=this.autoVerifyRuntime,D=this.lspManager,w=this.browserRuntime,q=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>w?.dispose()),await Z("dispose the background subagent completion registration",()=>q?.dispose()),this.backgroundSubagentCompletionRegistration=void 0,this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new H1,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,!this.isRemoteWorkspace())await Z("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>G?.dispose()),await Z("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await Z("release the session hook model resources",()=>x0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>C$.releaseSession(this.sessionId));if(await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>$$.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&z)Y.off("resourceUpdated",z);if(Y&&W)Y.off("connectionLifecycleChanged",W);if(Y&&V)Y.off("log",V);if(Y&&U)Y.off("instructionsChanged",U);if(H)$$.getInstance().off("taskChanged",H);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,Z){if(Z)try{await this.finishTurn($,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}});return}catch{}await this.getActiveTurnMailbox().finishTurn($).catch(()=>{return})}assertRewindIdle(){if(this.isRemoteWorkspace())throw Error("Rewind is unavailable for ACP remote workspaces");if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Y0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let X=m0($,this.config,J,this.modelResources.catalog,Y,Q);E0.debug(`${Z} ${X.displayName} (${$.model})`);let z=X.model.contextWindow,W=await S4(X.chat),V=this.initialized?this.chatService:void 0,U=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new V6(W,U,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=z,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let H=V;try{await H?.dispose?.()}catch(B){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(!this.options.auxiliaryReadOnly&&this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&!this.options.auxiliaryReadOnly&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot},environmentOptions:{...u1,workingDirectory:this.executionRoot}})}catch(J){E0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof fX||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await s.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new n8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposeArtifactPaths:!U0(this.sessionId)});let $=await v4({sessionId:this.sessionId,configDir:t(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,stateStorage:this.stateStorage,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime}),Z=iJ($.filter((J)=>!J.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=e0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new o2(`${this.stateStorage.kind==="acp-remote"?this.workspaceRoot:this.projectRoot}\x00${this.sessionId}`,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(U)=>{this.applyMcpCatalog(U,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(U)=>{this.applyMcpContentCatalog(U)},Q=(U)=>{this.applyMcpResourceUpdated(U)},X=(U)=>{this.applyMcpConnectionChange(U)},z=(U)=>{this.applyMcpLog(U)},W=(U)=>{this.applyMcpInstructions(U)},V=(U)=>{if(U.owner.sessionId!==this.sessionId||F0.resolve(U.owner.projectPath)!==F0.resolve(this.workspaceRoot))return;this.applyMcpTask(U);let{owner:H,result:B,...G}=U;W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",G)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=z,this.mcpInstructionsListener=W,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",X),Z.on("log",z),Z.on("instructionsChanged",W),$$.getInstance().on("taskChanged",V);for(let[U,H]of Object.entries($))try{let B=H.type==="stdio"?{...this.sessionEnvironment,...H.env}:void 0;await Z.registerServer(U,H.type==="stdio"?{...H,...B&&Object.keys(B).length>0?{env:B}:{}}:H)}catch(B){E0.warn(`Warning: MCP server "${U}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Y6(Z)),this.baseRegistry.registerAll(KZ(Z))}catch($){E0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),z={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},W=z.added.length>0||z.removed.length>0||z.updated.length>0;J.replaceMcpTools(Q,Z&&W?z:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!X.blocked?.has(W)&&(!X.allowed||X.allowed.has(W))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return qX(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?AX(this.resourceRoot):await c0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function Z9(){let $=await B0.getInstance().reload();q0().config.actions.setConfig($),await e0.getInstance().disconnectAll(),kX(),await c0(C())}import KF from"fuse.js";import c$ from"node:path";import{Mutex as pD}from"async-mutex";var p$=new pD;async function xX($){let Z=$.getWorkspaceRoot();await f$(Z,async(J)=>{await $.reapplyEnabledSettings(),i1(Z),await l1(Z),await J9(J)})}async function lD($){let Z=$.getWorkspaceRoot();return f$(Z,async(J)=>{i1(Z);let Y=await $.refresh();return await l1(Z),await J9(J),Y})}async function Y9($){return f$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...W2.getInitializedInstances()])),Y;for(let Q of J){let X=await lD(Q);if(Q===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function iD($,Z){let J=c$.resolve($),Y=h1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function rD($){return c$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function IX($,Z){if(rD(Z)&&!vX(await a0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function V8($,Z,J,Y="local"){return p$.runExclusive(async()=>{let Q=c$.resolve($);return f$(Q,async(X)=>{let z=X.plugins.get(Z);if(!z)throw Error(`Plugin not found: ${Z}`);if(z.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await h1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let W=Y==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let H of W)await xX(H);let V=X.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let U=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:U.settings[Z]?.effectiveScope??"default"}})})}async function U8($){return p$.runExclusive(()=>f$($,async(Z)=>{i1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function Q9($,Z,J="global"){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q={...Z,...yX(Z)};return await h1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),f$(Y,async(X)=>{let z=J==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let W of z)await xX(W);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function X9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function z9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function W9($,Z,J=!1){return p$.runExclusive(async()=>{let Y=c$.resolve($);return f$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let z=await G$().uninstall(Z,J);if(!z.success)return{result:z};await iD(Y,Z);let W=await Y9(Y);return{result:z,discovery:W}})})}async function V9($,Z,J){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return G$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function U9($,Z){return p$.runExclusive(async()=>{let J=c$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(J);return G$().refreshMarketplace(Z,Y)})}async function H9($,Z=!1){return p$.runExclusive(()=>G$().removeMarketplace($,Z))}var nD={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
1112
1112
 
1113
1113
  ${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.response,durationMs:Y.durationMs,usage:Y.usage}}}},hX=nD;import bz from"node:fs/promises";import jz from"node:path";function B9($){return Number.isFinite($)?Math.max(0,$):0}function gX($){let Z=B9($.totalInputTokens),J=B9($.cacheReadTokens),Y=B9($.cacheWriteTokens),Q=Math.min(J,Z),X=Math.min(Y,Math.max(0,Z-Q)),z=Math.max(0,Z-Q-X),W=Z>0&&(J>0||Y>0);return{totalInputTokens:Z,cacheReadTokens:Q,cacheWriteTokens:X,uncachedInputTokens:z,...W?{hitRate:Q/Z}:{}}}function uX($){if($===void 0||!Number.isFinite($))return"—";return`${Math.round(Math.max(0,Math.min(1,$))*100)}%`}function dX($){return`${{model_changed:"model changed",system_prompt_changed:"system prompt changed",tools_changed:"tool definitions changed",request_policy_changed:"request policy changed",ttl_expired:"cache TTL expired",server_side:"likely Provider routing or eviction"}[$.reason]} (${$.previousCacheReadTokens.toLocaleString()} → ${$.cacheReadTokens.toLocaleString()} cache-read tokens)`}async function B8($,Z,J={}){let Y=Date.now(),Q=J.timeoutMs??20000,X="unknown";try{let z=m0($,Z,"off");X=z.model.api;let V=await new mX({...z.chat,temperature:0,maxOutputTokens:8,timeout:Q,streamIdleTimeout:Q,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(Q),{providerAdmission:{sessionId:`provider-health:${$.id}`,ownerId:`provider-health:${$.id}`,requestClass:"internal"}});if(!Boolean(V.content||V.reasoningContent||V.finishReason||V.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:"ok",message:"Provider responded successfully."}}catch(z){let W=W8(z);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:W.code,message:W.message}}}import sD from"node:os";import cX from"node:path";var G9=Object.freeze(["help","version","btw","effort","speed","verbosity","style"]),aD=new Set(G9);function K9($){return aD.has($)}function c($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
1114
1114
 
@@ -1675,7 +1675,7 @@ ${J}
1675
1675
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1676
1676
  `)}}case"create":{let W=aw(X);if("error"in W)return Y.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let V={prompt:W.prompt,projectPath:z,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(V),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
1677
1677
  ${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(W);return Y.sendMessage(V?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let W=X[0];if(!W)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(W,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await sw(W),Y.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
1678
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-b23aa6zn.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
1678
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-rtgbcq5r.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
1679
1679
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return $F(z,Z,J,Y);let V=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=oz(tz(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:V.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function $F($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let W=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",V=M9(W,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return V?[V]:[]})}function M9($,Z,J,Y,Q,X,z){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let V=W.indexOf(Z),U=Math.max(0,V-80),H=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:z}}function JW($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1680
1680
  `];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(`
1681
1681
  `)}var ZF={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=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await ZW(Y,{maxResults:15,projectPath:Z.cwd}),X=JW(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},YW=ZF;var JF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},QW=JF;import YF from"node:path";function O8($){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 XW($){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 zW($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function QF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),z=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:YF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)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 q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(W??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let V=[`**后台任务列表**
@@ -1,2 +1,2 @@
1
- import{V as I}from"./chunk-8mf7z5yp.js";import{he as M}from"./chunk-2q027yq5.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{V as I}from"./chunk-jntqevks.js";import{he as M}from"./chunk-p5233z7a.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as B,$ as C,V as D,x as E,i as F,K as G};
@@ -0,0 +1 @@
1
+ import{rf as a,sf as b}from"./chunk-88fhmxky.js";import"./chunk-hspgpbt5.js";import"./chunk-eg3ms291.js";export{a as globalOptions,b as cliConfig};
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d,o as e}from"./chunk-gqe8tyzb.js";import"./chunk-hspgpbt5.js";import"./chunk-eg3ms291.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +1 @@
1
- import{tf as a,uf as b,vf as c}from"./chunk-8mthb8hh.js";import"./chunk-nheny8xp.js";import"./chunk-nyr7d91w.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-06hkf59s.js";import"./chunk-sv9p66tx.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-md30ev61.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
1
+ import{tf as a,uf as b,vf as c}from"./chunk-tws1c1q5.js";import"./chunk-nheny8xp.js";import"./chunk-3b8hd8m3.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-06hkf59s.js";import"./chunk-x9xm6by7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-hspgpbt5.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +1 @@
1
- import{Ag as d,xg as a,yg as b,zg as c}from"./chunk-7wk76jf5.js";import"./chunk-sv9p66tx.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-md30ev61.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
1
+ import{Ag as d,xg as a,yg as b,zg as c}from"./chunk-jmpcycaf.js";import"./chunk-x9xm6by7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-hspgpbt5.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,d as createProcessModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +1 @@
1
- import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-11d6vk8g.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-stnjkq5d.js";import"./chunk-3y2x6fb6.js";import"./chunk-sv9p66tx.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-md30ev61.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-yw558b1h.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-5vjg37rf.js";import"./chunk-3y2x6fb6.js";import"./chunk-x9xm6by7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-hspgpbt5.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1 +1 @@
1
- import{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-nyr7d91w.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-sv9p66tx.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-md30ev61.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-3b8hd8m3.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-x9xm6by7.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-hspgpbt5.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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,4 +1,4 @@
1
- import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-stnjkq5d.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-sv9p66tx.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-md30ev61.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{sc as Xt,tc as En,uc as yn,vc as bn}from"./chunk-zzvs471p.js";import{zh as Bt}from"./chunk-5vjg37rf.js";import{$h as wn,Eh as xt,Fh as vi,Gh as sn,Hh as zt,Ih as U,Jh as en,Kh as gt,Lh as mt,Nh as rn,Oh as Tn,Ph as B,Qh as dn,Rh as on,Sh as pn,Th as lt,Uh as un,Vh as cn,Wh as Mn,Yh as S,ai as Gt,bi as Ut,ci as h,di as Ht}from"./chunk-x9xm6by7.js";import{bj as It}from"./chunk-2f8d0km4.js";import{Fj as X,Hj as x}from"./chunk-2mk914vk.js";import{Xj as tn,Yj as nn}from"./chunk-hspgpbt5.js";import{Mk as ns}from"./chunk-eg3ms291.js";import{EventEmitter as fs}from"events";import Un from"node:path";function hn(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function An(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${hn(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:An(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;isRetrySafe;constructor(t,i,n,s,e,r=!1){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e;this.isRetrySafe=r}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function jt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isConcurrencySafe:t.isConcurrencySafe??!1,isRetrySafe:t.isRetrySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{$e as a2,Ae as U1,Be as A0,Ce as B1,De as H1,Fe as d2,Me as i2,Ne as C0,Ue as p_,We as N1,Ye as r2,Ze as o2,_e as q1,oe as u2,pe as e,qe as h2,re as Z1,se as l2,te as v,ue as G1,ve as c2,we as p2,xe as V1,ye as L1,ze as n2}from"./chunk-y5wngtz0.js";import{vg as o_}from"./chunk-50vwafn5.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-md30ev61.js";import{Ak as c_,Bk as A,Ck as P,Dk as I,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
1
+ import{$e as a2,Ae as U1,Be as A0,Ce as B1,De as H1,Fe as d2,Me as i2,Ne as C0,Ue as p_,We as N1,Ye as r2,Ze as o2,_e as q1,oe as u2,pe as e,qe as h2,re as Z1,se as l2,te as v,ue as G1,ve as c2,we as p2,xe as V1,ye as L1,ze as n2}from"./chunk-y5wngtz0.js";import{vg as o_}from"./chunk-50vwafn5.js";import{rh as a_}from"./chunk-vbjgcn49.js";import{Vi as v2,Wi as P2,Xi as x_,Yi as Q0,Zi as w_}from"./chunk-5v0jcyea.js";import{bj as f1}from"./chunk-2f8d0km4.js";import{Dj as H0}from"./chunk-2mk914vk.js";import{Qj as i_,Tj as r_}from"./chunk-4cdk4mds.js";import{Xj as __}from"./chunk-hspgpbt5.js";import{Ak as c_,Bk as A,Ck as P,Dk as I,Ek as E1,Fk as F1,Gk as M_,Hk as z1,Ik as b1,Jk as q_,fk as h,pk as o,qk as p,rk as S2,sk as n,tk as d,uk as I2,vk as K0,wk as Y1,xk as m2,yk as K_,zk as M0}from"./chunk-4wx5sya5.js";import{readdir as b_,readFile as V_,rm as f_,stat as E0}from"node:fs/promises";import*as N from"node:path";import{nanoid as m}from"nanoid";import{createHash as F4,randomUUID as z4}from"node:crypto";import*as W_ from"node:fs/promises";import*as W0 from"node:path";import D4 from"proper-lockfile";function cX(_){return Object.freeze({kind:"local",root:_})}function pX(_,X){let $=o(X);if(p($.collisionIdentity)!==_)throw Error("ACP remote workspace durable state is invalid");return Object.freeze({kind:"acp-remote",root:_,descriptor:$})}function nX(_,X){return _.kind==="acp-remote"?`${_.kind}\x00${_.root}\x00${_.descriptor.exactIdentity}\x00${X}`:`${_.kind}\x00${_.root}\x00${X}`}async function H_(_,X){if(_.kind==="local")return X(K_(_.root));return n(_.root,($)=>X(String($),$))}async function dX(_,X,$){return H_(_,(W,J)=>$(J?{storageRoot:W,transcriptPath:I(J,X),inboxPath:F1(J,X),goalPath:z1(J,X),remoteScope:J}:{storageRoot:W,transcriptPath:P(_.root,X),inboxPath:E1(_.root,X),goalPath:M_(_.root,X)}))}import{execFileSync as T4}from"node:child_process";import{createHash as C4}from"node:crypto";import{readFileSync as K4}from"node:fs";var M4=/^[a-f0-9]{64}$/;function D1(_){if(!_||typeof _!=="object")return!1;let X=_;return(X.platform==="linux"||X.platform==="darwin"||X.platform==="win32")&&typeof X.fingerprint==="string"&&M4.test(X.fingerprint)}var R1={readFile:(_)=>K4(_,"utf8"),execFile:(_,X)=>T4(_,X,{encoding:"utf8",timeout:_==="powershell.exe"?3000:2000,windowsHide:!0})},A4=(_)=>{try{return process.kill(_,0),!0}catch(X){return X instanceof Error&&"code"in X&&X.code==="EPERM"}};function x0(_,X){return{platform:_,fingerprint:C4("sha256").update(`${_}\x00${X}`).digest("hex")}}function E4(_,X){let $=X.readFile(`/proc/${_}/stat`).trim(),W=$.lastIndexOf(")");if(W<0)throw Error("Invalid /proc process stat");let O=$.slice(W+2).split(/\s+/)[19];if(!O||!/^\d+$/.test(O))throw Error("Missing process start ticks");return O}function m_(_,X=process.platform,$=R1){if(!Number.isInteger(_)||_<=1)return;try{if(X==="linux")return x0(X,E4(_,$));if(X==="darwin"){let W=$.execFile("ps",["-o","lstart=","-p",String(_)]).trim();return W?x0(X,W):void 0}if(X==="win32"){let W=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${_}").CreationDate.ToUniversalTime().ToString('O')`,J=$.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",W]).trim();return J?x0(X,J):void 0}}catch{return}return}function tX(_,X){return m_(_,X.platform)?.fingerprint===X.fingerprint}function sX(_,X,$=R1,W=A4){if(!Number.isInteger(_)||_<=1)return!1;let J=m_(_,X.platform,$);if(J)return J.fingerprint===X.fingerprint;return!W(_)}var j1=1;function R4(_,X){let $=F4("sha256").update(X).digest("hex");return W0.join(K_(_),".locks",`${$}.lock`)}function R_(_,X){return _ instanceof Error&&"code"in _&&_.code===X}async function k0(_){try{let X=JSON.parse(await W_.readFile(_,"utf8"));if(X.version!==j1||typeof X.sessionId!=="string"||typeof X.ownerId!=="string"||!Number.isInteger(X.pid)||(X.pid??0)<=0||X.processIdentity!==void 0&&!D1(X.processIdentity)||typeof X.acquiredAt!=="string")return;return X}catch(X){if(R_(X,"ENOENT")||X instanceof SyntaxError)return;throw X}}async function w1(_){let X=await k0(_);if(X)return X;return await new Promise(($)=>setTimeout($,10)),k0(_)}function w4(_){try{return process.kill(_,0),!0}catch(X){return!R_(X,"ESRCH")}}async function x1(_,X){let $;try{return $=await W_.open(_,"wx",384),await $.writeFile(`${JSON.stringify(X)}
2
2
  `,"utf8"),!0}catch(W){if(R_(W,"EEXIST"))return!1;if($)await W_.unlink(_).catch(()=>{return});throw W}finally{await $?.close().catch(()=>{return})}}class $_ extends Error{code="BLADE_SESSION_IN_USE";constructor(_){super(_?`Session is already active in another Blade process (PID ${_}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}async function k1(_,X,$=!1){let W,J;try{J=await D4.lock(_,{realpath:!1,retries:$?{retries:50,minTimeout:10,maxTimeout:100,factor:1.2}:0,onCompromised:(Q)=>{W=Q}})}catch(Q){if(R_(Q,"ELOCKED"))throw new $_;throw Q}let O=()=>{if(W)throw W};try{O();let Q=await X(O);return O(),Q}finally{await J()}}class u{filePath;record;stateStorage;released=!1;constructor(_,X,$){this.filePath=_;this.record=X;this.stateStorage=$}static async acquireForStorage(_,X){if(X.kind==="local")return u.acquire(_,X.root);return H_(X,($,W)=>{if(!W||$!==X.root)throw Error("ACP remote session lease scope is invalid");return u.acquireRemote(_,W,X)})}static async acquire(_,X=f1()){return u.acquireAtPath(_,R4(X,_))}static async acquireRemote(_,X,$){let W=b1(X,_);try{await d(X,W)}catch(O){if(O.code!=="ENOENT")throw O}let J=await u.acquireAtPath(_,W);try{return await d(X,W),new u(W,J.record,$)}catch(O){throw await J.release(),O}}static async acquireAtPath(_,X){return await W_.mkdir(W0.dirname(X),{recursive:!0,mode:448}),k1(X,async($)=>{let W={version:j1,sessionId:_,ownerId:z4(),pid:process.pid,processIdentity:m_(process.pid),acquiredAt:new Date().toISOString()};if($(),await x1(X,W))return new u(X,W);let J=await w1(X);if(!J||J.sessionId!==_)throw new $_;if(w4(J.pid)){let O=J.processIdentity?m_(J.pid,J.processIdentity.platform):void 0;if(!O||O.fingerprint===J.processIdentity?.fingerprint)throw new $_(J.pid)}if($(),await W_.unlink(X).catch((O)=>{if(!R_(O,"ENOENT"))throw O}),$(),await x1(X,W))return new u(X,W);throw new $_((await w1(X))?.pid)})}async release(){if(this.released)return;let _=()=>k1(this.filePath,async(X)=>{if((await k0(this.filePath))?.ownerId!==this.record.ownerId)return;X(),await W_.unlink(this.filePath).catch((W)=>{if(!R_(W,"ENOENT"))throw W})},!0);if(this.stateStorage?.kind==="acp-remote")await H_(this.stateStorage,_);else await _();this.released=!0}}import{createHash as O0}from"node:crypto";import{constants as A_,promises as O_}from"node:fs";import G_ from"node:path";import{Mutex as x4}from"async-mutex";var y1=128,g1=67108864,k4=24576,S1=65536,f0=1,h1=/^[a-f0-9]{64}$/,b4=/^[a-f0-9]{64}\.txt$/,l1=64,f4=new Set(["EBUSY","EAGAIN","EMFILE","ENFILE"]),Y0=`
3
3
 
4
4
  ...[middle omitted; read the private prompt artifact for the complete request]...
@@ -1,4 +1,4 @@
1
- import{Pf as N}from"./chunk-nyr7d91w.js";import{zh as $}from"./chunk-stnjkq5d.js";import{bj as _}from"./chunk-2f8d0km4.js";import{Bj as Y,Dj as Z}from"./chunk-2mk914vk.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Pf as N}from"./chunk-3b8hd8m3.js";import{zh as $}from"./chunk-5vjg37rf.js";import{bj as _}from"./chunk-2f8d0km4.js";import{Bj as Y,Dj as Z}from"./chunk-2mk914vk.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as xf,y as yf,j as zf,C as Af};
@@ -1 +1 @@
1
- import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-md30ev61.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-hspgpbt5.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};