blade-code 0.11.2 → 0.11.3

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 (94) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-a3dz41pd.js → chunk-0759ckbc.js} +1 -1
  3. package/dist/{chunk-04qhtx2w.js → chunk-0pcrccgp.js} +1 -1
  4. package/dist/{chunk-0kxya4ye.js → chunk-33w0b9r4.js} +1 -1
  5. package/dist/{chunk-kaj8jaj5.js → chunk-3rxs9vxm.js} +1 -1
  6. package/dist/{chunk-f9qrjd2f.js → chunk-45xdp95z.js} +1 -1
  7. package/dist/{chunk-tx9tb485.js → chunk-5qrw9g8c.js} +1 -1
  8. package/dist/chunk-b3kvf23h.js +357 -0
  9. package/dist/{chunk-21qsfewd.js → chunk-b7pn03pb.js} +1 -1
  10. package/dist/{chunk-t3pkk95s.js → chunk-b8hm4td5.js} +1 -1
  11. package/dist/{chunk-s7x4x6xw.js → chunk-cmpxdek8.js} +1 -1
  12. package/dist/{chunk-8q6zsznc.js → chunk-crbt25b4.js} +1 -1
  13. package/dist/{chunk-ebvzp8tn.js → chunk-dv5ts9ae.js} +1 -1
  14. package/dist/{chunk-zwe1a7xe.js → chunk-dyf12wbv.js} +1 -1
  15. package/dist/{chunk-634ymwg5.js → chunk-fa5sebe2.js} +1 -1
  16. package/dist/{chunk-7rz5dt79.js → chunk-faedrfhd.js} +2 -2
  17. package/dist/{chunk-enmn892r.js → chunk-ffq1k7q5.js} +1 -1
  18. package/dist/{chunk-65v1vjvg.js → chunk-fnvh22vc.js} +1 -1
  19. package/dist/{chunk-p665f6pn.js → chunk-gfhb2h6z.js} +1 -1
  20. package/dist/{chunk-pjeks4cz.js → chunk-gqypt03h.js} +1 -1
  21. package/dist/{chunk-gymecxcc.js → chunk-hn2p1296.js} +1 -1
  22. package/dist/chunk-hnnhpv75.js +1 -0
  23. package/dist/{chunk-vemyfx92.js → chunk-hzz27w5w.js} +1 -1
  24. package/dist/{chunk-fb2x1026.js → chunk-jm1chm6x.js} +1 -1
  25. package/dist/{chunk-290p3r7a.js → chunk-kb4hwa5a.js} +1 -1
  26. package/dist/{chunk-qhcd0ww0.js → chunk-kdtj92em.js} +1 -1
  27. package/dist/{chunk-qyfbeg5h.js → chunk-mmpcq1yh.js} +1 -1
  28. package/dist/{chunk-k2rgg45h.js → chunk-mqfayxf7.js} +1 -1
  29. package/dist/{chunk-er6zghgg.js → chunk-nts19h6v.js} +1 -1
  30. package/dist/{chunk-re8p2y22.js → chunk-nvj4da2w.js} +1 -1
  31. package/dist/{chunk-yjcp8jk1.js → chunk-pbckwd41.js} +1 -1
  32. package/dist/{chunk-xnys4bgs.js → chunk-prqtwzxd.js} +1 -1
  33. package/dist/{chunk-g7pjgspy.js → chunk-qvew5nk3.js} +1 -1
  34. package/dist/{chunk-h4b4fn3t.js → chunk-qy6p8bpr.js} +1 -1
  35. package/dist/{chunk-6x5f6she.js → chunk-r5svk833.js} +1 -1
  36. package/dist/{chunk-3ee357pw.js → chunk-r9nyzqzb.js} +5 -5
  37. package/dist/{chunk-xrgeakpy.js → chunk-s3pnhdqk.js} +1 -1
  38. package/dist/{chunk-2fdghgmf.js → chunk-t0swttvj.js} +2 -2
  39. package/dist/{chunk-qa86anwd.js → chunk-x2crj6jq.js} +1 -1
  40. package/dist/chunk-yw3achrm.js +1 -0
  41. package/dist/{chunk-zf72e5w8.js → chunk-zc8erdkc.js} +1 -1
  42. package/dist/web/assets/ChatView-CvuKp3Yl.js +17 -0
  43. package/dist/web/assets/{CodeBlockHighlighter-OvLyFs9U.js → CodeBlockHighlighter-CYiAdOLs.js} +1 -1
  44. package/dist/web/assets/FilePreview-DGolvoH6.js +8 -0
  45. package/dist/web/assets/KanbanBoard-DdwrLpvb.js +1 -0
  46. package/dist/web/assets/{MarkdownRenderer-BTxnqChi.js → MarkdownRenderer-fJny7W8J.js} +3 -3
  47. package/dist/web/assets/{ScrollArea-BdOqyQ3g.js → ScrollArea-CSCl8r35.js} +1 -1
  48. package/dist/web/assets/{SessionHistorySurface-DaKE2oKU.js → SessionHistorySurface-dttyHhtN.js} +1 -1
  49. package/dist/web/assets/SettingsModal-Bn9m-F-v.js +5 -0
  50. package/dist/web/assets/Sidebar-JYvLuHTi.js +1 -0
  51. package/dist/web/assets/{TaskSwitcher-DKelLFZm.js → TaskSwitcher-InE9ArQH.js} +1 -1
  52. package/dist/web/assets/{TerminalPanel-D5Rieq62.js → TerminalPanel-BLRAlQoa.js} +1 -1
  53. package/dist/web/assets/{archive-CsFSEMp9.js → archive-D3alcPOa.js} +1 -1
  54. package/dist/web/assets/{arrow-left-gaino9Tb.js → arrow-left-CNfcSdE2.js} +1 -1
  55. package/dist/web/assets/{calendar-clock-DfHUrEw9.js → calendar-clock-BoRTfsxW.js} +1 -1
  56. package/dist/web/assets/chevron-right-B8JH5N50.js +1 -0
  57. package/dist/web/assets/{clock-3-dWIDc9IF.js → clock-3-BGymk4sE.js} +1 -1
  58. package/dist/web/assets/{copy-BPfhyh47.js → copy-CLG3LQ2v.js} +1 -1
  59. package/dist/web/assets/{dist-RGayDvc-.js → dist-BtGkS2rG.js} +1 -1
  60. package/dist/web/assets/{download-BR2L5Wme.js → download-DxK6pukC.js} +1 -1
  61. package/dist/web/assets/{folder-8dmZJ2a6.js → folder-B0xRimYH.js} +1 -1
  62. package/dist/web/assets/index-BJdxoBtv.css +1 -0
  63. package/dist/web/assets/{index-DSa8Dzp7.js → index-DkwePtIh.js} +4 -4
  64. package/dist/web/assets/{pause-DLZIDFMB.js → pause-CKNq9DgJ.js} +1 -1
  65. package/dist/web/assets/{pencil-DkC0bPYD.js → pencil-CMjIwtk5.js} +1 -1
  66. package/dist/web/assets/{play-BVeNn6fv.js → play-BOz9Sqzf.js} +1 -1
  67. package/dist/web/assets/plus-BJIEQjD7.js +1 -0
  68. package/dist/web/assets/preload-helper-HI3NtP3B.js +1 -0
  69. package/dist/web/assets/{session-events-BuMTbIwu.js → session-events-B-hnDC4L.js} +3 -3
  70. package/dist/web/assets/{settings-msYyNDKx.js → settings-CP6ArjQ7.js} +1 -1
  71. package/dist/web/assets/team-BHlihaeV.js +1 -0
  72. package/dist/web/assets/{teamService-Bus5RDi1.js → teamService-DDfifLYm.js} +1 -1
  73. package/dist/web/assets/{terminal-Cp5WYo8w.js → terminal-BYHhWXe-.js} +1 -1
  74. package/dist/web/assets/tooltip-DJBQZhJD.js +1 -0
  75. package/dist/web/assets/triangle-alert-BCJaJaVj.js +1 -0
  76. package/dist/web/assets/{vendor-radix-L0yJCKJX.js → vendor-radix-BCAvgfOW.js} +1 -1
  77. package/dist/web/assets/{vendor-react-CHEIQMI-.js → vendor-react-DQwAdeyS.js} +1 -1
  78. package/dist/web/index.html +5 -5
  79. package/package.json +1 -1
  80. package/dist/chunk-d4xsrx3z.js +0 -357
  81. package/dist/chunk-eg0s155w.js +0 -1
  82. package/dist/chunk-gff7a5q0.js +0 -1
  83. package/dist/web/assets/ChatView-DysPZPwF.js +0 -17
  84. package/dist/web/assets/FilePreview-CkSPwPdW.js +0 -8
  85. package/dist/web/assets/KanbanBoard-DH1wApt6.js +0 -1
  86. package/dist/web/assets/SettingsModal-CWlSSO_E.js +0 -5
  87. package/dist/web/assets/Sidebar-Dirk-XAQ.js +0 -1
  88. package/dist/web/assets/chevron-right-Bvu2j6hB.js +0 -1
  89. package/dist/web/assets/index-B7RyuO2x.css +0 -1
  90. package/dist/web/assets/message-square-plus-BgC981WF.js +0 -1
  91. package/dist/web/assets/plus-kzdwas-3.js +0 -1
  92. package/dist/web/assets/preload-helper-DvgLbiBV.js +0 -1
  93. package/dist/web/assets/team-D3XOVbxL.js +0 -1
  94. package/dist/web/assets/triangle-alert-cGqHxFsZ.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Ka as QJ}from"./chunk-wnzr9h84.js";import{Na as T,Oa as t0,Ta as DW,Ua as PY,Va as o0}from"./chunk-290p3r7a.js";import{Ab as JV,Wa as t8,Za as u3,bb as n3,cb as KX,db as DX,fb as eW,hb as $V,ib as b9}from"./chunk-6x5f6she.js";import{Bb as i5,Cb as I7,Db as J1,Eb as d7,Fb as G2,Gb as KY,Hb as S1,Ib as t7,Jb as qY,Kb as YY,Lb as wY,Mb as FY,Nb as zQ,Pb as WX,Rb as V0,Tb as w2,Wb as u6,Yb as G3,Zb as d6,_b as m6,ac as jZ,bc as T$,hc as $W,ic as V8,jc as JW,kc as ZW,lc as XX,nc as x1,oc as IX,tc as nY,wc as aY}from"./chunk-d4xsrx3z.js";import{$c as h4,Cc as k$,Dc as fX,Ec as lJ,Fc as PJ,Gc as M1,Hc as eJ,Ic as L0,Jc as S2,Kc as L1,Lc as P4,Mc as T9,Nc as h6,Oc as g6,Pc as XY,Qc as WY,Rc as PX,Sc as YJ,Sd as Z8,Tc as j1,Uc as JJ,Ud as f0,Vc as u8,Vd as _$,Wc as e$,Xc as $1,Yc as l2,Zc as c2,_c as i2,ad as g4,bd as d2,be as UW,cd as UJ,ce as GX,dd as m2,ed as d8,fd as E1,fe as rY,gd as s1,hd as p2,id as o1,jd as t1,kd as u4,ke as vX,ld as e1,le as yX,md as d4,nd as m4,ne as o,od as S$,pd as p4,qd as LJ,rd as r2,sd as c4,td as l4,ud as i4,vd as r4,wd as OJ,xd as _J,zd as NJ}from"./chunk-7rz5dt79.js";import{oe as l,pe as DQ,qe as qQ,re as yZ,te as q2}from"./chunk-skktstg8.js";import{Me as R9,Ne as $$,Oe as K2,Pe as s3,Qe as SX,Re as kX,_e as XV,lf as WV,ve as YV,ye as QV}from"./chunk-wan9q99y.js";import{Hf as LZ,If as wZ}from"./chunk-crv3sghv.js";import{$f as F2,Uf as p6,Vf as N0,Wf as g,Zf as E0,_f as C6,ag as H1,bg as b3,cg as A2,dg as lY,eg as U2}from"./chunk-ebvzp8tn.js";import{fg as h1}from"./chunk-x6k5ye1z.js";import{hg as eX,jg as F3,kg as iY,pg as pY,qg as iX,rg as T6}from"./chunk-g0xtk1yy.js";import{sg as c3}from"./chunk-q6sr4979.js";import{vg as u0,wg as F1}from"./chunk-g2295k8s.js";import{xg as QW}from"./chunk-pm163dfm.js";import{Ag as EX,Bg as AX,Cg as MX,zg as jX}from"./chunk-zwe1a7xe.js";import{$g as R6,Dg as k6,Eg as v6,Fg as y6,Hg as I6,Ig as x6,Jg as q1,Kg as I$,Lg as N$,Mg as H$,Ng as n8,Og as Q2,Pg as X8,Qg as m1,Rg as p1,Sg as TX,Wg as t3,Yg as d0,Zg as R$,ah as RX,bh as xX}from"./chunk-8q6zsznc.js";import{dh as B1,fh as C$,gh as L6}from"./chunk-kehgewqh.js";import{hh as gJ,ih as Y2,jh as uJ,kh as s2,lh as dJ,mh as mJ,nh as $6,oh as e4,ph as pJ,qh as cJ,rh as t4}from"./chunk-kkzznz4w.js";import{sh as EW,uh as CX,vh as J8,wh as OZ}from"./chunk-1cy4ab77.js";import{Ah as y0,yh as q9}from"./chunk-k2rgg45h.js";import{Bh as j4,Ch as C9,Dh as E4,Eh as c1}from"./chunk-ys8gysg8.js";import{Fi as kY,Gi as vY,Hh as YZ,Hi as yY,Ih as F$,Ii as IY,Ji as _3,Ki as xY,Li as U1,Mi as hY,Nh as QZ,Ni as gY,Oi as uY,Ph as z9,Qi as sJ,Si as gX,Ti as bX,Uh as KW,Ui as B0,Yh as XZ,_h as OX,ai as BY,bi as GY,si as v1,vi as ZY}from"./chunk-h4b4fn3t.js";import{Xi as Q6,Zi as C}from"./chunk-b22ab7yw.js";import{xj as YX,zj as QX}from"./chunk-m2x6pb4f.js";import{Ej as $0,Gj as n4,Hj as Z2,Ij as K,Jj as CJ,Kj as S,Lj as h}from"./chunk-4e4qtpca.js";import{Pj as _X,Qj as NX}from"./chunk-5s2x98rx.js";import{Rj as MW,Uj as bW}from"./chunk-0eajnhrj.js";import{Yj as fW}from"./chunk-yjcp8jk1.js";import{dk as hX,ek as r0}from"./chunk-px45q235.js";import{Bk as b$,Gk as hJ,fk as e,gk as O$,hk as B$,ik as a1,jk as a9,kk as u2,lk as Y$,mk as JY,pk as I4,yk as f4}from"./chunk-a95jmx2j.js";import{Lk as J$}from"./chunk-sdapqhj0.js";import{randomUUID as _8}from"crypto";import{randomUUID as EV}from"node:crypto";var OV=String.raw`
1
+ import{Ka as QJ}from"./chunk-wnzr9h84.js";import{Na as T,Oa as t0,Ta as DW,Ua as PY,Va as o0}from"./chunk-kb4hwa5a.js";import{Ab as JV,Wa as t8,Za as u3,bb as n3,cb as KX,db as DX,fb as eW,hb as $V,ib as b9}from"./chunk-r5svk833.js";import{Bb as i5,Cb as I7,Db as J1,Eb as d7,Fb as G2,Gb as KY,Hb as S1,Ib as t7,Jb as qY,Kb as YY,Lb as wY,Mb as FY,Nb as zQ,Pb as WX,Rb as V0,Tb as w2,Wb as u6,Yb as G3,Zb as d6,_b as m6,ac as jZ,bc as T$,hc as $W,ic as V8,jc as JW,kc as ZW,lc as XX,nc as x1,oc as IX,tc as nY,wc as aY}from"./chunk-b3kvf23h.js";import{$c as h4,Cc as k$,Dc as fX,Ec as lJ,Fc as PJ,Gc as M1,Hc as eJ,Ic as L0,Jc as S2,Kc as L1,Lc as P4,Mc as T9,Nc as h6,Oc as g6,Pc as XY,Qc as WY,Rc as PX,Sc as YJ,Sd as Z8,Tc as j1,Uc as JJ,Ud as f0,Vc as u8,Vd as _$,Wc as e$,Xc as $1,Yc as l2,Zc as c2,_c as i2,ad as g4,bd as d2,be as UW,cd as UJ,ce as GX,dd as m2,ed as d8,fd as E1,fe as rY,gd as s1,hd as p2,id as o1,jd as t1,kd as u4,ke as vX,ld as e1,le as yX,md as d4,nd as m4,ne as o,od as S$,pd as p4,qd as LJ,rd as r2,sd as c4,td as l4,ud as i4,vd as r4,wd as OJ,xd as _J,zd as NJ}from"./chunk-faedrfhd.js";import{oe as l,pe as DQ,qe as qQ,re as yZ,te as q2}from"./chunk-skktstg8.js";import{Me as R9,Ne as $$,Oe as K2,Pe as s3,Qe as SX,Re as kX,_e as XV,lf as WV,ve as YV,ye as QV}from"./chunk-wan9q99y.js";import{Hf as LZ,If as wZ}from"./chunk-crv3sghv.js";import{$f as F2,Uf as p6,Vf as N0,Wf as g,Zf as E0,_f as C6,ag as H1,bg as b3,cg as A2,dg as lY,eg as U2}from"./chunk-dv5ts9ae.js";import{fg as h1}from"./chunk-x6k5ye1z.js";import{hg as eX,jg as F3,kg as iY,pg as pY,qg as iX,rg as T6}from"./chunk-g0xtk1yy.js";import{sg as c3}from"./chunk-q6sr4979.js";import{vg as u0,wg as F1}from"./chunk-g2295k8s.js";import{xg as QW}from"./chunk-pm163dfm.js";import{Ag as EX,Bg as AX,Cg as MX,zg as jX}from"./chunk-dyf12wbv.js";import{$g as R6,Dg as k6,Eg as v6,Fg as y6,Hg as I6,Ig as x6,Jg as q1,Kg as I$,Lg as N$,Mg as H$,Ng as n8,Og as Q2,Pg as X8,Qg as m1,Rg as p1,Sg as TX,Wg as t3,Yg as d0,Zg as R$,ah as RX,bh as xX}from"./chunk-crbt25b4.js";import{dh as B1,fh as C$,gh as L6}from"./chunk-kehgewqh.js";import{hh as gJ,ih as Y2,jh as uJ,kh as s2,lh as dJ,mh as mJ,nh as $6,oh as e4,ph as pJ,qh as cJ,rh as t4}from"./chunk-kkzznz4w.js";import{sh as EW,uh as CX,vh as J8,wh as OZ}from"./chunk-1cy4ab77.js";import{Ah as y0,yh as q9}from"./chunk-mqfayxf7.js";import{Bh as j4,Ch as C9,Dh as E4,Eh as c1}from"./chunk-ys8gysg8.js";import{Fi as kY,Gi as vY,Hh as YZ,Hi as yY,Ih as F$,Ii as IY,Ji as _3,Ki as xY,Li as U1,Mi as hY,Nh as QZ,Ni as gY,Oi as uY,Ph as z9,Qi as sJ,Si as gX,Ti as bX,Uh as KW,Ui as B0,Yh as XZ,_h as OX,ai as BY,bi as GY,si as v1,vi as ZY}from"./chunk-qy6p8bpr.js";import{Xi as Q6,Zi as C}from"./chunk-b22ab7yw.js";import{xj as YX,zj as QX}from"./chunk-m2x6pb4f.js";import{Ej as $0,Gj as n4,Hj as Z2,Ij as K,Jj as CJ,Kj as S,Lj as h}from"./chunk-4e4qtpca.js";import{Pj as _X,Qj as NX}from"./chunk-5s2x98rx.js";import{Rj as MW,Uj as bW}from"./chunk-0eajnhrj.js";import{Yj as fW}from"./chunk-pbckwd41.js";import{dk as hX,ek as r0}from"./chunk-px45q235.js";import{Bk as b$,Gk as hJ,fk as e,gk as O$,hk as B$,ik as a1,jk as a9,kk as u2,lk as Y$,mk as JY,pk as I4,yk as f4}from"./chunk-a95jmx2j.js";import{Lk as J$}from"./chunk-sdapqhj0.js";import{randomUUID as _8}from"crypto";import{randomUUID as EV}from"node:crypto";var OV=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -866,8 +866,8 @@ ${z.additionalContext}`};if(z.warning)console.warn(`[ToolExecutor] PostToolUseFa
866
866
  ${l$}
867
867
  </approved-plan>
868
868
 
869
- IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof b==="string")P2=b+A9;else P2=[...b,{type:"text",text:A9}]}k=yield*this.runLoop(P2,_,{...I,inputMessageId:void 0})}}finally{this.clearSkillContext()}if(!this.sessionRuntime||!y)return k;let a=v??await this.sessionRuntime.getGoal(),u=await this.sessionRuntime.recordGoalProgress({tokens:k.metadata?.tokensUsed??0,elapsedMs:k.metadata?.duration??0,turnId:y.id,...a?{goalId:a.goalId,objective:a.objective}:{},executionHostFailureCategory:k.metadata?.executionHostFailureCategory,prematureStopPattern:k.success?zY(k.finalMessage):void 0});if(u)yield{kind:"goal_updated",goal:u};if(!k.success||_.signal?.aborted){if(u=await this.sessionRuntime.pauseActiveGoal(_.signal?.aborted?"goal paused after user cancellation":k.error?.message??"goal paused after turn failure"),u)yield{kind:"goal_updated",goal:u}}if(k.success&&!_.signal?.aborted&&m<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(y,_.signal);let m0=k.success&&!_.signal?.aborted&&m<20,z0=UG(k)||!k.success&&k.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(y,{continuePending:m0,...z0?{acknowledgeInput:!0}:{},outcome:k.success&&!_.signal?.aborted?{status:"completed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}:{status:"aborted",cause:_.signal?.aborted?"cancelled":"failed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0}}),R){m++,N=!0,A=!1,j=null,b="",c=void 0,M="",P=void 0,E=J0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:t(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!k.success||_.signal?.aborted)return k;if(u=await this.sessionRuntime.getGoal(),!u||u.status!=="active"&&u.status!=="verifying")return k;let F0=await this.sessionRuntime.prepareGoalContinuation(u);if(!F0.ok){if(F0.goal)yield{kind:"goal_updated",goal:F0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:F0.error.message},metadata:{turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,duration:k.metadata?.duration??0}}}let P$=await this.sessionRuntime.beginGoalTurn(F0.goal);if(!P$)return k;j=P$.goal,w={...F0,goal:P$.goal},R=P$.handle,N=!1,A=!0,b=C5(j),c=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:F0.frontier,tasks:F0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let L=typeof z==="string"?z:z.filter((b)=>b.type==="text").map((b)=>b.text).join(`
870
- `),O={id:this.generateTaskId(),type:"simple",prompt:L};return{success:!0,finalMessage:(await this.executeTask(O)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,J,Z){let{drainLoop:Y}=await import("./chunk-pjeks4cz.js");return Y(this.chatStream($,J,Z))}async*runPlanLoop($,J,Z){s.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...J.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:J.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:J.executionRoot??J.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...J.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,J,Z,Y)}async*runLoop($,J,Z){s.debug("Processing enhanced chat message...");let Y=J.systemPrompt??await this.buildSystemPromptOnDemand(J);return yield*this.executeLoop($,J,Z,Y)}async buildSystemPromptOnDemand($){let J=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:J,append:Z,includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,J,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,J,Z,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:J,result:Z})=>{let Y={id:J.toolCallId,type:"function",function:{name:J.toolName,arguments:JSON.stringify(J.input)}},Q=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0,X=Z.error===void 0,W=Z.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?Z.error?`Subagent execution failed: ${Z.error}.`:"":String(W),...Z.error?{error:{type:"execution_error",message:Z.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=nY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),J=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),Z=J&&J.state!=="none"?[{kind:"turn_recovery",assessment:J}]:[];return Z.push(...this.takeStartupAdoptedToolResultEvents()),Z}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,J,Z,Y)=>this.sessionRuntime.resolveContextualProjectRules($,J,Z,Y):void 0}}async chatWithSystem($,J){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:J}];return(await this.chatService.chat(Z)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let J=this.toolExecutor.getRegistry(),Y=J.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)J.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let J=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of J.getAll())if(Z.has(Y.name))J.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),J=new Map;return $.forEach((Z)=>{let Y=J.get(Z.kind)||0;J.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(J),toolNames:$.map((Z)=>Z.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,J){s.debug(`[MainAgent] ${$}`,J||"")}error($,J){s.error(`[MainAgent] ${$}`,J||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt,Z=await Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:J,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...x1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(Z.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f6({sessionId:"default",configDir:e(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let J=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${J} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await X6({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let J=o0.createIsolated({artifactWriter:new o2(`legacy-${VG()}`)});this.legacyMcpRegistry=J;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await J.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let Z=this.toolExecutor.getRegistry();Z.setMcpCatalogBarrier(()=>J.waitForCatalogIdle());let Y=J.getCatalogSnapshot();Z.replaceMcpTools(Y.tools),Z.registerAll(Z4(J));let Q=J.getInstructionsSnapshot();if(Z.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),J.on("catalogChanged",(X)=>{Z.replaceMcpTools(X.tools,X)}),J.on("contentCatalogChanged",(X)=>{Z.queueMcpContentChange(X)}),J.on("resourceUpdated",(X)=>{Z.queueMcpResourceUpdated(X)}),J.on("connectionLifecycleChanged",(X)=>{Z.queueMcpConnectionChange(X)}),J.on("log",(X)=>{Z.queueMcpLog(X)}),J.on("instructionsChanged",(X)=>{Z.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await d0(C());if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let J=this.subagentRegistry.getAllNames().length;if(J>0)s.debug(`Loaded ${J} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let J=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${J.join(", ")}`);let Z=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return J.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let J=[];for(let Y of $)if(Y.type==="text")J.push(Y.text);if(J.length===0)return $;let Z=J.join(`
869
+ IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof b==="string")P2=b+A9;else P2=[...b,{type:"text",text:A9}]}k=yield*this.runLoop(P2,_,{...I,inputMessageId:void 0})}}finally{this.clearSkillContext()}if(!this.sessionRuntime||!y)return k;let a=v??await this.sessionRuntime.getGoal(),u=await this.sessionRuntime.recordGoalProgress({tokens:k.metadata?.tokensUsed??0,elapsedMs:k.metadata?.duration??0,turnId:y.id,...a?{goalId:a.goalId,objective:a.objective}:{},executionHostFailureCategory:k.metadata?.executionHostFailureCategory,prematureStopPattern:k.success?zY(k.finalMessage):void 0});if(u)yield{kind:"goal_updated",goal:u};if(!k.success||_.signal?.aborted){if(u=await this.sessionRuntime.pauseActiveGoal(_.signal?.aborted?"goal paused after user cancellation":k.error?.message??"goal paused after turn failure"),u)yield{kind:"goal_updated",goal:u}}if(k.success&&!_.signal?.aborted&&m<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(y,_.signal);let m0=k.success&&!_.signal?.aborted&&m<20,z0=UG(k)||!k.success&&k.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(y,{continuePending:m0,...z0?{acknowledgeInput:!0}:{},outcome:k.success&&!_.signal?.aborted?{status:"completed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0,...k.metadata?.usage?{usage:k.metadata.usage}:{}}:{status:"aborted",cause:_.signal?.aborted?"cancelled":"failed",turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,durationMs:k.metadata?.duration??0,...k.metadata?.usage?{usage:k.metadata.usage}:{}}}),R){m++,N=!0,A=!1,j=null,b="",c=void 0,M="",P=void 0,E=J0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:t(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!k.success||_.signal?.aborted)return k;if(u=await this.sessionRuntime.getGoal(),!u||u.status!=="active"&&u.status!=="verifying")return k;let F0=await this.sessionRuntime.prepareGoalContinuation(u);if(!F0.ok){if(F0.goal)yield{kind:"goal_updated",goal:F0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:F0.error.message},metadata:{turnsCount:k.metadata?.turnsCount??0,toolCallsCount:k.metadata?.toolCallsCount??0,duration:k.metadata?.duration??0}}}let P$=await this.sessionRuntime.beginGoalTurn(F0.goal);if(!P$)return k;j=P$.goal,w={...F0,goal:P$.goal},R=P$.handle,N=!1,A=!0,b=C5(j),c=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:F0.frontier,tasks:F0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let L=typeof z==="string"?z:z.filter((b)=>b.type==="text").map((b)=>b.text).join(`
870
+ `),O={id:this.generateTaskId(),type:"simple",prompt:L};return{success:!0,finalMessage:(await this.executeTask(O)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,J,Z){let{drainLoop:Y}=await import("./chunk-gqypt03h.js");return Y(this.chatStream($,J,Z))}async*runPlanLoop($,J,Z){s.debug("Processing Plan mode message...");let{prompt:Y}=await Z1({...J.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:J.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:J.executionRoot??J.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...J.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,J,Z,Y)}async*runLoop($,J,Z){s.debug("Processing enhanced chat message...");let Y=J.systemPrompt??await this.buildSystemPromptOnDemand(J);return yield*this.executeLoop($,J,Z,Y)}async buildSystemPromptOnDemand($){let J=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await Z1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:J,append:Z,includeEnvironment:!0,environmentOptions:{...x1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,J,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return aY(Q,$,J,Z,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:J,result:Z})=>{let Y={id:J.toolCallId,type:"function",function:{name:J.toolName,arguments:JSON.stringify(J.input)}},Q=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0,X=Z.error===void 0,W=Z.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?Z.error?`Subagent execution failed: ${Z.error}.`:"":String(W),...Z.error?{error:{type:"execution_error",message:Z.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=nY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),J=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),Z=J&&J.state!=="none"?[{kind:"turn_recovery",assessment:J}]:[];return Z.push(...this.takeStartupAdoptedToolResultEvents()),Z}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,J,Z,Y)=>this.sessionRuntime.resolveContextualProjectRules($,J,Z,Y):void 0}}async chatWithSystem($,J){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:J}];return(await this.chatService.chat(Z)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let J=this.toolExecutor.getRegistry(),Y=J.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)J.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let J=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of J.getAll())if(Z.has(Y.name))J.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),J=new Map;return $.forEach((Z)=>{let Y=J.get(Z.kind)||0;J.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(J),toolNames:$.map((Z)=>Z.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,J){s.debug(`[MainAgent] ${$}`,J||"")}error($,J){s.error(`[MainAgent] ${$}`,J||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt,Z=await Z1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:J,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...x1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(Z.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await f6({sessionId:"default",configDir:e(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let J=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${J} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await X6({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let J=o0.createIsolated({artifactWriter:new o2(`legacy-${VG()}`)});this.legacyMcpRegistry=J;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await J.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let Z=this.toolExecutor.getRegistry();Z.setMcpCatalogBarrier(()=>J.waitForCatalogIdle());let Y=J.getCatalogSnapshot();Z.replaceMcpTools(Y.tools),Z.registerAll(Z4(J));let Q=J.getInstructionsSnapshot();if(Z.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),J.on("catalogChanged",(X)=>{Z.replaceMcpTools(X.tools,X)}),J.on("contentCatalogChanged",(X)=>{Z.queueMcpContentChange(X)}),J.on("resourceUpdated",(X)=>{Z.queueMcpResourceUpdated(X)}),J.on("connectionLifecycleChanged",(X)=>{Z.queueMcpConnectionChange(X)}),J.on("log",(X)=>{Z.queueMcpLog(X)}),J.on("instructionsChanged",(X)=>{Z.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await d0(C());if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let J=this.subagentRegistry.getAllNames().length;if(J>0)s.debug(`Loaded ${J} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let J=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${J.join(", ")}`);let Z=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return J.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let J=[];for(let Y of $)if(Y.type==="text")J.push(Y.text);if(J.length===0)return $;let Z=J.join(`
871
871
  `);try{let Y=await this.attachmentCollector.collect(Z);if(Y.length===0)return $;s.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return s.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let J=[],Z=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";J.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")J.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")Z.push(`- @${Q.path}: ${Q.error}`);let Y="";if(J.length>0)Y+=`
872
872
 
873
873
  <system-reminder>
@@ -1117,7 +1117,7 @@ ${H}
1117
1117
  `+` /model add
1118
1118
 
1119
1119
  `+`或运行初始化向导:
1120
- `+" /init");if(!B&&Q&&Q!=="inherit"&&!_.some((M)=>M.id===Q))Q=void 0;let A=await X6({workspaceRoot:F,...q?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:L.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...b.config,permissionMode:X??b.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:q?structuredClone(b.config.permissions):await O.loadWorkspacePermissions(F,b.config.permissions),hooks:q?{enabled:!1}:await O.loadWorkspaceHooks(F,b.config.hooks??{})};O.validateConfig(E,b.catalog);let j=new G1(E,{...$,modelResources:b,lspResources:N,mcpServers:A,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:W,serviceTier:V,responseVerbosity:U,communicationStyle:H,...z?{communicationStyleDigest:z}:{},...G?{projectInstructionsDigest:G}:{},...Z?{taskWorktree:Z}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(q){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(q instanceof h6)){let w=Z?await M$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await G1.persistTaskStatus($.sessionId,J,"failed","Session runtime initialization failed",w??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((L)=>{if(L.code!=="ENOENT")A0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,L)})}throw q}}static async hasPendingInbox($,J,Z=k$($)){if(await M1(Z,J,async({inboxPath:X})=>{try{return(await qX(X)).size>0}catch(W){if(W.code!=="ENOENT")throw W;return!1}}))return!0;if(Z.kind==="acp-remote")return!1;if(E0()?.agentTeamsEnabled!==!0)return!1;let Q=(await U$.getInstance(e()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===J&&X.workspaceRoot===$);for(let X of Q)if((await new V$(X.name,e()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,J,Z=k$($)){return M1(Z,J,async({inboxPath:Y})=>{try{return await qX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,J,Z=k$($)){return U0.hasActiveGoal($,J,Z)}static async hasRecoverableTurn($,J,Z=k$($)){return new w2($,void 0,Z).hasRecoverableTurn(J)}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}getModelById($){let J=this.config.models.find((Z)=>Z.id===$);return J?structuredClone(J):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return X2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=I1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let J=new Date().toISOString(),Z=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:Z?$.queuePosition??1:null,taskQueueDepth:Z?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...Z?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:J,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await o.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await o.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return V0.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:I1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let J=I1.getStats();V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:J.queued,taskConcurrencyLimit:J.maxConcurrent,taskInFlight:J.inFlight,taskAdmissionPaused:J.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($,J){let Z=this.providerRecovery.observe($,J);if(Z)this.publishProviderRecovery(Z);return Z}clearProviderRecovery($){let J=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(J)this.publishProviderRecovery(J);return J}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,J){let Z=this.turnActivity.observe($,J);if(Z)this.publishTurnActivity(Z);return Z}clearTurnActivity($){let J=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(J)this.publishTurnActivity(J);return J}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){V0.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"?o.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):o.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,J={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let Z=this.sideConversationOperations.enter(J.signal),Y=this.config.permissionMode??"default",Q;try{if(Z.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(Z.signal);let W=[this.loadModelContext(),Z1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:J.systemPrompt,append:J.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...x1,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}})],[V,U]=await Promise.all(W).catch(async(z)=>{throw await Promise.allSettled(W),z});if(Z.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let H=IX(U.prompt,X);if(!H)throw Error("Side conversation system prompt is empty");return await EZ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:H,messages:V,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:Z.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),Z.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return bJ(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 Z=(await this.loadModelContext()).findLast((W)=>W.role==="assistant"&&LX(W)?.turnId===$.turnId&&JSON.stringify(LX(W))===JSON.stringify($.finalization));if(!Z||typeof Z.content!=="string")return;let Y=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.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:Z.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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return J8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return J8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??CX}getProjectRuleCatalog(){return this.agentResources?.projectRules??TX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,J,Z,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let U=this.baseRegistry.get($)?.build(J);for(let H of U?.getAffectedPaths()??[])if(H)Q.add(H)}catch{}let X=(U)=>{if(typeof U==="string"&&U.trim())Q.add(U)};if(["Read","Edit","Write"].includes($))X(J.file_path);else if($==="NotebookEdit")X(J.notebook_path);else if(["Grep","Glob"].includes($))X(J.path);else if($==="Bash")X(J.cwd);let W=Z?.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0;if(Array.isArray(W?.affected_paths))for(let U of W.affected_paths)X(U);if(Array.isArray(W?.changes)){for(let U of W.changes)if(U&&typeof U==="object")X(U.path)}let V=[...Q].map((U)=>w0.isAbsolute(U)?w0.resolve(U):w0.resolve(this.workspaceRoot,U)).flatMap((U)=>{let H=w0.relative(this.workspaceRoot,U);if(H===""||!H.startsWith("..")&&!w0.isAbsolute(H))return[w0.resolve(this.projectRoot,H)];let z=w0.relative(this.projectRoot,U);return z===""||!z.startsWith("..")&&!w0.isAbsolute(z)?[U]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,V,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,J={}){try{let Z=await s4($,{configDir:e(),stateStorage:this.stateStorage}),Y=J.observeStall===!1&&$.frontierStall?.digestSha256===Z.frontier.digestSha256,Q=J.observeStall===!1?Y?$.frontierStall:void 0:kJ($.executionFrontier,Z.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(Z.frontier,Q,{preserveStall:Y}),...Z}}catch(Z){let Y=Z instanceof Error?Z.message:String(Z),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){A0.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($,J){if(this.options.subagentInfo)return;let Z=this.options.taskWorktree&&!["queued","running"].includes($)?await M$.getChangeSummary(this.sessionId):void 0;return G1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,J,Z??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,J,Z,Y,Q,X){let W=new Date().toISOString(),V=Z==="failed"&&Y!==void 0?Z8(Y):void 0,U=V?.message??(typeof Y==="string"?Y.slice(0,500):void 0),H={taskStatus:Z,taskStatusReason:U??null,taskFailure:V??null,...Q!==void 0?{taskDiffStat:Q}:Z==="running"?{taskDiffStat:null}:{},...Z!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...Z==="running"?{taskStartedAt:W,taskCompletedAt:null,taskOwnerPid:process.pid}:Z==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:W,taskOwnerPid:null}},z=X?await o.updateRemoteSessionMetadata($,J,X,H):await o.updateSessionMetadata($,J,H);return V0.publish({sessionId:$,projectPath:J},"task.status",{taskStatus:z.taskStatus,...U?{taskStatusReason:U}:{},...V?{taskFailure:V}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskCompletedAt?{taskCompletedAt:z.taskCompletedAt}:{},...z.taskDiffStat?{taskDiffStat:z.taskDiffStat}:{},...z.taskQueuePosition?{taskQueuePosition:z.taskQueuePosition}:{},...z.taskQueueDepth!==void 0?{taskQueueDepth:z.taskQueueDepth}:{},...z.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:z.taskConcurrencyLimit}:{},updatedAt:z.lastMessageTime}),z}createGoal($,J){return this.goalStore.create($,J)}async beginGoalTurn($){let J=this.getActiveTurnMailbox(),Z=await J.beginTurn(),Y=await this.goalStore.prepareTurnBinding(Z.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await J.finishTurn(Z).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(Z,"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:Z,goal:X}}catch(X){throw await this.releaseFailedTurnStart(Z,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(),o.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let J=await o.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),J}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($,J,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,J,Z)}async completeMcpArgument($,J,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,J,Z)}listMcpTasks($){return t0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return t0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,J){return t0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},J)}getMcpLogs($,J={}){return this.sessionMcpRegistry?.getLogSnapshot($,J)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,J)}resumeSubagent($){this.assertSubagentControlIdle();let J=D0.getInstance(),Z={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=J.getAgent($.agentId,Z);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 W=J.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:Z,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(U)=>{await this.notifyBackgroundSubagentCompleted(U.id),await $.onCompleted?.(U)}});if(!W)throw Error(`Subagent cannot be resumed: ${Y.id}`);let V=J.getAgent(W.agentId,Z);if(!V)throw Error(`Resumed subagent was not persisted: ${W.agentId}`);return{source:W.source,session:V}}async beginTurn($="goal"){let J=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(J,$),J}catch(Z){throw await this.getActiveTurnMailbox().finishTurn(J).catch(()=>{return}),Z}}async prepareInputTurn($,J){let Z=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,J?.metadata),Q=await Z.prepareInputTurn(Y.content,{...J,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let W=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await Z.reservedMessageIds(Q.handle),W?{goalId:W.goalId,...W.lineage}:void 0),X=!0,W&&!await this.goalStore.commitTurnBinding(W))throw Error("Goal changed before user turn lineage commit");return Q}catch(W){throw await this.releaseFailedTurnStart(Q.handle,X),W}}async enqueueSteering($,J){let Z=(J?.origin??"user")==="user"?await this.materializeUserMessage($,J?.metadata):{content:$,metadata:J?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(Z.content,{...J,...Z.metadata?{metadata:Z.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,J){return this.userPromptArtifactStore.materialize($,J)}restoreUserMessage($,J){return this.userPromptArtifactStore.restore($,J)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let J=this.startupTurnRecovery;if(!J||J.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let Z=await this.getClaimedTurnMessageIds($),Y=new Set(J.inputMessageIds);if(Z.length===0||Z.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:J.hadSuccessfulToolResult,...J.interruptedToolCallCount?{interruptedToolCallCount:J.interruptedToolCallCount}:{},...J.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:J.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),J=$.pendingMessages().map((Z)=>Z.id);if(J.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,J),await $.acknowledge(J)}async finishTurn($,J={}){let Z=J.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(Z.status==="completed"){let W=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:Z.turnsCount,toolCallsCount:Z.toolCallsCount,durationMs:Z.durationMs},W),await this.getActiveTurnMailbox().acknowledge(W)}else{let W=this.startupTurnRecovery,V=J.preserveStartupRecovery&&W?.outcome==="aborted"?{hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume,correctionSpent:W.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),U=await this.getActiveTurnMailbox().claimedMessageIds($),H=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:Z.cause,abortedAt:new Date().toISOString(),turnsCount:Z.turnsCount,toolCallsCount:Z.toolCallsCount,durationMs:Z.durationMs,recovery:{version:3,inputMessageIds:U,hadSuccessfulToolResult:V.hadSuccessfulToolResult,interruptedToolCallCount:V.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:V.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:V.correctionSpent}},J.acknowledgeInput?{acknowledgeInputMessageIds:U}:void 0);if(this.startupTurnRecovery=H.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(H.recovery?.inputMessageIds??[]),J.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(H.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,J);if(!Q)return;let X=!1;try{let W=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),W?{goalId:W.goalId,...W.lineage}:void 0),X=!0,W&&!await this.goalStore.commitTurnBinding(W))throw Error("Goal changed before pending turn lineage commit");return Q}catch(W){throw await this.releaseFailedTurnStart(Q,X),W}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),J=await $.beginPendingTurn();if(!J)return;let Z=!1;try{let Y=await this.goalStore.prepareTurnBinding(J.id,!1);if(await this.saveTurnStart(J,"pending",await $.reservedMessageIds(J),Y?{goalId:Y.goalId,...Y.lineage}:void 0),Z=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return J}catch(Y){throw await this.releaseFailedTurnStart(J,Z),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((J)=>J.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((J)=>J.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!t0.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await m3.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,J){while(!J?.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 Z=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(Z,J)}return!1}async hasUnclaimedPendingInput($){let J=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((Z)=>!J.has(Z.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,J){if(J?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((Z)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),J?.removeEventListener("abort",Q),Z()};if(this.backgroundSubagentCompletionWaiters.add(Q),J?.addEventListener("abort",Q,{once:!0}),J?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},J=v0.getInstance().listSessions().filter((Z)=>s0(Z,$)&&this.backgroundTaskChildIds.has(Z.id)&&Z.background===!0);if(J.some((Z)=>Z.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(Z.id)))return"terminal_pending";return J.some((Z)=>Z.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await m3.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let J=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let Z=v0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[Z.loadSession($)].filter((W)=>Boolean(W)):Z.listSessions().filter((W)=>s0(W,Y)),X=0;for(let W of Q){if(!this.backgroundTaskChildIds.has(W.id)||this.backgroundTaskCompletionSettledIds.has(W.id)||W.status==="running")continue;let V=W.resumedFrom?Z.loadSession(W.resumedFrom):void 0,U=aQ(W,Y,V);if(!U){this.backgroundTaskCompletionSettledIds.add(W.id);continue}let H=await J.persistBackgroundSubagentCompletion(this.sessionId,U);if(!H.eligible||H.acknowledged){this.backgroundTaskCompletionSettledIds.add(W.id);continue}let z=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(U);if(!z.accepted){A0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${W.id}`);continue}if(z.delivery==="current_turn"&&z.turnId)await this.goalStore.invalidateTurnLineageRoot(z.turnId);if(this.backgroundTaskCompletionSettledIds.add(W.id),z.duplicate)continue;if(X++,z.queue)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:z.queue});V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:W.id,inboxMessageId:U.inboxMessageId,status:W.status,type:W.subagentType,description:W.description,summary:U.subagentRef.subagentSummary,resumedFrom:W.resumedFrom,rootAgentId:W.rootAgentId,resumeDepth:W.resumeDepth,verificationVerdict:W.result?.verificationVerdict,queued:z.queued,delivery:z.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w4.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 U$.getInstance(e()).listTeams()).filter((J)=>J.deletedAt===void 0&&J.leadSessionId===this.sessionId&&J.workspaceRoot===this.workspaceRoot);for(let J of $){let Z=new V$(J.name,e()),Y=await Z.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(O2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:s6(Q)})).accepted)await Z.markDelivered([Q.id])}}async executeUserShellCommand($,J={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let Z=iD(12),Y=this.hasTurnOwner(),Q=J.signal??new AbortController().signal,X=async(B)=>{let D=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:Y}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:Y}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:Y,delivery:B.delivery,queued:B.queued};V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,D),await J.onEvent?.(B)},W=await SX($,{executionId:Z,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:J.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??s3():s3():this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await X({...B,auxiliary:Y})}}),V=kX(W),H=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",V,null,{...Y?{inboxMessageId:Z}:{},userShellCommand:JSON.parse(JSON.stringify(W))},this.options.subagentInfo),z=Y?await this.getActiveTurnMailbox().enqueue(V,{allowBeforeTurn:!0,messageId:Z,persisted:!0,origin:"user_shell"}):void 0;if(z?.delivery==="current_turn"&&z.turnId)await this.goalStore.invalidateTurnLineageRoot(z.turnId);let G={executionId:Z,messageId:H,record:W,modelContent:V,auxiliary:Y,...z?.delivery?{delivery:z.delivery}:{},...z?{queued:z.queued}:{},...z?.queue?{queue:z.queue}:{}};return await X({type:"completed",executionId:Z,messageId:H,record:W,auxiliary:Y,...z?.delivery?{delivery:z.delivery}:{},...z?{queued:z.queued}:{}}),G})}async initialize(){if(this.initialized)return;this.sessionLease=await g6.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new O1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await SZ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await rD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let V=y0.getInstance();if(V.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),V.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)V.inheritProjectConfig(this.projectRoot,this.workspaceRoot);V.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??V.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??V.getConfig(this.projectRoot));let U=await V.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!U.proceed)throw Error(U.warning||"SessionStart hook blocked initialization");if(U.warning)A0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${U.warning}`);let H=bX(U.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...H}),this.config.env=this.sessionEnvironment,V.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new r8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new g3({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w4.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 J=await $.loadInterruptedToolCalls(this.sessionId),Z=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let V=v0.getInstance();for(let U of J){if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))continue;let H=U.input.subagent_session_id;if(typeof H!=="string")continue;let z=V.loadSession(H);if(!z)continue;let G=KQ(U,z,Y);if(G)Z.set(U.toolCallId,G)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:Z});if(Q)this.startupAdoptedToolResults=J.flatMap((V)=>{let U=Z.get(V.toolCallId);return U?[{call:V,result:U}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),W=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(W?.finalized)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:W.goal});if(this.startupTurnRecovery=Q??(X&&W?.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)A0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,A0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(J){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,J)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let J=$.modelId==="inherit",Z=$.modelId&&!J?$.modelId:void 0,Y=J?this.getDefaultModel()?.id:Z??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,W=$.responseVerbosity??this.selectedResponseVerbosity,V=$.communicationStyle??this.selectedCommunicationStyle;if(J8(V,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||W!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,W);if(J)this.selectedModelId=void 0;else if(Z)this.selectedModelId=Z;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=W,this.selectedCommunicationStyle=V}createToolExecutor($={}){let J=new y1;J.setMcpCatalogBarrier(this.mcpCatalogBarrier);let Z="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,Z])]:void 0,Q=$.toolBlacklist?.filter((G)=>G!==Z),X=Y?new Set(Y):null,W=Q?new Set(Q):null;for(let G of this.baseRegistry.getBuiltinTools()){if(W?.has(G.name))continue;if(!X||X.has(G.name))J.register(G)}J.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,W));let V=this.getMcpInstructions();if(J.queueMcpInstructionsChange({revision:V.revision,reason:"snapshot",replace:!0,instructions:V.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((G)=>!W?.has(G)&&(!X||X.has(G))))for(let G of t0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:B,...D}=G;J.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(J,{allowed:X,blocked:W});let H={...this.config.permissions,...$.permissions},z=$.permissionMode??this.config.permissionMode??"default";return new X4(J,{permissionConfig:H,permissionMode:z,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:z,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(G)=>this.notifyBackgroundSubagentCompleted(G),registerBackgroundSubagent:(G)=>this.registerBackgroundSubagent(G)},...this.lspManager?{lspManager:this.lspManager}:{},...z==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(J)}})}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,J=async(L,O)=>{try{await O()}catch(F){$??=F,A0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${L} during cleanup`,F)}},Z=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,W=this.mcpResourceUpdatedListener,V=this.mcpConnectionListener,U=this.mcpLogListener,H=this.mcpInstructionsListener,z=this.mcpTaskListener,G=this.sessionLease,B=this.autoVerifyRuntime,D=this.lspManager,q=this.browserRuntime,w=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await J("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await J("close the Session browser",()=>q?.dispose()),await J("dispose the background subagent completion registration",()=>w?.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 y1,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 J("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await J("clear the session approvals",()=>this.approvalStore.clear()),await J("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await J("stop the session auto-verification processes",()=>B?.dispose()),await J("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await J("release the session hook model resources",()=>y0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await J("release the session worktrees",()=>M$.releaseSession(this.sessionId));if(await J("dispose the session chat service",()=>Z?.dispose?.()),await J("cancel the session MCP tasks",()=>t0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await J("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&W)Y.off("resourceUpdated",W);if(Y&&V)Y.off("connectionLifecycleChanged",V);if(Y&&U)Y.off("log",U);if(Y&&H)Y.off("instructionsChanged",H);if(z)t0.getInstance().off("taskChanged",z);await Y?.disconnectAll()}),await J("release the session lease",()=>G?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let J=$&&$!=="inherit"?$:void 0,Z=J?this.config.models.find((Y)=>Y.id===J):this.getDefaultModel();if(!Z)throw Error(`模型配置未找到: ${J??"current"}`);return Z}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($,J,Z=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:J,startedAt:new Date().toISOString(),...Z.length>0?{inputMessageIds:Z}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,J){if(J)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($,J,Z,Y,Q){let X=u0($,this.config,Z,this.modelResources.catalog,Y,Q);A0.debug(`${J} ${X.displayName} (${$.model})`);let W=X.model.contextWindow,V=await T6(X.chat),U=this.initialized?this.chatService:void 0,H=this.executionEngine?.getContextManager();this.chatService=V,this.executionEngine=new V4(V,H,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=W,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let z=U;try{await z?.dispose?.()}catch(G){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,G)}}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 J=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&J.source!=="built-in"&&this.options.communicationStyleDigest&&J.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&J.source!=="built-in"&&J.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:J.contentSha256}),this.options.communicationStyleDigest=J.contentSha256;try{await Z1({...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:{...x1,workingDirectory:this.executionRoot}})}catch(Z){A0.warn("[SessionRuntime] Failed to validate system prompt configuration:",Z)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await o.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await o.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(J){if(!(J instanceof vX||J.code==="ENOENT")||this.options.subagentInfo)throw J;await o.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new m8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:e(),stateStorage:this.stateStorage,exposeArtifactPaths:!H0(this.sessionId)});let $=await f6({sessionId:this.sessionId,configDir:e(),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}),J=cZ($.filter((Z)=>!Z.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(J),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let J=o0.createIsolated({roots:H0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!H0(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:e(),stateStorage:this.stateStorage,exposePaths:!H0(this.sessionId)}),exposeLogDetails:!H0(this.sessionId),exposeInstructions:!H0(this.sessionId)});this.sessionMcpRegistry=J,this.mcpCatalogBarrier=()=>J.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let Z=(H)=>{this.applyMcpCatalog(H,this.initialized)};this.mcpCatalogListener=Z,J.on("catalogChanged",Z);let Y=(H)=>{this.applyMcpContentCatalog(H)},Q=(H)=>{this.applyMcpResourceUpdated(H)},X=(H)=>{this.applyMcpConnectionChange(H)},W=(H)=>{this.applyMcpLog(H)},V=(H)=>{this.applyMcpInstructions(H)},U=(H)=>{if(H.owner.sessionId!==this.sessionId||w0.resolve(H.owner.projectPath)!==w0.resolve(this.workspaceRoot))return;this.applyMcpTask(H);let{owner:z,result:G,...B}=H;V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=W,this.mcpInstructionsListener=V,this.mcpTaskListener=U,J.on("contentCatalogChanged",Y),J.on("resourceUpdated",Q),J.on("connectionLifecycleChanged",X),J.on("log",W),J.on("instructionsChanged",V),t0.getInstance().on("taskChanged",U);for(let[H,z]of Object.entries($))try{let G=z.type==="stdio"?{...this.sessionEnvironment,...z.env}:void 0;await J.registerServer(H,z.type==="stdio"?{...z,...G&&Object.keys(G).length>0?{env:G}:{}}:z)}catch(G){A0.warn(`Warning: MCP server "${H}" connection failed:`,G)}this.baseRegistry.replaceMcpTools(J.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Z4(J)),this.baseRegistry.registerAll(V3(J))}catch($){A0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,J,Z){return $.filter((Y)=>!Z?.has(Y.name)&&(!J||J.has(Y.name)))}applyMcpCatalog($,J){this.baseRegistry.replaceMcpTools($.tools);for(let[Z,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(U)=>!Y.blocked?.has(U)&&(!Y.allowed||Y.allowed.has(U)),W={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},V=W.added.length>0||W.removed.length>0||W.updated.length>0;Z.replaceMcpTools(Q,J&&V?W:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let J=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[Z,Y]of this.executorCatalogs)if(J.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))Z.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[J,Z]of this.executorCatalogs)if(!Z.blocked?.has("ReadMcpResource")&&(!Z.allowed||Z.allowed.has("ReadMcpResource")))J.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.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:J,result:Z,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((V)=>!X.blocked?.has(V)&&(!X.allowed||X.allowed.has(V))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,J)=>{let Z=this.getChatService(),Y=await Z.chat($.messages,void 0,J,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return OX(Y,Z.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?RX(this.resourceRoot):await d0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function o3(){let $=await B0.getInstance().reload();N0().config.actions.setConfig($),await o0.getInstance().disconnectAll(),xX(),await d0(C())}import FF from"fuse.js";import p$ from"node:path";import{Mutex as nD}from"async-mutex";var c$=new nD;async function uX($){let J=$.getWorkspaceRoot();await R$(J,async(Z)=>{await $.reapplyEnabledSettings(),p1(J),await m1(J),await t3(Z)})}async function aD($){let J=$.getWorkspaceRoot();return R$(J,async(Z)=>{p1(J);let Y=await $.refresh();return await m1(J),await t3(Z),Y})}async function e3($){return R$($,async(J)=>{let Z=Array.from(new Set([J.plugins,...Q2.getInitializedInstances()])),Y;for(let Q of Z){let X=await aD(Q);if(Q===J.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function sD($,J){let Z=p$.resolve($),Y=v1();await Promise.all([Y.removePluginSetting(J,{scope:"global",immediate:!0}),Y.removePluginSetting(J,{scope:"project",projectDir:Z,immediate:!0}),Y.removePluginSetting(J,{scope:"local",projectDir:Z,immediate:!0})])}function oD($){return p$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function dX($,J){if(oD(J)&&!hX(await r0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function Y8($,J,Z,Y="local"){return c$.runExclusive(async()=>{let Q=p$.resolve($);return R$(Q,async(X)=>{let W=X.plugins.get(J);if(!W)throw Error(`Plugin not found: ${J}`);if(W.source==="cli")throw Error(`Plugin "${J}" was loaded with --plugin-dir and is invocation-scoped`);await v1().save({enabledPlugins:{[J]:Z}},{scope:Y,projectDir:Q,immediate:!0});let V=Y==="global"?Array.from(new Set([X.plugins,...Q2.getInitializedInstances()])):[X.plugins];for(let z of V)await uX(z);let U=X.plugins.get(J);if(!U)throw Error(`Plugin disappeared during reconciliation: ${J}`);let H=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:J,requestedEnabled:Z,effectiveEnabled:U.status==="active",scope:Y,source:U.source,status:U.status,effectiveScope:H.settings[J]?.effectiveScope??"default"}})})}async function Q8($){return c$.runExclusive(()=>R$($,async(J)=>{p1(J.workspaceRoot);let Z=await J.plugins.refresh();return await m1(J.workspaceRoot),{registry:J.plugins,discovery:Z}}))}async function $9($,J,Z="global"){return c$.runExclusive(async()=>{let Y=p$.resolve($),Q={...J,...gX(J)};return await v1().save({pluginSourcePolicy:Q},{scope:Z,projectDir:Y,immediate:!0}),R$(Y,async(X)=>{let W=Z==="global"?Array.from(new Set([X.plugins,...Q2.getInitializedInstances()])):[X.plugins];for(let V of W)await uX(V);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function J9($,J,Z={}){return c$.runExclusive(async()=>{let Y=p$.resolve($);await dX(Y,J);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await H$().install(J,{...Z,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let W=await e3(Y);return{result:X,discovery:W}})}async function Z9($,J,Z={}){return c$.runExclusive(async()=>{let Y=p$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await H$().update(J,{...Z,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let W=await e3(Y);return{result:X,discovery:W}})}async function Y9($,J,Z=!1){return c$.runExclusive(async()=>{let Y=p$.resolve($);return R$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((U)=>U.manifest.name!==J&&U.manifest.dependencies?.[J]!==void 0).map((U)=>U.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:J,code:"PLUGIN_REQUIRED",error:`Plugin "${J}" is required by: ${X.join(", ")}`}};let W=await H$().uninstall(J,Z);if(!W.success)return{result:W};await sD(Y,J);let V=await e3(Y);return{result:W,discovery:V}})})}async function Q9($,J,Z){return c$.runExclusive(async()=>{let Y=p$.resolve($);await dX(Y,J);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return H$().addMarketplace(J,{workspaceRoot:Y,ref:Z,policy:Q})})}async function X9($,J){return c$.runExclusive(async()=>{let Z=p$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(Z);return H$().refreshMarketplace(J,Y)})}async function W9($,J=!1){return c$.runExclusive(()=>H$().removeMarketplace($,J))}var tD={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($,J){let Z=$.join(" ").trim();if(!Z)return{success:!1,error:"Usage: /btw <question>"};if(!J.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await J.sideConversation.ask(Z,J.signal);return{success:!0,content:`**/btw** ${Z}
1120
+ `+" /init");if(!B&&Q&&Q!=="inherit"&&!_.some((M)=>M.id===Q))Q=void 0;let A=await X6({workspaceRoot:F,...q?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:L.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...b.config,permissionMode:X??b.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:q?structuredClone(b.config.permissions):await O.loadWorkspacePermissions(F,b.config.permissions),hooks:q?{enabled:!1}:await O.loadWorkspaceHooks(F,b.config.hooks??{})};O.validateConfig(E,b.catalog);let j=new G1(E,{...$,modelResources:b,lspResources:N,mcpServers:A,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:W,serviceTier:V,responseVerbosity:U,communicationStyle:H,...z?{communicationStyleDigest:z}:{},...G?{projectInstructionsDigest:G}:{},...Z?{taskWorktree:Z}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(q){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(q instanceof h6)){let w=Z?await M$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await G1.persistTaskStatus($.sessionId,J,"failed","Session runtime initialization failed",w??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((L)=>{if(L.code!=="ENOENT")A0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,L)})}throw q}}static async hasPendingInbox($,J,Z=k$($)){if(await M1(Z,J,async({inboxPath:X})=>{try{return(await qX(X)).size>0}catch(W){if(W.code!=="ENOENT")throw W;return!1}}))return!0;if(Z.kind==="acp-remote")return!1;if(E0()?.agentTeamsEnabled!==!0)return!1;let Q=(await U$.getInstance(e()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===J&&X.workspaceRoot===$);for(let X of Q)if((await new V$(X.name,e()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,J,Z=k$($)){return M1(Z,J,async({inboxPath:Y})=>{try{return await qX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,J,Z=k$($)){return U0.hasActiveGoal($,J,Z)}static async hasRecoverableTurn($,J,Z=k$($)){return new w2($,void 0,Z).hasRecoverableTurn(J)}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}getModelById($){let J=this.config.models.find((Z)=>Z.id===$);return J?structuredClone(J):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return X2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=I1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let J=new Date().toISOString(),Z=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:Z?$.queuePosition??1:null,taskQueueDepth:Z?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...Z?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:J,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await o.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await o.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return V0.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:I1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let J=I1.getStats();V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:J.queued,taskConcurrencyLimit:J.maxConcurrent,taskInFlight:J.inFlight,taskAdmissionPaused:J.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($,J){let Z=this.providerRecovery.observe($,J);if(Z)this.publishProviderRecovery(Z);return Z}clearProviderRecovery($){let J=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(J)this.publishProviderRecovery(J);return J}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,J){let Z=this.turnActivity.observe($,J);if(Z)this.publishTurnActivity(Z);return Z}clearTurnActivity($){let J=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(J)this.publishTurnActivity(J);return J}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){V0.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"?o.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):o.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,J={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let Z=this.sideConversationOperations.enter(J.signal),Y=this.config.permissionMode??"default",Q;try{if(Z.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(Z.signal);let W=[this.loadModelContext(),Z1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:J.systemPrompt,append:J.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...x1,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}})],[V,U]=await Promise.all(W).catch(async(z)=>{throw await Promise.allSettled(W),z});if(Z.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let H=IX(U.prompt,X);if(!H)throw Error("Side conversation system prompt is empty");return await EZ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:H,messages:V,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:Z.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),Z.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return bJ(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 Z=(await this.loadModelContext()).findLast((W)=>W.role==="assistant"&&LX(W)?.turnId===$.turnId&&JSON.stringify(LX(W))===JSON.stringify($.finalization));if(!Z||typeof Z.content!=="string")return;let Y=Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.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:Z.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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),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($,J=this.currentModelId){return u0(this.resolveModelConfig(J),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return J8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return J8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??CX}getProjectRuleCatalog(){return this.agentResources?.projectRules??TX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,J,Z,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let U=this.baseRegistry.get($)?.build(J);for(let H of U?.getAffectedPaths()??[])if(H)Q.add(H)}catch{}let X=(U)=>{if(typeof U==="string"&&U.trim())Q.add(U)};if(["Read","Edit","Write"].includes($))X(J.file_path);else if($==="NotebookEdit")X(J.notebook_path);else if(["Grep","Glob"].includes($))X(J.path);else if($==="Bash")X(J.cwd);let W=Z?.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0;if(Array.isArray(W?.affected_paths))for(let U of W.affected_paths)X(U);if(Array.isArray(W?.changes)){for(let U of W.changes)if(U&&typeof U==="object")X(U.path)}let V=[...Q].map((U)=>w0.isAbsolute(U)?w0.resolve(U):w0.resolve(this.workspaceRoot,U)).flatMap((U)=>{let H=w0.relative(this.workspaceRoot,U);if(H===""||!H.startsWith("..")&&!w0.isAbsolute(H))return[w0.resolve(this.projectRoot,H)];let z=w0.relative(this.projectRoot,U);return z===""||!z.startsWith("..")&&!w0.isAbsolute(z)?[U]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,V,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,J={}){try{let Z=await s4($,{configDir:e(),stateStorage:this.stateStorage}),Y=J.observeStall===!1&&$.frontierStall?.digestSha256===Z.frontier.digestSha256,Q=J.observeStall===!1?Y?$.frontierStall:void 0:kJ($.executionFrontier,Z.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(Z.frontier,Q,{preserveStall:Y}),...Z}}catch(Z){let Y=Z instanceof Error?Z.message:String(Z),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){A0.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($,J){if(this.options.subagentInfo)return;let Z=this.options.taskWorktree&&!["queued","running"].includes($)?await M$.getChangeSummary(this.sessionId):void 0;return G1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,J,Z??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,J,Z,Y,Q,X){let W=new Date().toISOString(),V=Z==="failed"&&Y!==void 0?Z8(Y):void 0,U=V?.message??(typeof Y==="string"?Y.slice(0,500):void 0),H={taskStatus:Z,taskStatusReason:U??null,taskFailure:V??null,...Q!==void 0?{taskDiffStat:Q}:Z==="running"?{taskDiffStat:null}:{},...Z!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...Z==="running"?{taskStartedAt:W,taskCompletedAt:null,taskOwnerPid:process.pid}:Z==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:W,taskOwnerPid:null}},z=X?await o.updateRemoteSessionMetadata($,J,X,H):await o.updateSessionMetadata($,J,H);return V0.publish({sessionId:$,projectPath:J},"task.status",{taskStatus:z.taskStatus,...U?{taskStatusReason:U}:{},...V?{taskFailure:V}:{},...z.taskStartedAt?{taskStartedAt:z.taskStartedAt}:{},...z.taskCompletedAt?{taskCompletedAt:z.taskCompletedAt}:{},...z.taskDiffStat?{taskDiffStat:z.taskDiffStat}:{},...z.taskQueuePosition?{taskQueuePosition:z.taskQueuePosition}:{},...z.taskQueueDepth!==void 0?{taskQueueDepth:z.taskQueueDepth}:{},...z.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:z.taskConcurrencyLimit}:{},updatedAt:z.lastMessageTime}),z}createGoal($,J){return this.goalStore.create($,J)}async beginGoalTurn($){let J=this.getActiveTurnMailbox(),Z=await J.beginTurn(),Y=await this.goalStore.prepareTurnBinding(Z.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await J.finishTurn(Z).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(Z,"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:Z,goal:X}}catch(X){throw await this.releaseFailedTurnStart(Z,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(),o.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let J=await o.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),J}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($,J,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,J,Z)}async completeMcpArgument($,J,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,J,Z)}listMcpTasks($){return t0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return t0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,J){return t0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},J)}getMcpLogs($,J={}){return this.sessionMcpRegistry?.getLogSnapshot($,J)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,J)}resumeSubagent($){this.assertSubagentControlIdle();let J=D0.getInstance(),Z={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=J.getAgent($.agentId,Z);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 W=J.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:Z,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(U)=>{await this.notifyBackgroundSubagentCompleted(U.id),await $.onCompleted?.(U)}});if(!W)throw Error(`Subagent cannot be resumed: ${Y.id}`);let V=J.getAgent(W.agentId,Z);if(!V)throw Error(`Resumed subagent was not persisted: ${W.agentId}`);return{source:W.source,session:V}}async beginTurn($="goal"){let J=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(J,$),J}catch(Z){throw await this.getActiveTurnMailbox().finishTurn(J).catch(()=>{return}),Z}}async prepareInputTurn($,J){let Z=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,J?.metadata),Q=await Z.prepareInputTurn(Y.content,{...J,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let W=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await Z.reservedMessageIds(Q.handle),W?{goalId:W.goalId,...W.lineage}:void 0),X=!0,W&&!await this.goalStore.commitTurnBinding(W))throw Error("Goal changed before user turn lineage commit");return Q}catch(W){throw await this.releaseFailedTurnStart(Q.handle,X),W}}async enqueueSteering($,J){let Z=(J?.origin??"user")==="user"?await this.materializeUserMessage($,J?.metadata):{content:$,metadata:J?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(Z.content,{...J,...Z.metadata?{metadata:Z.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,J){return this.userPromptArtifactStore.materialize($,J)}restoreUserMessage($,J){return this.userPromptArtifactStore.restore($,J)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let J=this.startupTurnRecovery;if(!J||J.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let Z=await this.getClaimedTurnMessageIds($),Y=new Set(J.inputMessageIds);if(Z.length===0||Z.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:J.hadSuccessfulToolResult,...J.interruptedToolCallCount?{interruptedToolCallCount:J.interruptedToolCallCount}:{},...J.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:J.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),J=$.pendingMessages().map((Z)=>Z.id);if(J.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,J),await $.acknowledge(J)}async finishTurn($,J={}){let Z=J.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(Z.status==="completed"){let W=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:Z.turnsCount,toolCallsCount:Z.toolCallsCount,durationMs:Z.durationMs,...Z.usage?{usage:Z.usage}:{}},W),await this.getActiveTurnMailbox().acknowledge(W)}else{let W=this.startupTurnRecovery,V=J.preserveStartupRecovery&&W?.outcome==="aborted"?{hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume,correctionSpent:W.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),U=await this.getActiveTurnMailbox().claimedMessageIds($),H=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:Z.cause,abortedAt:new Date().toISOString(),turnsCount:Z.turnsCount,toolCallsCount:Z.toolCallsCount,durationMs:Z.durationMs,...Z.usage?{usage:Z.usage}:{},recovery:{version:3,inputMessageIds:U,hadSuccessfulToolResult:V.hadSuccessfulToolResult,interruptedToolCallCount:V.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:V.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:V.correctionSpent}},J.acknowledgeInput?{acknowledgeInputMessageIds:U}:void 0);if(this.startupTurnRecovery=H.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(H.recovery?.inputMessageIds??[]),J.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(H.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,J);if(!Q)return;let X=!1;try{let W=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),W?{goalId:W.goalId,...W.lineage}:void 0),X=!0,W&&!await this.goalStore.commitTurnBinding(W))throw Error("Goal changed before pending turn lineage commit");return Q}catch(W){throw await this.releaseFailedTurnStart(Q,X),W}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),J=await $.beginPendingTurn();if(!J)return;let Z=!1;try{let Y=await this.goalStore.prepareTurnBinding(J.id,!1);if(await this.saveTurnStart(J,"pending",await $.reservedMessageIds(J),Y?{goalId:Y.goalId,...Y.lineage}:void 0),Z=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return J}catch(Y){throw await this.releaseFailedTurnStart(J,Z),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((J)=>J.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((J)=>J.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!t0.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await m3.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,J){while(!J?.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 Z=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(Z,J)}return!1}async hasUnclaimedPendingInput($){let J=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((Z)=>!J.has(Z.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,J){if(J?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((Z)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),J?.removeEventListener("abort",Q),Z()};if(this.backgroundSubagentCompletionWaiters.add(Q),J?.addEventListener("abort",Q,{once:!0}),J?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},J=v0.getInstance().listSessions().filter((Z)=>s0(Z,$)&&this.backgroundTaskChildIds.has(Z.id)&&Z.background===!0);if(J.some((Z)=>Z.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(Z.id)))return"terminal_pending";return J.some((Z)=>Z.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await m3.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let J=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let Z=v0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[Z.loadSession($)].filter((W)=>Boolean(W)):Z.listSessions().filter((W)=>s0(W,Y)),X=0;for(let W of Q){if(!this.backgroundTaskChildIds.has(W.id)||this.backgroundTaskCompletionSettledIds.has(W.id)||W.status==="running")continue;let V=W.resumedFrom?Z.loadSession(W.resumedFrom):void 0,U=aQ(W,Y,V);if(!U){this.backgroundTaskCompletionSettledIds.add(W.id);continue}let H=await J.persistBackgroundSubagentCompletion(this.sessionId,U);if(!H.eligible||H.acknowledged){this.backgroundTaskCompletionSettledIds.add(W.id);continue}let z=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(U);if(!z.accepted){A0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${W.id}`);continue}if(z.delivery==="current_turn"&&z.turnId)await this.goalStore.invalidateTurnLineageRoot(z.turnId);if(this.backgroundTaskCompletionSettledIds.add(W.id),z.duplicate)continue;if(X++,z.queue)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:z.queue});V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:W.id,inboxMessageId:U.inboxMessageId,status:W.status,type:W.subagentType,description:W.description,summary:U.subagentRef.subagentSummary,resumedFrom:W.resumedFrom,rootAgentId:W.rootAgentId,resumeDepth:W.resumeDepth,verificationVerdict:W.result?.verificationVerdict,queued:z.queued,delivery:z.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w4.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 U$.getInstance(e()).listTeams()).filter((J)=>J.deletedAt===void 0&&J.leadSessionId===this.sessionId&&J.workspaceRoot===this.workspaceRoot);for(let J of $){let Z=new V$(J.name,e()),Y=await Z.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(O2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:s6(Q)})).accepted)await Z.markDelivered([Q.id])}}async executeUserShellCommand($,J={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let Z=iD(12),Y=this.hasTurnOwner(),Q=J.signal??new AbortController().signal,X=async(B)=>{let D=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:Y}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:Y}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:Y,delivery:B.delivery,queued:B.queued};V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,D),await J.onEvent?.(B)},W=await SX($,{executionId:Z,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:J.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??s3():s3():this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await X({...B,auxiliary:Y})}}),V=kX(W),H=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",V,null,{...Y?{inboxMessageId:Z}:{},userShellCommand:JSON.parse(JSON.stringify(W))},this.options.subagentInfo),z=Y?await this.getActiveTurnMailbox().enqueue(V,{allowBeforeTurn:!0,messageId:Z,persisted:!0,origin:"user_shell"}):void 0;if(z?.delivery==="current_turn"&&z.turnId)await this.goalStore.invalidateTurnLineageRoot(z.turnId);let G={executionId:Z,messageId:H,record:W,modelContent:V,auxiliary:Y,...z?.delivery?{delivery:z.delivery}:{},...z?{queued:z.queued}:{},...z?.queue?{queue:z.queue}:{}};return await X({type:"completed",executionId:Z,messageId:H,record:W,auxiliary:Y,...z?.delivery?{delivery:z.delivery}:{},...z?{queued:z.queued}:{}}),G})}async initialize(){if(this.initialized)return;this.sessionLease=await g6.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new O1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await SZ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await rD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let V=y0.getInstance();if(V.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),V.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)V.inheritProjectConfig(this.projectRoot,this.workspaceRoot);V.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??V.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??V.getConfig(this.projectRoot));let U=await V.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!U.proceed)throw Error(U.warning||"SessionStart hook blocked initialization");if(U.warning)A0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${U.warning}`);let H=bX(U.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...H}),this.config.env=this.sessionEnvironment,V.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new r8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new g3({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w4.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 J=await $.loadInterruptedToolCalls(this.sessionId),Z=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let V=v0.getInstance();for(let U of J){if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))continue;let H=U.input.subagent_session_id;if(typeof H!=="string")continue;let z=V.loadSession(H);if(!z)continue;let G=KQ(U,z,Y);if(G)Z.set(U.toolCallId,G)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:Z});if(Q)this.startupAdoptedToolResults=J.flatMap((V)=>{let U=Z.get(V.toolCallId);return U?[{call:V,result:U}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),W=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(W?.finalized)V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:W.goal});if(this.startupTurnRecovery=Q??(X&&W?.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)A0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,A0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(J){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,J)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let J=$.modelId==="inherit",Z=$.modelId&&!J?$.modelId:void 0,Y=J?this.getDefaultModel()?.id:Z??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,W=$.responseVerbosity??this.selectedResponseVerbosity,V=$.communicationStyle??this.selectedCommunicationStyle;if(J8(V,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||W!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,W);if(J)this.selectedModelId=void 0;else if(Z)this.selectedModelId=Z;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=W,this.selectedCommunicationStyle=V}createToolExecutor($={}){let J=new y1;J.setMcpCatalogBarrier(this.mcpCatalogBarrier);let Z="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,Z])]:void 0,Q=$.toolBlacklist?.filter((G)=>G!==Z),X=Y?new Set(Y):null,W=Q?new Set(Q):null;for(let G of this.baseRegistry.getBuiltinTools()){if(W?.has(G.name))continue;if(!X||X.has(G.name))J.register(G)}J.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,W));let V=this.getMcpInstructions();if(J.queueMcpInstructionsChange({revision:V.revision,reason:"snapshot",replace:!0,instructions:V.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((G)=>!W?.has(G)&&(!X||X.has(G))))for(let G of t0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:B,...D}=G;J.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(J,{allowed:X,blocked:W});let H={...this.config.permissions,...$.permissions},z=$.permissionMode??this.config.permissionMode??"default";return new X4(J,{permissionConfig:H,permissionMode:z,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:z,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(G)=>this.notifyBackgroundSubagentCompleted(G),registerBackgroundSubagent:(G)=>this.registerBackgroundSubagent(G)},...this.lspManager?{lspManager:this.lspManager}:{},...z==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(J)}})}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,J=async(L,O)=>{try{await O()}catch(F){$??=F,A0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${L} during cleanup`,F)}},Z=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,W=this.mcpResourceUpdatedListener,V=this.mcpConnectionListener,U=this.mcpLogListener,H=this.mcpInstructionsListener,z=this.mcpTaskListener,G=this.sessionLease,B=this.autoVerifyRuntime,D=this.lspManager,q=this.browserRuntime,w=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await J("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await J("close the Session browser",()=>q?.dispose()),await J("dispose the background subagent completion registration",()=>w?.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 y1,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 J("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await J("clear the session approvals",()=>this.approvalStore.clear()),await J("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await J("stop the session auto-verification processes",()=>B?.dispose()),await J("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await J("release the session hook model resources",()=>y0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await J("release the session worktrees",()=>M$.releaseSession(this.sessionId));if(await J("dispose the session chat service",()=>Z?.dispose?.()),await J("cancel the session MCP tasks",()=>t0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await J("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&W)Y.off("resourceUpdated",W);if(Y&&V)Y.off("connectionLifecycleChanged",V);if(Y&&U)Y.off("log",U);if(Y&&H)Y.off("instructionsChanged",H);if(z)t0.getInstance().off("taskChanged",z);await Y?.disconnectAll()}),await J("release the session lease",()=>G?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let J=$&&$!=="inherit"?$:void 0,Z=J?this.config.models.find((Y)=>Y.id===J):this.getDefaultModel();if(!Z)throw Error(`模型配置未找到: ${J??"current"}`);return Z}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($,J,Z=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:J,startedAt:new Date().toISOString(),...Z.length>0?{inputMessageIds:Z}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,J){if(J)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($,J,Z,Y,Q){let X=u0($,this.config,Z,this.modelResources.catalog,Y,Q);A0.debug(`${J} ${X.displayName} (${$.model})`);let W=X.model.contextWindow,V=await T6(X.chat),U=this.initialized?this.chatService:void 0,H=this.executionEngine?.getContextManager();this.chatService=V,this.executionEngine=new V4(V,H,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=W,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let z=U;try{await z?.dispose?.()}catch(G){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,G)}}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 J=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&J.source!=="built-in"&&this.options.communicationStyleDigest&&J.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&J.source!=="built-in"&&J.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:J.contentSha256}),this.options.communicationStyleDigest=J.contentSha256;try{await Z1({...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:{...x1,workingDirectory:this.executionRoot}})}catch(Z){A0.warn("[SessionRuntime] Failed to validate system prompt configuration:",Z)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await o.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await o.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(J){if(!(J instanceof vX||J.code==="ENOENT")||this.options.subagentInfo)throw J;await o.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new m8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:e(),stateStorage:this.stateStorage,exposeArtifactPaths:!H0(this.sessionId)});let $=await f6({sessionId:this.sessionId,configDir:e(),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}),J=cZ($.filter((Z)=>!Z.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(J),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let J=o0.createIsolated({roots:H0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!H0(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:e(),stateStorage:this.stateStorage,exposePaths:!H0(this.sessionId)}),exposeLogDetails:!H0(this.sessionId),exposeInstructions:!H0(this.sessionId)});this.sessionMcpRegistry=J,this.mcpCatalogBarrier=()=>J.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let Z=(H)=>{this.applyMcpCatalog(H,this.initialized)};this.mcpCatalogListener=Z,J.on("catalogChanged",Z);let Y=(H)=>{this.applyMcpContentCatalog(H)},Q=(H)=>{this.applyMcpResourceUpdated(H)},X=(H)=>{this.applyMcpConnectionChange(H)},W=(H)=>{this.applyMcpLog(H)},V=(H)=>{this.applyMcpInstructions(H)},U=(H)=>{if(H.owner.sessionId!==this.sessionId||w0.resolve(H.owner.projectPath)!==w0.resolve(this.workspaceRoot))return;this.applyMcpTask(H);let{owner:z,result:G,...B}=H;V0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=W,this.mcpInstructionsListener=V,this.mcpTaskListener=U,J.on("contentCatalogChanged",Y),J.on("resourceUpdated",Q),J.on("connectionLifecycleChanged",X),J.on("log",W),J.on("instructionsChanged",V),t0.getInstance().on("taskChanged",U);for(let[H,z]of Object.entries($))try{let G=z.type==="stdio"?{...this.sessionEnvironment,...z.env}:void 0;await J.registerServer(H,z.type==="stdio"?{...z,...G&&Object.keys(G).length>0?{env:G}:{}}:z)}catch(G){A0.warn(`Warning: MCP server "${H}" connection failed:`,G)}this.baseRegistry.replaceMcpTools(J.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Z4(J)),this.baseRegistry.registerAll(V3(J))}catch($){A0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,J,Z){return $.filter((Y)=>!Z?.has(Y.name)&&(!J||J.has(Y.name)))}applyMcpCatalog($,J){this.baseRegistry.replaceMcpTools($.tools);for(let[Z,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(U)=>!Y.blocked?.has(U)&&(!Y.allowed||Y.allowed.has(U)),W={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},V=W.added.length>0||W.removed.length>0||W.updated.length>0;Z.replaceMcpTools(Q,J&&V?W:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let J=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[Z,Y]of this.executorCatalogs)if(J.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))Z.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[J,Z]of this.executorCatalogs)if(!Z.blocked?.has("ReadMcpResource")&&(!Z.allowed||Z.allowed.has("ReadMcpResource")))J.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let J of this.executorCatalogs.keys())J.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:J,result:Z,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((V)=>!X.blocked?.has(V)&&(!X.allowed||X.allowed.has(V))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,J)=>{let Z=this.getChatService(),Y=await Z.chat($.messages,void 0,J,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return OX(Y,Z.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?RX(this.resourceRoot):await d0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=R6($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function o3(){let $=await B0.getInstance().reload();N0().config.actions.setConfig($),await o0.getInstance().disconnectAll(),xX(),await d0(C())}import FF from"fuse.js";import p$ from"node:path";import{Mutex as nD}from"async-mutex";var c$=new nD;async function uX($){let J=$.getWorkspaceRoot();await R$(J,async(Z)=>{await $.reapplyEnabledSettings(),p1(J),await m1(J),await t3(Z)})}async function aD($){let J=$.getWorkspaceRoot();return R$(J,async(Z)=>{p1(J);let Y=await $.refresh();return await m1(J),await t3(Z),Y})}async function e3($){return R$($,async(J)=>{let Z=Array.from(new Set([J.plugins,...Q2.getInitializedInstances()])),Y;for(let Q of Z){let X=await aD(Q);if(Q===J.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function sD($,J){let Z=p$.resolve($),Y=v1();await Promise.all([Y.removePluginSetting(J,{scope:"global",immediate:!0}),Y.removePluginSetting(J,{scope:"project",projectDir:Z,immediate:!0}),Y.removePluginSetting(J,{scope:"local",projectDir:Z,immediate:!0})])}function oD($){return p$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function dX($,J){if(oD(J)&&!hX(await r0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function Y8($,J,Z,Y="local"){return c$.runExclusive(async()=>{let Q=p$.resolve($);return R$(Q,async(X)=>{let W=X.plugins.get(J);if(!W)throw Error(`Plugin not found: ${J}`);if(W.source==="cli")throw Error(`Plugin "${J}" was loaded with --plugin-dir and is invocation-scoped`);await v1().save({enabledPlugins:{[J]:Z}},{scope:Y,projectDir:Q,immediate:!0});let V=Y==="global"?Array.from(new Set([X.plugins,...Q2.getInitializedInstances()])):[X.plugins];for(let z of V)await uX(z);let U=X.plugins.get(J);if(!U)throw Error(`Plugin disappeared during reconciliation: ${J}`);let H=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:J,requestedEnabled:Z,effectiveEnabled:U.status==="active",scope:Y,source:U.source,status:U.status,effectiveScope:H.settings[J]?.effectiveScope??"default"}})})}async function Q8($){return c$.runExclusive(()=>R$($,async(J)=>{p1(J.workspaceRoot);let Z=await J.plugins.refresh();return await m1(J.workspaceRoot),{registry:J.plugins,discovery:Z}}))}async function $9($,J,Z="global"){return c$.runExclusive(async()=>{let Y=p$.resolve($),Q={...J,...gX(J)};return await v1().save({pluginSourcePolicy:Q},{scope:Z,projectDir:Y,immediate:!0}),R$(Y,async(X)=>{let W=Z==="global"?Array.from(new Set([X.plugins,...Q2.getInitializedInstances()])):[X.plugins];for(let V of W)await uX(V);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function J9($,J,Z={}){return c$.runExclusive(async()=>{let Y=p$.resolve($);await dX(Y,J);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await H$().install(J,{...Z,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let W=await e3(Y);return{result:X,discovery:W}})}async function Z9($,J,Z={}){return c$.runExclusive(async()=>{let Y=p$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await H$().update(J,{...Z,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let W=await e3(Y);return{result:X,discovery:W}})}async function Y9($,J,Z=!1){return c$.runExclusive(async()=>{let Y=p$.resolve($);return R$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((U)=>U.manifest.name!==J&&U.manifest.dependencies?.[J]!==void 0).map((U)=>U.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:J,code:"PLUGIN_REQUIRED",error:`Plugin "${J}" is required by: ${X.join(", ")}`}};let W=await H$().uninstall(J,Z);if(!W.success)return{result:W};await sD(Y,J);let V=await e3(Y);return{result:W,discovery:V}})})}async function Q9($,J,Z){return c$.runExclusive(async()=>{let Y=p$.resolve($);await dX(Y,J);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return H$().addMarketplace(J,{workspaceRoot:Y,ref:Z,policy:Q})})}async function X9($,J){return c$.runExclusive(async()=>{let Z=p$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(Z);return H$().refreshMarketplace(J,Y)})}async function W9($,J=!1){return c$.runExclusive(()=>H$().removeMarketplace($,J))}var tD={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($,J){let Z=$.join(" ").trim();if(!Z)return{success:!1,error:"Usage: /btw <question>"};if(!J.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await J.sideConversation.ask(Z,J.signal);return{success:!0,content:`**/btw** ${Z}
1121
1121
 
1122
1122
  ${Y.response}`,data:{action:"show_side_conversation",question:Z,response:Y.response,durationMs:Y.durationMs,usage:Y.usage}}}},mX=tD;import TW from"node:fs/promises";import RW from"node:path";function V9($){return Number.isFinite($)?Math.max(0,$):0}function pX($){let J=V9($.totalInputTokens),Z=V9($.cacheReadTokens),Y=V9($.cacheWriteTokens),Q=Math.min(Z,J),X=Math.min(Y,Math.max(0,J-Q)),W=Math.max(0,J-Q-X),V=J>0&&(Z>0||Y>0);return{totalInputTokens:J,cacheReadTokens:Q,cacheWriteTokens:X,uncachedInputTokens:W,...V?{hitRate:Q/J}:{}}}function cX($){if($===void 0||!Number.isFinite($))return"—";return`${Math.round(Math.max(0,Math.min(1,$))*100)}%`}function lX($){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 W8($,J,Z={}){let Y=Date.now(),Q=Z.timeoutMs??20000,X="unknown";try{let W=u0($,J,"off");X=W.model.api;let U=await new iX({...W.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(U.content||U.reasoningContent||U.finishReason||U.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(W){let V=Z8(W);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:V.code,message:V.message}}}import $q from"node:os";import rX from"node:path";var U9=Object.freeze(["help","version","btw","effort","speed","verbosity","style"]),eD=new Set(U9);function H9($){return eD.has($)}function i($){if($.acp)return{sendMessage:(J)=>$.acp.sendMessage(`• ${J}
1123
1123
 
@@ -1684,7 +1684,7 @@ ${Z}
1684
1684
  `)),{success:!0,message:"Schedules listed",content:U.join(`
1685
1685
  `)}}case"create":{let V=ew(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let U={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(U),z=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1686
1686
  ${b9(H.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let z=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let U=await $.remove(V);return Y.sendMessage(U?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:U,message:U?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let U=await $.setEnabled(V,Q==="enable");return Y.sendMessage(U?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(U),message:U?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await $F(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
1687
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var ZV=JF();import*as R2 from"node:fs/promises";import*as f2 from"node:path";async function VV($,J={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=J,W=X??f4(Q??C());if(!X){let B=await ZF($,Q??C(),Z,Y);if(B)return B}let V;try{V=(await R2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>f2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(B)=>{try{let D=await R2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of H){if(z.length>=Z)break;let D=f2.basename(B,".jsonl"),q=await YF(B,G,Y,D);if(z.push(...q),z.length>=Z){z.length=Z;break}}return z}async function ZF($,J,Z,Y){try{let{syncAll:Q}=await import("./chunk-p36k2e96.js"),X=await XV();if(!X)return null;let{SessionService:W}=await import("./chunk-qyfbeg5h.js");await Q(X,W.projectionDeriverForSearch());let V=f2.resolve(J),U=WV(X,$,V,Z*4),H=Y?$:$.toLowerCase(),z=[];for(let G of U){if(G.role!=="user"&&G.role!=="assistant")continue;let B=j9(G.text,H,Y,G.session_id,G.role,G.timestamp??void 0,0);if(B)z.push(B);if(z.length>=Z)break}return z}catch{return null}}async function YF($,J,Z,Y){try{let Q=await R2.readFile($,"utf8"),W=Q.split(`
1687
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var ZV=JF();import*as R2 from"node:fs/promises";import*as f2 from"node:path";async function VV($,J={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=J,W=X??f4(Q??C());if(!X){let B=await ZF($,Q??C(),Z,Y);if(B)return B}let V;try{V=(await R2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>f2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(B)=>{try{let D=await R2.stat(B);return{path:B,mtime:D.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,D)=>D.mtime-B.mtime).map((B)=>B.path),z=[],G=Y?$:$.toLowerCase();for(let B of H){if(z.length>=Z)break;let D=f2.basename(B,".jsonl"),q=await YF(B,G,Y,D);if(z.push(...q),z.length>=Z){z.length=Z;break}}return z}async function ZF($,J,Z,Y){try{let{syncAll:Q}=await import("./chunk-p36k2e96.js"),X=await XV();if(!X)return null;let{SessionService:W}=await import("./chunk-mmpcq1yh.js");await Q(X,W.projectionDeriverForSearch());let V=f2.resolve(J),U=WV(X,$,V,Z*4),H=Y?$:$.toLowerCase(),z=[];for(let G of U){if(G.role!=="user"&&G.role!=="assistant")continue;let B=j9(G.text,H,Y,G.session_id,G.role,G.timestamp??void 0,0);if(B)z.push(B);if(z.length>=Z)break}return z}catch{return null}}async function YF($,J,Z,Y){try{let Q=await R2.readFile($,"utf8"),W=Q.split(`
1688
1688
  `).flatMap((G,B)=>{if(!G.trim())return[];try{return[{event:JSON.parse(G),index:B}]}catch{return[]}});if(!W.some(({event:G})=>G.type==="session_created"))return QF(W,J,Z,Y);let U=new Map(W.flatMap(({event:G,index:B})=>typeof G.id==="string"?[[G.id,B+1]]:[])),H=YV(QV(Q,$)),z=new Map;for(let G of H){if(G.type==="message_created"&&(G.data.role==="user"||G.data.role==="assistant"))z.set(G.data.messageId,{role:G.data.role,content:[],timestamp:G.timestamp,lineNumber:U.get(G.id)??0});if(G.type==="part_created"&&G.data.partType==="text"){let B=z.get(G.data.messageId),D=G.data.payload.text;if(B&&typeof D==="string")B.content.push(D)}}return[...z.values()].flatMap((G)=>{let B=j9(G.content.join(" "),J,Z,Y,G.role,G.timestamp,G.lineNumber);return B?[B]:[]})}catch{return[]}}function QF($,J,Z,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",U=j9(V,J,Z,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return U?[U]:[]})}function j9($,J,Z,Y,Q,X,W){if(!$)return;let V=Z?$:$.toLowerCase();if(!V.includes(J))return;let U=V.indexOf(J),H=Math.max(0,U-80),z=Math.min($.length,U+J.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function UV($){if($.length===0)return"没有找到匹配的历史记录";let J=[`**找到 ${$.length} 条匹配:**
1689
1689
  `];for(let Z of $){let Y=Z.timestamp?new Date(Z.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=Z.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";J.push(`${Q} \`${Z.sessionId.slice(0,8)}\` (${Y})`),J.push(` ${Z.content}`),J.push("")}return J.join(`
1690
1690
  `)}var XF={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,J){let Z=i(J);if($.length===0)return Z.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");Z.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await VV(Y,{maxResults:15,projectPath:J.cwd}),X=UV(Q);return Z.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return Z.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},HV=XF;var WF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,J)=>{try{let Z=J.workspaceRoot??J.cwd;return await R$(Z,async(Y)=>{await Y.skills.refresh(),p1(Z),await m1(Z)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(Z){let Y=`获取 Skills 失败: ${Z instanceof Error?Z.message:"未知错误"}`;return g().addAssistantMessage(Y),{success:!1,error:Y}}}},zV=WF;import VF from"node:path";function D8($){if($<1000)return`${$}ms`;let J=Math.floor($/1000);if(J<60)return`${J}s`;let Z=Math.floor(J/60);if(Z<60)return`${Z}m ${J%60}s`;return`${Math.floor(Z/60)}h ${Z%60}m`}function BV($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function GV($,J){if($.length<=J)return $;return $.slice(0,J-3)+"..."}async function UF($,J){let Z=i(J),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=J.sessionId??"",V=J.sessionId?{sessionId:J.sessionId,projectPath:VF.resolve(J.workspaceRoot??J.cwd)}:void 0;if(Y==="resume"){let D=$[1],q=$.slice(2).join(" ").trim();if(!D||!q)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!J.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let w=await J.subagents.resume(D,q),L=`Resumed \`${D}\` as \`${w.session.id}\` (depth ${w.session.resumeDepth}).`;return Z.sendMessage(L),{success:!0,message:L,data:{action:"subagent_resumed",sourceAgentId:D,subagent:w.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return Z.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let U=[`**后台任务列表**
@@ -1 +1 @@
1
- import{Ab as J,fb as V,hb as W,ib as O}from"./chunk-6x5f6she.js";import"./chunk-n30najxq.js";import"./chunk-q6sr4979.js";import"./chunk-kkzznz4w.js";import{Zi as Q}from"./chunk-b22ab7yw.js";import"./chunk-m2x6pb4f.js";import"./chunk-4e4qtpca.js";import"./chunk-a95jmx2j.js";import"./chunk-sdapqhj0.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{Ab as J,fb as V,hb as W,ib as O}from"./chunk-r5svk833.js";import"./chunk-n30najxq.js";import"./chunk-q6sr4979.js";import"./chunk-kkzznz4w.js";import{Zi as Q}from"./chunk-b22ab7yw.js";import"./chunk-m2x6pb4f.js";import"./chunk-4e4qtpca.js";import"./chunk-a95jmx2j.js";import"./chunk-sdapqhj0.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{Ui as Q}from"./chunk-h4b4fn3t.js";import{Zi as L}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-4e4qtpca.js";import"./chunk-5s2x98rx.js";import"./chunk-0eajnhrj.js";import"./chunk-yjcp8jk1.js";import"./chunk-px45q235.js";import"./chunk-a95jmx2j.js";import{Lk as F}from"./chunk-sdapqhj0.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-p36k2e96.js"),{SessionService:B}=await import("./chunk-qyfbeg5h.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{Ui as Q}from"./chunk-qy6p8bpr.js";import{Zi as L}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import"./chunk-m2x6pb4f.js";import"./chunk-4e4qtpca.js";import"./chunk-5s2x98rx.js";import"./chunk-0eajnhrj.js";import"./chunk-pbckwd41.js";import"./chunk-px45q235.js";import"./chunk-a95jmx2j.js";import{Lk as F}from"./chunk-sdapqhj0.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-p36k2e96.js"),{SessionService:B}=await import("./chunk-mmpcq1yh.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{Vf as N}from"./chunk-ebvzp8tn.js";import{Ah as $}from"./chunk-k2rgg45h.js";import{Zi as _}from"./chunk-b22ab7yw.js";import{Cj as Y,Ej as Z}from"./chunk-4e4qtpca.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}if(!process.stdout.isTTY)return;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",()=>{if(!process.stdin.isTTY||!process.stdout.isTTY){this.shutdown("SIGINT",0);return}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{Vf as N}from"./chunk-dv5ts9ae.js";import{Ah as $}from"./chunk-mqfayxf7.js";import{Zi as _}from"./chunk-b22ab7yw.js";import{Cj as Y,Ej as Z}from"./chunk-4e4qtpca.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}if(!process.stdout.isTTY)return;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",()=>{if(!process.stdin.isTTY||!process.stdout.isTTY){this.shutdown("SIGINT",0);return}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 Df,y as Ef,j as Ff,C as Gf};
@@ -0,0 +1 @@
1
+ import{xf as a,yf as b}from"./chunk-5qrw9g8c.js";import"./chunk-pbckwd41.js";import"./chunk-sdapqhj0.js";export{a as globalOptions,b as cliConfig};
@@ -1,4 +1,4 @@
1
- import{w as QH,x as YH,z as a}from"./chunk-qhcd0ww0.js";import{A as uz,B as gz,C as cz,D as S}from"./chunk-re8p2y22.js";import{E as JH,F as Rz,G as Sz,H as Mz,I as Iz,J as hz}from"./chunk-f9qrjd2f.js";import{$ as qz,Ea as yz,Fa as kz,Ga as Cz,Ha as fz,Q as R,_ as Ez,ha as Tz,ka as Pz,la as xz,oa as bz}from"./chunk-3ee357pw.js";import"./chunk-wnzr9h84.js";import{Va as HH}from"./chunk-290p3r7a.js";import{$a as i,Xa as Oz,cb as r}from"./chunk-6x5f6she.js";import{Rb as Nz,bc as Az,mc as l}from"./chunk-d4xsrx3z.js";import{xc as m}from"./chunk-9qxch6sy.js";import{$d as Fz,Hd as _z,Rd as I,Sd as d,Td as Vz,Yd as Dz,ae as Kz,ce as M,fe as jz,ke as wz,ne as K}from"./chunk-7rz5dt79.js";import"./chunk-skktstg8.js";import{Le as Uz,Se as n,Te as Gz}from"./chunk-wan9q99y.js";import"./chunk-n30najxq.js";import{Ef as ZH}from"./chunk-qa86anwd.js";import"./chunk-crv3sghv.js";import{Zf as sz,_f as tz}from"./chunk-ebvzp8tn.js";import{fg as zz}from"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import{kg as Bz}from"./chunk-g0xtk1yy.js";import{sg as p}from"./chunk-q6sr4979.js";import"./chunk-g2295k8s.js";import{xg as ez}from"./chunk-pm163dfm.js";import"./chunk-zwe1a7xe.js";import"./chunk-8q6zsznc.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as zH}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-k2rgg45h.js";import"./chunk-ys8gysg8.js";import{Ai as oz,xi as nz}from"./chunk-h4b4fn3t.js";import{Zi as e}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import{Aj as v,wj as g,xj as Wz,zj as c}from"./chunk-m2x6pb4f.js";import{Ej as h}from"./chunk-4e4qtpca.js";import"./chunk-5s2x98rx.js";import{Rj as rz,Uj as az}from"./chunk-0eajnhrj.js";import"./chunk-yjcp8jk1.js";import"./chunk-px45q235.js";import{fk as Lz,gk as lz,kk as Hz,ok as Jz,pk as iz,qk as Qz}from"./chunk-a95jmx2j.js";import"./chunk-sdapqhj0.js";import{Readable as NH,Writable as AH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as DH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as vz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function LH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function WH(z){let H={};for(let J of z){let Y=LH(J);if(Y)H[J.name]=Y}return H}function pz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function BH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:pz(z.content)}function _H(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{w as QH,x as YH,z as a}from"./chunk-kdtj92em.js";import{A as uz,B as gz,C as cz,D as S}from"./chunk-nvj4da2w.js";import{E as JH,F as Rz,G as Sz,H as Mz,I as Iz,J as hz}from"./chunk-45xdp95z.js";import{$ as qz,Ea as yz,Fa as kz,Ga as Cz,Ha as fz,Q as R,_ as Ez,ha as Tz,ka as Pz,la as xz,oa as bz}from"./chunk-r9nyzqzb.js";import"./chunk-wnzr9h84.js";import{Va as HH}from"./chunk-kb4hwa5a.js";import{$a as i,Xa as Oz,cb as r}from"./chunk-r5svk833.js";import{Rb as Nz,bc as Az,mc as l}from"./chunk-b3kvf23h.js";import{xc as m}from"./chunk-9qxch6sy.js";import{$d as Fz,Hd as _z,Rd as I,Sd as d,Td as Vz,Yd as Dz,ae as Kz,ce as M,fe as jz,ke as wz,ne as K}from"./chunk-faedrfhd.js";import"./chunk-skktstg8.js";import{Le as Uz,Se as n,Te as Gz}from"./chunk-wan9q99y.js";import"./chunk-n30najxq.js";import{Ef as ZH}from"./chunk-x2crj6jq.js";import"./chunk-crv3sghv.js";import{Zf as sz,_f as tz}from"./chunk-dv5ts9ae.js";import{fg as zz}from"./chunk-x6k5ye1z.js";import"./chunk-v508x7cg.js";import{kg as Bz}from"./chunk-g0xtk1yy.js";import{sg as p}from"./chunk-q6sr4979.js";import"./chunk-g2295k8s.js";import{xg as ez}from"./chunk-pm163dfm.js";import"./chunk-dyf12wbv.js";import"./chunk-crbt25b4.js";import"./chunk-kehgewqh.js";import"./chunk-kkzznz4w.js";import{sh as zH}from"./chunk-1cy4ab77.js";import"./chunk-7ajvrtb3.js";import"./chunk-mqfayxf7.js";import"./chunk-ys8gysg8.js";import{Ai as oz,xi as nz}from"./chunk-qy6p8bpr.js";import{Zi as e}from"./chunk-b22ab7yw.js";import"./chunk-amabfzc8.js";import{Aj as v,wj as g,xj as Wz,zj as c}from"./chunk-m2x6pb4f.js";import{Ej as h}from"./chunk-4e4qtpca.js";import"./chunk-5s2x98rx.js";import{Rj as rz,Uj as az}from"./chunk-0eajnhrj.js";import"./chunk-pbckwd41.js";import"./chunk-px45q235.js";import{fk as Lz,gk as lz,kk as Hz,ok as Jz,pk as iz,qk as Qz}from"./chunk-a95jmx2j.js";import"./chunk-sdapqhj0.js";import{Readable as NH,Writable as AH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as DH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as vz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=h("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Xz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function LH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Xz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Xz("headers"in z?z.headers:void 0)};return null}function WH(z){let H={};for(let J of z){let Y=LH(J);if(Y)H[J.name]=Y}return H}function pz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let J=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function BH(z){let H=Gz(z.metadata);return H?[{type:"text",text:n(H)}]:pz(z.content)}function _H(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function UH(z){if(!Bz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function GH(z){if(!(z instanceof vz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Vz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function VH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,J,Y,X={}){this.id=z;this.roots=H;this.connection=J;this.clientCapabilities=Y;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new hz({maxPendingItems:Rz,maxPendingBytes:Sz,writeTimeoutMs:Mz,signal:J.signal,sizeOf:(L)=>Buffer.byteLength(JSON.stringify(L)),write:async(L)=>{await J.sessionUpdate(L)},onFailure:(L)=>this.handleUpdateEgressFailure(L)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(J){if(!(J instanceof wz)&&J.code!=="ENOENT")throw J;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return bz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async($)=>{await this.sendUpdateAndWait($)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:($)=>this.requestPermission($)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?WH(this.options.mcpServers):void 0,Y=R.getTerminalService(this.id),X=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Tz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...X?{workspace:X}:{},permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,_)=>{let U=await Y.execute($,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await kz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Nz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.roots.hostStateRoot)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="follow_up.queue.changed"){let _=i.safeParse($.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if($.type==="provider.recovery"){let _=p.safeParse($.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if($.type==="turn.activity"){let _=r.safeParse($.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=$.properties,T=$.properties.metadata;if($.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&qz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Ez(_,Lz()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!Uz(H))continue;if(Kz(H)&&typeof H.content==="string"){if(!await this.sendUpdateAndWait({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`
3
3
 
4
4
  recap: ${H.content}