blade-code 0.10.165 → 0.10.167
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/chunk-0ehksh8s.js +1 -0
- package/dist/{chunk-9430yx31.js → chunk-1b5ctn1e.js} +1 -1
- package/dist/{chunk-wa3sdw3c.js → chunk-2b7ramqx.js} +1 -1
- package/dist/{chunk-c5ncj6se.js → chunk-5a80f2q4.js} +1 -1
- package/dist/{chunk-ndhdrtef.js → chunk-6txze2h9.js} +1 -1
- package/dist/{chunk-3yx1z7vq.js → chunk-73kn3p0n.js} +1 -1
- package/dist/chunk-75yfcccm.js +1 -0
- package/dist/{chunk-8eqs5drs.js → chunk-8bqxy3e9.js} +1 -1
- package/dist/{chunk-h1cs69np.js → chunk-8k10wy5p.js} +1 -1
- package/dist/{chunk-e394p3sh.js → chunk-96ak72kb.js} +1 -1
- package/dist/{chunk-708ja5cz.js → chunk-9zaq9fpe.js} +1 -1
- package/dist/{chunk-6knxtdzn.js → chunk-akzm4tvr.js} +4 -4
- package/dist/{chunk-ye0ev131.js → chunk-bqt15vhc.js} +1 -1
- package/dist/{chunk-g570p5bh.js → chunk-dcb29618.js} +1 -1
- package/dist/{chunk-dzhkr1h0.js → chunk-e5bw6rr6.js} +1 -1
- package/dist/{chunk-10pj0g1r.js → chunk-ep6kwh34.js} +1 -1
- package/dist/{chunk-za40abdc.js → chunk-f3sftx41.js} +1 -1
- package/dist/{chunk-911n2w2b.js → chunk-fmvf1apm.js} +1 -1
- package/dist/{chunk-73vr1br7.js → chunk-fvvzwc2x.js} +1 -1
- package/dist/{chunk-hnnsqhgg.js → chunk-g8he620f.js} +1 -1
- package/dist/{chunk-dzgj64vq.js → chunk-garqatdq.js} +1 -1
- package/dist/{chunk-wkyw8ban.js → chunk-ghfrh1hd.js} +42 -42
- package/dist/{chunk-zw8q8dye.js → chunk-gveathev.js} +1 -1
- package/dist/{chunk-p505ms9g.js → chunk-j73map95.js} +1 -1
- package/dist/{chunk-xde27z0w.js → chunk-k26rzh57.js} +1 -1
- package/dist/{chunk-r3fke6yp.js → chunk-kpk0yhr6.js} +1 -1
- package/dist/{chunk-tgxa39ay.js → chunk-mc3rgx6n.js} +2 -2
- package/dist/{chunk-1wmcyagp.js → chunk-mg92gcfm.js} +1 -1
- package/dist/{chunk-6tgjente.js → chunk-n5ap473n.js} +1 -1
- package/dist/{chunk-82sdv0yv.js → chunk-prccwvyv.js} +1 -1
- package/dist/{chunk-md7px7ha.js → chunk-qwj4q010.js} +1 -1
- package/dist/{chunk-51crjjt1.js → chunk-r02c9d2d.js} +1 -1
- package/dist/{chunk-sg580v6q.js → chunk-repg5q51.js} +1 -1
- package/dist/{chunk-wac2a806.js → chunk-vxhz56my.js} +1 -1
- package/dist/{chunk-vmckpv2t.js → chunk-wmgfqesw.js} +1 -1
- package/dist/{chunk-whbp683s.js → chunk-xqnnaxb5.js} +1 -1
- package/dist/{chunk-zrnzpknv.js → chunk-ygm6cr5b.js} +1 -1
- package/dist/{chunk-yq3982gr.js → chunk-z9re1bgq.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-3wx9aq8m.js +0 -1
- package/dist/chunk-55z8nm23.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{dg as J0}from"./chunk-t0gm0pn1.js";import{Fh as H0,Oi as r,Ri as U0,pi as x}from"./chunk-wa3sdw3c.js";import{bj as G0}from"./chunk-2f8d0km4.js";import{Pj as A}from"./chunk-j8hbddjp.js";import{devtools as v0,subscribeWithSelector as k0}from"zustand/middleware";import{createStore as f0}from"zustand/vanilla";var _0={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},K0={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},W0={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},O0={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},q0={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},B0={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},E0={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},x0={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},D0={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},L0={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},P0={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},A0={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},N0={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},i=[{id:"ayu-dark",label:"Ayu Dark",theme:_0,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:K0,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:W0,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:O0,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:q0,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:B0,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:E0,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:x0,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:D0,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:L0,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:P0,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:A0,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:N0,tags:["dark","japanese"]}];var n={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},v={name:"default",colors:n,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},w0={...v,name:"dark",colors:{...n,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class o{currentTheme=v;themes=new Map;constructor(){this.themes.set("default",v),this.themes.set("dark",w0);for(let Y of i)this.themes.set(Y.id,Y.theme)}setTheme(Y){let Z=this.themes.get(Y);if(Z)this.currentTheme=Z;else throw Error(`Theme '${Y}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(Y){return this.themes.get(Y)}hasTheme(Y){return this.themes.has(Y)}}var a=new o;var R0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,taskAttentionStatus:"idle",taskAttentionUnreadKeys:[],followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]},modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,reasoningEffort:"off",serviceTier:"auto",responseVerbosity:"auto",communicationStyle:"auto",subagentProgress:null,subagentProgresses:{},sideConversation:null,teams:[]},k=(Y)=>({...R0,actions:{setInitializationStatus:(Z)=>{Y((X)=>({app:{...X.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{Y((X)=>({app:{...X.app,initializationError:Z}}))},setActiveModal:(Z)=>{Y((X)=>({app:{...X.app,activeModal:Z}}))},showSessionSelector:(Z,X="resume")=>{Y((Q)=>({app:{...Q.app,activeModal:"sessionSelector",sessionSelectorData:{intent:X,sessions:Z},sessionHistoryViewerData:void 0}}))},showSessionHistoryViewer:(Z,X="resume")=>{Y((Q)=>({app:{...Q.app,activeModal:"sessionHistoryViewer",sessionSelectorData:void 0,sessionHistoryViewerData:{intent:X,session:Z}}}))},showModelEditWizard:(Z)=>{Y((X)=>({app:{...X.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{Y((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,modelEditorTarget:null}}))},setTasks:(Z)=>{Y((X)=>({app:{...X.app,tasks:Z}}))},updateTask:(Z)=>{Y((X)=>({app:{...X.app,tasks:X.app.tasks.map((Q)=>Q.id===Z.id?Z:Q)}}))},setAwaitingSecondCtrlC:(Z)=>{Y((X)=>({app:{...X.app,awaitingSecondCtrlC:Z}}))},projectTaskAttentionState:(Z,X,Q)=>{Y(($)=>({app:{...$.app,taskAttentionStatus:Z,taskAttentionUnreadKeys:[...X],sessionSelectorData:Z==="ready"&&$.app.activeModal==="sessionSelector"&&$.app.sessionSelectorData?{...$.app.sessionSelectorData,sessions:[...Q]}:$.app.sessionSelectorData}}))},projectFollowUpQueue:(Z,X)=>{Y((Q)=>{let $=[Q.session.workspaceRoot,Q.session.sessionId,""].join("\x00");if(X!==void 0&&!X.startsWith($))return Q;if(X!==void 0&&Q.app.followUpQueueOwner!==null&&Q.app.followUpQueueOwner!==X)return Q;let G=Q.app.followUpQueueMutation.supersededVersions??[];if(G.includes(Z.version))return Q;let J=Q.app.followUpQueue&&Q.app.followUpQueue.version!==Z.version?[...G,Q.app.followUpQueue.version].slice(-16):G;return{app:{...Q.app,followUpQueue:Z,followUpQueueOwner:X??Q.app.followUpQueueOwner,followUpQueueMutation:{pending:Q.app.followUpQueueMutation.pending,...Q.app.followUpQueueMutation.messageId?{messageId:Q.app.followUpQueueMutation.messageId}:{},supersededVersions:J}},command:{...Q.command,followUpPresentations:Object.fromEntries(Object.entries(Q.command.followUpPresentations).filter(([V])=>Z.items.some((F)=>F.id===V)))}}})},claimFollowUpQueueOwner:(Z)=>{Y((X)=>{let Q=[X.session.workspaceRoot,X.session.sessionId,""].join("\x00");if(!Z.startsWith(Q))return X;if(X.app.followUpQueueOwner===Z)return X;return{app:{...X.app,followUpQueue:null,followUpQueueOwner:Z,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...X.command,followUpPresentations:{}}}})},setFollowUpQueueMutation:(Z,X)=>{Y((Q)=>{let $=[Q.session.workspaceRoot,Q.session.sessionId,""].join("\x00");if(X!==void 0&&!X.startsWith($))return Q;if(X!==void 0&&Q.app.followUpQueueOwner!==null&&Q.app.followUpQueueOwner!==X)return Q;return{app:{...Q.app,followUpQueueMutation:{...Z,supersededVersions:Z.supersededVersions??Q.app.followUpQueueMutation.supersededVersions}}}})},clearFollowUpQueue:(Z)=>{Y((X)=>{if(Z!==void 0&&X.app.followUpQueueOwner!==Z)return X;return{app:{...X.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...X.command,followUpPresentations:{}}}})},setReasoningEffort:(Z)=>{Y((X)=>({app:{...X.app,reasoningEffort:Z}}))},setServiceTier:(Z)=>{Y((X)=>({app:{...X.app,serviceTier:Z}}))},setResponseVerbosity:(Z)=>{Y((X)=>({app:{...X.app,responseVerbosity:Z}}))},setCommunicationStyle:(Z)=>{Y((X)=>({app:{...X.app,communicationStyle:Z}}))},setThinkingModeEnabled:(Z)=>{Y((X)=>({app:{...X.app,reasoningEffort:Z?"auto":"off"}}))},toggleThinkingMode:()=>{Y((Z)=>({app:{...Z.app,reasoningEffort:Z.app.reasoningEffort==="off"?"auto":"off"}}))},startSubagentProgress:(Z,X,Q)=>{Y(($)=>({app:{...$.app,subagentProgresses:{...$.app.subagentProgresses,[Z]:{id:Z,type:X,description:Q,status:"running",startTime:Date.now()}},subagentProgress:{id:Z,type:X,description:Q,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(Z,X)=>{Y((Q)=>{let $=Q.app.subagentProgresses[Z];if(!$)return Q;let G={...$,currentTool:X};return{app:{...Q.app,subagentProgresses:{...Q.app.subagentProgresses,[Z]:G},subagentProgress:Q.app.subagentProgress?.id===Z?G:Q.app.subagentProgress}}})},completeSubagentProgress:(Z,X,Q)=>{Y(($)=>{let G=$.app.subagentProgresses[Z];if(!G)return $;let J=Q?.trim(),V={...G,status:X?"completed":"failed",currentTool:void 0,...!X&&J?{terminalSummary:J.slice(0,200)}:{}};return{app:{...$.app,subagentProgresses:{...$.app.subagentProgresses,[Z]:V},subagentProgress:$.app.subagentProgress?.id===Z?V:$.app.subagentProgress}}}),setTimeout(()=>{Y(($)=>{let G=$.app.subagentProgresses[Z];if(!G||G.status==="running")return $;let J={...$.app.subagentProgresses};delete J[Z];let V=Object.values(J);return{app:{...$.app,subagentProgresses:J,subagentProgress:$.app.subagentProgress?.id===Z?V[V.length-1]??null:$.app.subagentProgress}}})},1500)},startSideConversation:(Z,X)=>{Y((Q)=>({app:{...Q.app,sideConversation:{requestId:Z,question:X,status:"loading"}}}))},completeSideConversation:(Z,X)=>{Y((Q)=>{if(Q.app.sideConversation?.requestId!==Z)return Q;return{app:{...Q.app,sideConversation:{requestId:Z,question:Q.app.sideConversation.question,status:"completed",response:X.response,durationMs:X.durationMs}}}})},failSideConversation:(Z,X)=>{Y((Q)=>{if(Q.app.sideConversation?.requestId!==Z)return Q;return{app:{...Q.app,sideConversation:{requestId:Z,question:Q.app.sideConversation.question,status:"error",error:X}}}})},dismissSideConversation:()=>{Y((Z)=>({app:{...Z.app,sideConversation:null}}))},setTeams:(Z)=>{Y((X)=>({app:{...X.app,teams:Z}}))}}});var T0={isProcessing:!1,abortController:null,followUpPresentations:{},recoveredSteeringCount:0},f=(Y,Z)=>({...T0,actions:{setProcessing:(X)=>{Y((Q)=>({command:{...Q.command,isProcessing:X},...!X?{session:{...Q.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}:{}}))},createAbortController:()=>{let X=Z().command.abortController;if(X&&!X.signal.aborted)X.abort("interrupted-by-new-command");let Q=new AbortController;return Y(($)=>({command:{...$.command,abortController:Q}})),Q},getAbortController:()=>{return Z().command.abortController},clearAbortController:(X)=>{let Q=Z().command.abortController;if(X!==void 0&&Q!==X)return;Y(($)=>({command:{...$.command,abortController:null}}))},abort:(X)=>{let{abortController:Q}=Z().command;if(Q&&!Q.signal.aborted)Q.abort(X??"user-cancel");Y(($)=>({command:{...$.command,isProcessing:!1},session:{...$.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}))},rememberFollowUpPresentation:(X,Q)=>{Y(($)=>({command:{...$.command,followUpPresentations:Object.fromEntries([...Object.entries($.command.followUpPresentations),[X,Q]].slice(-20))}}))},takeFollowUpPresentation:(X)=>{let Q=Z().command.followUpPresentations[X];if(!Q)return;return Y(($)=>({command:{...$.command,followUpPresentations:Object.fromEntries(Object.entries($.command.followUpPresentations).filter(([G])=>G!==X))}})),Q},clearFollowUpPresentations:()=>{Y((X)=>({command:{...X.command,followUpPresentations:{}}}))},setRecoveredSteeringCount:(X)=>{Y((Q)=>({command:{...Q.command,recoveredSteeringCount:Math.max(0,X)}}))}}});var y0={config:null},u=(Y,Z)=>({...y0,actions:{setConfig:(X)=>{A().configureModelProviders(X.modelProviders,X.models),Y((Q)=>({config:{...Q.config,config:X}}))},updateConfig:(X)=>{let Q=Z().config.config;if(!Q)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(X)}`);let $={...Q,...X};if(X.modelProviders||X.models)A().configureModelProviders($.modelProviders,$.models);Y((G)=>({config:{...G.config,config:$}}))}}});var S0={currentFocus:"main-input",previousFocus:null},p=(Y)=>({...S0,actions:{setFocus:(Z)=>{Y((X)=>({focus:{...X.focus,currentFocus:Z,previousFocus:X.focus.currentFocus}}))},restorePreviousFocus:()=>{Y((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});function m(Y,Z,X,Q){let $=Y.messages.find((J)=>J.id===Z);if($)return $;let G={id:Z,role:X,content:"",timestamp:Q};return Y.messages.push(G),G}function s(Y,Z){let X=Date.parse(Z.timestamp)||Date.now();switch(Z.type){case"message_created":return m(Y,Z.data.messageId,Z.data.role,X),Y;case"part_created":case"part_updated":{let{messageId:Q,partType:$,payload:G,partId:J}=Z.data,V=Y.messages.find((F)=>F.id===Q)??m(Y,Q,"assistant",X);if($==="text"){let F=G.text??"";Y.streamingText.delete(J),V.content=F}else if($==="image")V.content=V.content?`${V.content}
|
|
1
|
+
import{dg as J0}from"./chunk-t0gm0pn1.js";import{Fh as H0,Oi as r,Ri as U0,pi as x}from"./chunk-2b7ramqx.js";import{bj as G0}from"./chunk-2f8d0km4.js";import{Pj as A}from"./chunk-j8hbddjp.js";import{devtools as v0,subscribeWithSelector as k0}from"zustand/middleware";import{createStore as f0}from"zustand/vanilla";var _0={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},K0={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},W0={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},O0={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},q0={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#cb4b16",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},B0={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},E0={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},x0={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#bc4c00",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},D0={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},L0={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},P0={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},A0={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},N0={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},i=[{id:"ayu-dark",label:"Ayu Dark",theme:_0,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:K0,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:W0,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:O0,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:q0,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:B0,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:E0,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:x0,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:D0,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:L0,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:P0,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:A0,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:N0,tags:["dark","japanese"]}];var n={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},v={name:"default",colors:n,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},w0={...v,name:"dark",colors:{...n,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class o{currentTheme=v;themes=new Map;constructor(){this.themes.set("default",v),this.themes.set("dark",w0);for(let Y of i)this.themes.set(Y.id,Y.theme)}setTheme(Y){let Z=this.themes.get(Y);if(Z)this.currentTheme=Z;else throw Error(`Theme '${Y}' not found`)}getTheme(){return this.currentTheme}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName(Y){return this.themes.get(Y)}hasTheme(Y){return this.themes.has(Y)}}var a=new o;var R0={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,taskAttentionStatus:"idle",taskAttentionUnreadKeys:[],followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]},modelEditorTarget:null,tasks:[],awaitingSecondCtrlC:!1,reasoningEffort:"off",serviceTier:"auto",responseVerbosity:"auto",communicationStyle:"auto",subagentProgress:null,subagentProgresses:{},sideConversation:null,teams:[]},k=(Y)=>({...R0,actions:{setInitializationStatus:(Z)=>{Y((X)=>({app:{...X.app,initializationStatus:Z}}))},setInitializationError:(Z)=>{Y((X)=>({app:{...X.app,initializationError:Z}}))},setActiveModal:(Z)=>{Y((X)=>({app:{...X.app,activeModal:Z}}))},showSessionSelector:(Z,X="resume")=>{Y((Q)=>({app:{...Q.app,activeModal:"sessionSelector",sessionSelectorData:{intent:X,sessions:Z},sessionHistoryViewerData:void 0}}))},showSessionHistoryViewer:(Z,X="resume")=>{Y((Q)=>({app:{...Q.app,activeModal:"sessionHistoryViewer",sessionSelectorData:void 0,sessionHistoryViewerData:{intent:X,session:Z}}}))},showModelEditWizard:(Z)=>{Y((X)=>({app:{...X.app,activeModal:"modelEditWizard",modelEditorTarget:Z}}))},closeModal:()=>{Y((Z)=>({app:{...Z.app,activeModal:"none",sessionSelectorData:void 0,sessionHistoryViewerData:void 0,modelEditorTarget:null}}))},setTasks:(Z)=>{Y((X)=>({app:{...X.app,tasks:Z}}))},updateTask:(Z)=>{Y((X)=>({app:{...X.app,tasks:X.app.tasks.map((Q)=>Q.id===Z.id?Z:Q)}}))},setAwaitingSecondCtrlC:(Z)=>{Y((X)=>({app:{...X.app,awaitingSecondCtrlC:Z}}))},projectTaskAttentionState:(Z,X,Q)=>{Y(($)=>({app:{...$.app,taskAttentionStatus:Z,taskAttentionUnreadKeys:[...X],sessionSelectorData:Z==="ready"&&$.app.activeModal==="sessionSelector"&&$.app.sessionSelectorData?{...$.app.sessionSelectorData,sessions:[...Q]}:$.app.sessionSelectorData}}))},projectFollowUpQueue:(Z,X)=>{Y((Q)=>{let $=[Q.session.workspaceRoot,Q.session.sessionId,""].join("\x00");if(X!==void 0&&!X.startsWith($))return Q;if(X!==void 0&&Q.app.followUpQueueOwner!==null&&Q.app.followUpQueueOwner!==X)return Q;let G=Q.app.followUpQueueMutation.supersededVersions??[];if(G.includes(Z.version))return Q;let J=Q.app.followUpQueue&&Q.app.followUpQueue.version!==Z.version?[...G,Q.app.followUpQueue.version].slice(-16):G;return{app:{...Q.app,followUpQueue:Z,followUpQueueOwner:X??Q.app.followUpQueueOwner,followUpQueueMutation:{pending:Q.app.followUpQueueMutation.pending,...Q.app.followUpQueueMutation.messageId?{messageId:Q.app.followUpQueueMutation.messageId}:{},supersededVersions:J}},command:{...Q.command,followUpPresentations:Object.fromEntries(Object.entries(Q.command.followUpPresentations).filter(([V])=>Z.items.some((F)=>F.id===V)))}}})},claimFollowUpQueueOwner:(Z)=>{Y((X)=>{let Q=[X.session.workspaceRoot,X.session.sessionId,""].join("\x00");if(!Z.startsWith(Q))return X;if(X.app.followUpQueueOwner===Z)return X;return{app:{...X.app,followUpQueue:null,followUpQueueOwner:Z,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...X.command,followUpPresentations:{}}}})},setFollowUpQueueMutation:(Z,X)=>{Y((Q)=>{let $=[Q.session.workspaceRoot,Q.session.sessionId,""].join("\x00");if(X!==void 0&&!X.startsWith($))return Q;if(X!==void 0&&Q.app.followUpQueueOwner!==null&&Q.app.followUpQueueOwner!==X)return Q;return{app:{...Q.app,followUpQueueMutation:{...Z,supersededVersions:Z.supersededVersions??Q.app.followUpQueueMutation.supersededVersions}}}})},clearFollowUpQueue:(Z)=>{Y((X)=>{if(Z!==void 0&&X.app.followUpQueueOwner!==Z)return X;return{app:{...X.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...X.command,followUpPresentations:{}}}})},setReasoningEffort:(Z)=>{Y((X)=>({app:{...X.app,reasoningEffort:Z}}))},setServiceTier:(Z)=>{Y((X)=>({app:{...X.app,serviceTier:Z}}))},setResponseVerbosity:(Z)=>{Y((X)=>({app:{...X.app,responseVerbosity:Z}}))},setCommunicationStyle:(Z)=>{Y((X)=>({app:{...X.app,communicationStyle:Z}}))},setThinkingModeEnabled:(Z)=>{Y((X)=>({app:{...X.app,reasoningEffort:Z?"auto":"off"}}))},toggleThinkingMode:()=>{Y((Z)=>({app:{...Z.app,reasoningEffort:Z.app.reasoningEffort==="off"?"auto":"off"}}))},startSubagentProgress:(Z,X,Q)=>{Y(($)=>({app:{...$.app,subagentProgresses:{...$.app.subagentProgresses,[Z]:{id:Z,type:X,description:Q,status:"running",startTime:Date.now()}},subagentProgress:{id:Z,type:X,description:Q,status:"running",startTime:Date.now()}}}))},updateSubagentTool:(Z,X)=>{Y((Q)=>{let $=Q.app.subagentProgresses[Z];if(!$)return Q;let G={...$,currentTool:X};return{app:{...Q.app,subagentProgresses:{...Q.app.subagentProgresses,[Z]:G},subagentProgress:Q.app.subagentProgress?.id===Z?G:Q.app.subagentProgress}}})},completeSubagentProgress:(Z,X,Q)=>{Y(($)=>{let G=$.app.subagentProgresses[Z];if(!G)return $;let J=Q?.trim(),V={...G,status:X?"completed":"failed",currentTool:void 0,...!X&&J?{terminalSummary:J.slice(0,200)}:{}};return{app:{...$.app,subagentProgresses:{...$.app.subagentProgresses,[Z]:V},subagentProgress:$.app.subagentProgress?.id===Z?V:$.app.subagentProgress}}}),setTimeout(()=>{Y(($)=>{let G=$.app.subagentProgresses[Z];if(!G||G.status==="running")return $;let J={...$.app.subagentProgresses};delete J[Z];let V=Object.values(J);return{app:{...$.app,subagentProgresses:J,subagentProgress:$.app.subagentProgress?.id===Z?V[V.length-1]??null:$.app.subagentProgress}}})},1500)},startSideConversation:(Z,X)=>{Y((Q)=>({app:{...Q.app,sideConversation:{requestId:Z,question:X,status:"loading"}}}))},completeSideConversation:(Z,X)=>{Y((Q)=>{if(Q.app.sideConversation?.requestId!==Z)return Q;return{app:{...Q.app,sideConversation:{requestId:Z,question:Q.app.sideConversation.question,status:"completed",response:X.response,durationMs:X.durationMs}}}})},failSideConversation:(Z,X)=>{Y((Q)=>{if(Q.app.sideConversation?.requestId!==Z)return Q;return{app:{...Q.app,sideConversation:{requestId:Z,question:Q.app.sideConversation.question,status:"error",error:X}}}})},dismissSideConversation:()=>{Y((Z)=>({app:{...Z.app,sideConversation:null}}))},setTeams:(Z)=>{Y((X)=>({app:{...X.app,teams:Z}}))}}});var T0={isProcessing:!1,abortController:null,followUpPresentations:{},recoveredSteeringCount:0},f=(Y,Z)=>({...T0,actions:{setProcessing:(X)=>{Y((Q)=>({command:{...Q.command,isProcessing:X},...!X?{session:{...Q.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}:{}}))},createAbortController:()=>{let X=Z().command.abortController;if(X&&!X.signal.aborted)X.abort("interrupted-by-new-command");let Q=new AbortController;return Y(($)=>({command:{...$.command,abortController:Q}})),Q},getAbortController:()=>{return Z().command.abortController},clearAbortController:(X)=>{let Q=Z().command.abortController;if(X!==void 0&&Q!==X)return;Y(($)=>({command:{...$.command,abortController:null}}))},abort:(X)=>{let{abortController:Q}=Z().command;if(Q&&!Q.signal.aborted)Q.abort(X??"user-cancel");Y(($)=>({command:{...$.command,isProcessing:!1},session:{...$.session,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,providerRecovery:null,turnActivity:null,actionStationarity:null}}))},rememberFollowUpPresentation:(X,Q)=>{Y(($)=>({command:{...$.command,followUpPresentations:Object.fromEntries([...Object.entries($.command.followUpPresentations),[X,Q]].slice(-20))}}))},takeFollowUpPresentation:(X)=>{let Q=Z().command.followUpPresentations[X];if(!Q)return;return Y(($)=>({command:{...$.command,followUpPresentations:Object.fromEntries(Object.entries($.command.followUpPresentations).filter(([G])=>G!==X))}})),Q},clearFollowUpPresentations:()=>{Y((X)=>({command:{...X.command,followUpPresentations:{}}}))},setRecoveredSteeringCount:(X)=>{Y((Q)=>({command:{...Q.command,recoveredSteeringCount:Math.max(0,X)}}))}}});var y0={config:null},u=(Y,Z)=>({...y0,actions:{setConfig:(X)=>{A().configureModelProviders(X.modelProviders,X.models),Y((Q)=>({config:{...Q.config,config:X}}))},updateConfig:(X)=>{let Q=Z().config.config;if(!Q)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(X)}`);let $={...Q,...X};if(X.modelProviders||X.models)A().configureModelProviders($.modelProviders,$.models);Y((G)=>({config:{...G.config,config:$}}))}}});var S0={currentFocus:"main-input",previousFocus:null},p=(Y)=>({...S0,actions:{setFocus:(Z)=>{Y((X)=>({focus:{...X.focus,currentFocus:Z,previousFocus:X.focus.currentFocus}}))},restorePreviousFocus:()=>{Y((Z)=>({focus:{...Z.focus,currentFocus:Z.focus.previousFocus||"main-input",previousFocus:null}}))}}});function m(Y,Z,X,Q){let $=Y.messages.find((J)=>J.id===Z);if($)return $;let G={id:Z,role:X,content:"",timestamp:Q};return Y.messages.push(G),G}function s(Y,Z){let X=Date.parse(Z.timestamp)||Date.now();switch(Z.type){case"message_created":return m(Y,Z.data.messageId,Z.data.role,X),Y;case"part_created":case"part_updated":{let{messageId:Q,partType:$,payload:G,partId:J}=Z.data,V=Y.messages.find((F)=>F.id===Q)??m(Y,Q,"assistant",X);if($==="text"){let F=G.text??"";Y.streamingText.delete(J),V.content=F}else if($==="image")V.content=V.content?`${V.content}
|
|
2
2
|
[Image]`:"[Image]";return Y}default:return Y}}function t(Y,Z){if(Z.channel!=="content")return Y;let X=Y.messages.find((G)=>G.id===Z.messageId)??m(Y,Z.messageId,"assistant",Date.now()),$=(Y.streamingText.get(Z.partId)?.text??"")+Z.delta;return Y.streamingText.set(Z.partId,{messageId:Z.messageId,text:$}),X.content=$,Y}function e(Y,Z,X,Q=0,$=0,G){let J=A(),V=G?J.models.getModel(G,Y):J.models.getModels().find((K)=>K.id===Y);if(!V)return 0;let F=V.cost,z=Z/1e6*F.input+X/1e6*F.output+Q/1e6*F.cacheRead+$/1e6*F.cacheWrite;return Math.round(z*1e6)/1e6}var W={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,blockquote:/^(>+)\s?(.*)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/,commandMessage:/<command-message>(.*?)<\/command-message>/};function t0(Y){let Z=[],X=Y.split(/\r?\n/),Q=!1,$=[],G=null,J=0,V=!1,F=[],z=[],K=!1,B=[],L=!1,j=[],H=0,U=!0;for(let q=0;q<X.length;q++){let O=X[q];if(K){if(O.match(W.diffEnd)){try{let E=JSON.parse(B.join(`
|
|
3
3
|
`));Z.push({type:"diff",content:"",diffData:{patch:E.patch,startLine:E.startLine,matchLine:E.matchLine}})}catch(E){Z.push({type:"text",content:B.join(`
|
|
4
4
|
`)})}K=!1,B=[],U=!1;continue}B.push(O);continue}if(O.match(W.diffStart)){K=!0,B=[],U=!1;continue}if(Q){let E=O.match(W.codeBlock),P=O.trim()==="```";if(E&&E[1])J++,$.push(O);else if(P)if(J>0)J--,$.push(O);else{let j0=$.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-
|
|
1
|
+
import{Ga as z3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as Vz,Qa as RY,Ra as e0}from"./chunk-5a80f2q4.js";import{$a as HX,Sa as Y5,Va as pZ,Za as tZ,_a as UX,bb as rz,db as nz,eb as A9,wb as az}from"./chunk-30x3mcsb.js";import{Ab as c7,Bb as D2,Cb as BY,Db as x1,Eb as a7,Fb as KY,Gb as $Y,Hb as DY,Ib as qY,Jb as WQ,Lb as JX,Nb as W0,Pb as _2,Sb as p4,Ub as _Z,Vb as l4,Wb as i4,Yb as AJ,Zb as R$,dc as aX,ec as G8,fc as sX,gc as ZX,ic as u1,jc as SX,oc as iY,rc as rY,xb as s5,yb as h7,zb as J1}from"./chunk-73kn3p0n.js";import{$c as r8,$d as lY,Ac as k3,Bc as T1,Cc as ZJ,Dc as _0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as JY,Lc as YY,Mc as CX,Nc as X3,Nd as W8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as Jz,Yc as d2,Yd as VX,Zc as H3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as fX,fd as d6,fe as PX,gd as J2,hd as m6,he as s,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as MX,zc as r3}from"./chunk-dcb29618.js";import{ie as l,je as BQ,ke as GQ,le as IJ,ne as F2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as TX,Le as RX,Ue as ez,ff as $W,pe as oz,se as tz}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as cY,cg as B2}from"./chunk-9zaq9fpe.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as pY,ng as dY,og as mX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as tX}from"./chunk-50vwafn5.js";import{Ag as bX,xg as LX,yg as OX,zg as NX}from"./chunk-96ak72kb.js";import{$g as AX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as _1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as W2,Og as H8,Pg as l1,Qg as i1,Rg as EX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as kX}from"./chunk-qwj4q010.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as z2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as _z,th as jX,uh as z8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-j73map95.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as PY,Di as SY,Ei as kY,Fh as XJ,Fi as vY,Gi as AZ,Hi as yY,Ii as B1,Ji as xY,Kh as zJ,Ki as IY,Li as hY,Mh as D9,Ni as t3,Pi as yX,Qi as _X,Rh as Wz,Ri as B0,Vh as WJ,Xh as qX,Zh as UY,_h as HY,pi as h1,si as e7}from"./chunk-2b7ramqx.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as eQ,Yi as $X}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as wX,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as Oz,Tj as wz}from"./chunk-4cdk4mds.js";import{Xj as Ez}from"./chunk-xqnnaxb5.js";import{bk as vX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as t7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as _W}from"node:crypto";var KW=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -859,7 +859,7 @@ ${A0}
|
|
|
859
859
|
</approved-plan>
|
|
860
860
|
|
|
861
861
|
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}v=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return v;let p=await this.sessionRuntime.recordGoalProgress({tokens:v.metadata?.tokensUsed??0,elapsedMs:v.metadata?.duration??0,...k?{goalId:k.goalId,objective:k.objective,turnId:I.id}:{},executionHostFailureCategory:v.metadata?.executionHostFailureCategory,prematureStopPattern:v.success?VY(v.finalMessage):void 0});if(p)yield{kind:"goal_updated",goal:p};if(!v.success||b.signal?.aborted){if(p=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":v.error?.message??"goal paused after turn failure"),p)yield{kind:"goal_updated",goal:p}}if(v.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let n=v.success&&!b.signal?.aborted&&h<20,p0=XG(v)||!v.success&&v.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:n,...p0?{acknowledgeInput:!0}:{},outcome:v.success&&!b.signal?.aborted?{status:"completed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,durationMs:v.metadata?.duration??0}}),R){h++,N=!0,M=!1,j=null,O="",o=void 0,A="",S=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!v.success||b.signal?.aborted)return v;if(p=await this.sessionRuntime.getGoal(),!p||p.status!=="active"&&p.status!=="verifying")return v;let J0=await this.sessionRuntime.prepareGoalContinuation(p);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:v.metadata?.turnsCount??0,toolCallsCount:v.metadata?.toolCallsCount??0,duration:v.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return v;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,M=!0,O=S5(j),o=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let _=typeof H==="string"?H:H.filter((O)=>O.type==="text").map((O)=>O.text).join(`
|
|
862
|
-
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-zw8q8dye.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
862
|
+
`),L={id:this.generateTaskId(),type:"simple",prompt:_};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-gveathev.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){a.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((z)=>z.type==="text");if(X.length>0){let z=X[0];Q=$.map((W)=>W===z?{type:"text",text:t2(z.text)}:W)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){a.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return rY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,z=J.output,W={success:X,llmContent:typeof z==="string"||z!==null&&typeof z==="object"?z:z===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(z),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},V=[{kind:"tool_result",toolCall:Y,result:W}],U=iY(Y,W);if(U)V.push(U);return V})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,a.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);a.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);a.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){a.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){a.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),a.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});a.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;a.debug(`Builtin tools registered: ${Z} tools`),a.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw a.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await z4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){a.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${QG()}`)});this.legacyMcpRegistry=Z;for(let[X,z]of Object.entries($))try{a.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,z),a.debug(`MCP server "${X}" connected`)}catch(W){a.warn(`Warning: MCP server "${X}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)a.debug(`Registered ${Y.tools.length} MCP tools`),a.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){a.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)a.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else a.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;a.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return a.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)a.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
|
|
863
863
|
`);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;a.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return a.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
|
|
864
864
|
|
|
865
865
|
<system-reminder>
|
|
@@ -1108,7 +1108,7 @@ ${U}
|
|
|
1108
1108
|
`+` /model add
|
|
1109
1109
|
|
|
1110
1110
|
`+`或运行初始化向导:
|
|
1111
|
-
`+" /init");if(!G&&Q&&Q!=="inherit"&&!b.some((A)=>A.id===Q))Q=void 0;let M=await z4({workspaceRoot:F,...w?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:_.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...O.config,permissionMode:X??O.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:w?structuredClone(O.config.permissions):await L.loadWorkspacePermissions(F,O.config.permissions),hooks:w?{enabled:!1}:await L.loadWorkspaceHooks(F,O.config.hooks??{})};L.validateConfig(E,O.catalog);let j=new q1(E,{...$,modelResources:O,lspResources:N,mcpServers:M,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:z,serviceTier:W,responseVerbosity:V,communicationStyle:U,...H?{communicationStyleDigest:H}:{},...B?{projectInstructionsDigest:B}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(w){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(w instanceof m4)){let q=J?await C$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await q1.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",q??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((_)=>{if(_.code!=="ENOENT")E0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,_)})}throw w}}static async hasPendingInbox($,Z,J=v$($)){if(await T1(J,Z,async({inboxPath:X})=>{try{return(await BX(X)).size>0}catch(z){if(z.code!=="ENOENT")throw z;return!1}}))return!0;if(J.kind==="acp-remote")return!1;if(j0()?.agentTeamsEnabled!==!0)return!1;let Q=(await B$.getInstance(t()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===Z&&X.workspaceRoot===$);for(let X of Q)if((await new H$(X.name,t()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,Z,J=v$($)){return T1(J,Z,async({inboxPath:Y})=>{try{return await BX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,Z,J=v$($)){return V0.hasActiveGoal($,Z,J)}static async hasRecoverableTurn($,Z,J=v$($)){return new _2($,100,void 0,J).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??C()}get executionRoot(){return this.workspace.executionRoot}get resourceRoot(){return this.workspace.resourceRoot}isRemoteWorkspace(){return this.workspace.kind==="acp-remote"}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return V2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=g1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Q.taskStatus,...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:g1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=g1.getStats();W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}beginProviderRecovery(){let $=this.providerRecovery.begin();return this.providerRecoveryGeneration=$,this.publishProviderRecovery(this.providerRecovery.snapshot()),$}observeProviderRecovery($,Z){let J=this.providerRecovery.observe($,Z);if(J)this.publishProviderRecovery(J);return J}clearProviderRecovery($){let Z=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(Z)this.publishProviderRecovery(Z);return Z}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,Z){let J=this.turnActivity.observe($,Z);if(J)this.publishTurnActivity(J);return J}clearTurnActivity($){let Z=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(Z)this.publishTurnActivity(Z);return Z}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"turn.activity",{activity:$})}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return this.workspace.kind==="acp-remote"?s.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):s.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(J.signal);let[z,W]=await Promise.all([this.loadModelContext(),Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:this.executionRoot},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot}})]);if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let V=SX(W.prompt,X);if(!V)throw Error("Side conversation system prompt is empty");return await MJ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:V,messages:z,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return E3(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0,await this.activeTurnMailbox?.setRecoveryProtectedIds([])}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((z)=>z.role==="assistant"&&DX(z)?.turnId===$.turnId&&JSON.stringify(DX(z))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,X=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...X?{structuredOutput:X}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new f("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return z8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return z8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??jX}getProjectRuleCatalog(){return this.agentResources?.projectRules??EX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let U of V?.getAffectedPaths()??[])if(U)Q.add(U)}catch{}let X=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(z?.affected_paths))for(let V of z.affected_paths)X(V);if(Array.isArray(z?.changes)){for(let V of z.changes)if(V&&typeof V==="object")X(V.path)}let W=[...Q].map((V)=>F0.isAbsolute(V)?F0.resolve(V):F0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let U=F0.relative(this.workspaceRoot,V);if(U===""||!U.startsWith("..")&&!F0.isAbsolute(U))return[F0.resolve(this.projectRoot,U)];let H=F0.relative(this.projectRoot,V);return H===""||!H.startsWith("..")&&!F0.isAbsolute(H)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await o6($,{configDir:t(),stateStorage:this.stateStorage}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:y3($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){E0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${X instanceof Error?X.message:String(X)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await C$.getChangeSummary(this.sessionId):void 0;return q1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,Z,J,Y,Q,X){let z=new Date().toISOString(),W=J==="failed"&&Y!==void 0?W8(Y):void 0,V=W?.message??(typeof Y==="string"?Y.slice(0,500):void 0),U={taskStatus:J,taskStatusReason:V??null,taskFailure:W??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:z,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:z,taskOwnerPid:null}},H=X?await s.updateRemoteSessionMetadata($,Z,X,U):await s.updateSessionMetadata($,Z,U);return W0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:H.taskStatus,...V?{taskStatusReason:V}:{},...W?{taskFailure:W}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskCompletedAt?{taskCompletedAt:H.taskCompletedAt}:{},...H.taskDiffStat?{taskDiffStat:H.taskDiffStat}:{},...H.taskQueuePosition?{taskQueuePosition:H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{taskQueueDepth:H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:H.taskConcurrencyLimit}:{},updatedAt:H.lastMessageTime}),H}createGoal($,Z){return this.goalStore.create($,Z)}async beginGoalTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.beginTurn(),Y=await this.goalStore.prepareTurnBinding(J.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await Z.finishTurn(J).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(J,"goal",[],{goalId:Y.goalId,...Y.lineage}),Q=!0;let X=await this.goalStore.commitTurnBinding(Y);if(!X)throw Error("Goal changed before turn lineage commit");return{handle:J,goal:X}}catch(X){throw await this.releaseFailedTurnStart(J,Q),X}}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),s.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await s.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return $$.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return $$.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=D0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let z=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!z)throw Error(`Subagent cannot be resumed: ${Y.id}`);let W=Z.getAgent(z.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${z.agentId}`);return{source:z.source,session:W}}async beginTurn($="goal"){let Z=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,Z?.metadata),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await J.reservedMessageIds(Q.handle),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before user turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q.handle,X),z}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},...Z.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let z=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},z),await this.getActiveTurnMailbox().acknowledge(z)}else{let z=this.startupTurnRecovery,W=Z.preserveStartupRecovery&&z?.outcome==="aborted"?{hadSuccessfulToolResult:z.hadSuccessfulToolResult,interruptedToolCallCount:z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:z.allSuccessfulToolResultsSafeForResume,correctionSpent:z.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),V=await this.getActiveTurnMailbox().claimedMessageIds($),U=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:3,inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:W.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:V}:void 0);if(this.startupTurnRecovery=U.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(U.recovery?.inputMessageIds??[]),Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(U.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before pending turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q,X),z}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;let J=!1;try{let Y=await this.goalStore.prepareTurnBinding(Z.id,!1);if(await this.saveTurnStart(Z,"pending",await $.reservedMessageIds(Z),Y?{goalId:Y.goalId,...Y.lineage}:void 0),J=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return Z}catch(Y){throw await this.releaseFailedTurnStart(Z,J),Y}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}async getFollowUpQueueSnapshot(){return this.getActiveTurnMailbox().getFollowUpQueueSnapshot()}async mutateFollowUpQueue($){return this.getActiveTurnMailbox().mutateFollowUpQueue($)}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(!this.isRemoteWorkspace()&&Y0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!$$.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await iZ.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.reconcileBackgroundSubagentCompletions(),this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=y0.getInstance().listSessions().filter((J)=>t0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await iZ.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=y0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((z)=>Boolean(z)):J.listSessions().filter((z)=>t0(z,Y)),X=0;for(let z of Q){if(!this.backgroundTaskChildIds.has(z.id)||this.backgroundTaskCompletionSettledIds.has(z.id)||z.status==="running")continue;let W=z.resumedFrom?J.loadSession(z.resumedFrom):void 0,V=lQ(z,Y,W);if(!V){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let U=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!U.eligible||U.acknowledged){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let H=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!H.accepted){E0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${z.id}`);continue}if(H.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);if(this.backgroundTaskCompletionSettledIds.add(z.id),H.duplicate)continue;if(X++,H.queue)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:H.queue});W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:z.id,inboxMessageId:V.inboxMessageId,status:z.status,type:z.subagentType,description:z.description,summary:V.subagentRef.subagentSummary,resumedFrom:z.resumedFrom,rootAgentId:z.rootAgentId,resumeDepth:z.resumeDepth,verificationVerdict:z.result?.verificationVerdict,queued:H.queued,delivery:H.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[])}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await B$.getInstance(t()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new H$(Z.name,t()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(N2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:Z8(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=mD(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,X=async(G)=>{let D=G.type==="started"?{executionId:G.executionId,command:G.command,auxiliary:Y}:G.type==="output"?{executionId:G.executionId,stream:G.stream,chunk:G.chunk,streamedBytes:G.streamedBytes,streamTruncated:G.streamTruncated,auxiliary:Y}:{executionId:G.executionId,messageId:G.messageId,record:G.record,auxiliary:Y,delivery:G.delivery,queued:G.queued};W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${G.type}`,D),await Z.onEvent?.(G)},z=await TX($,{executionId:J,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??$9():$9():this.options.userShellExecutor,onEvent:async(G)=>{if(G.type!=="completed")await X({...G,auxiliary:Y})}}),W=RX(z),U=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(z))},this.options.subagentInfo),H=Y?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0,origin:"user_shell"}):void 0;if(H?.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);let B={executionId:J,messageId:U,record:z,modelContent:W,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{},...H?.queue?{queue:H.queue}:{}};return await X({type:"completed",executionId:J,messageId:U,record:z,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await c4.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new b1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await vJ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await cD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let W=x0.getInstance();if(W.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),W.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)W.inheritProjectConfig(this.projectRoot,this.workspaceRoot);W.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??W.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??W.getConfig(this.projectRoot));let V=await W.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!V.proceed)throw Error(V.warning||"SessionStart hook blocked initialization");if(V.warning)E0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${V.warning}`);let U=_X(V.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...U}),this.config.env=this.sessionEnvironment,W.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new e8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new cZ({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let $=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await $.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Z=await $.loadInterruptedToolCalls(this.sessionId),J=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let W=y0.getInstance();for(let V of Z){if(V.toolName!=="Task"||!V.input||typeof V.input!=="object"||Array.isArray(V.input))continue;let U=V.input.subagent_session_id;if(typeof U!=="string")continue;let H=W.loadSession(U);if(!H)continue;let B=HQ(V,H,Y);if(B)J.set(V.toolCallId,B)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:J});if(Q)this.startupAdoptedToolResults=Z.flatMap((W)=>{let V=J.get(W.toolCallId);return V?[{call:W,result:V}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),z=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(z?.finalized)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:z.goal});if(this.startupTurnRecovery=Q??(X&&z?.finalized?{turnId:X.turnId,outcome:"completed",inputMessageIds:X.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:X.finalization}:void 0),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[]),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(!this.isRemoteWorkspace())await this.recoverTeamLeadMessages(),await this.attachBackgroundSubagentCompletionDispatcher();if(Q)E0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,E0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,z=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(z8(W,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||z!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,z);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=z,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new H1;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((B)=>B!==J),X=Y?new Set(Y):null,z=Q?new Set(Q):null;for(let B of this.baseRegistry.getBuiltinTools()){if(z?.has(B.name))continue;if(!X||X.has(B.name))Z.register(B)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,z));let W=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((B)=>!z?.has(B)&&(!X||X.has(B))))for(let B of $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:G,...D}=B;Z.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(Z,{allowed:X,blocked:z});let U={...this.config.permissions,...$.permissions},H=$.permissionMode??this.config.permissionMode??"default";return new z6(Z,{permissionConfig:U,permissionMode:H,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,workspaceToolPolicy:this.workspaceToolPolicy,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,executionRoot:this.executionRoot,workspaceKind:this.workspace.kind,environment:this.sessionEnvironment,permissionMode:H,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(B)=>this.notifyBackgroundSubagentCompleted(B),registerBackgroundSubagent:(B)=>this.registerBackgroundSubagent(B)},...this.lspManager?{lspManager:this.lspManager}:{},...H==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,Z=async(_,L)=>{try{await L()}catch(F){$??=F,E0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${_} during cleanup`,F)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,z=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,V=this.mcpLogListener,U=this.mcpInstructionsListener,H=this.mcpTaskListener,B=this.sessionLease,G=this.autoVerifyRuntime,D=this.lspManager,w=this.browserRuntime,q=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>w?.dispose()),await Z("dispose the background subagent completion registration",()=>q?.dispose()),this.backgroundSubagentCompletionRegistration=void 0,this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new H1,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,!this.isRemoteWorkspace())await Z("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>G?.dispose()),await Z("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await Z("release the session hook model resources",()=>x0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>C$.releaseSession(this.sessionId));if(await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>$$.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&z)Y.off("resourceUpdated",z);if(Y&&W)Y.off("connectionLifecycleChanged",W);if(Y&&V)Y.off("log",V);if(Y&&U)Y.off("instructionsChanged",U);if(H)$$.getInstance().off("taskChanged",H);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,Z){if(Z)try{await this.finishTurn($,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}});return}catch{}await this.getActiveTurnMailbox().finishTurn($).catch(()=>{return})}assertRewindIdle(){if(this.isRemoteWorkspace())throw Error("Rewind is unavailable for ACP remote workspaces");if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Y0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let X=m0($,this.config,J,this.modelResources.catalog,Y,Q);E0.debug(`${Z} ${X.displayName} (${$.model})`);let z=X.model.contextWindow,W=await S4(X.chat),V=this.initialized?this.chatService:void 0,U=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new V6(W,U,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=z,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let H=V;try{await H?.dispose?.()}catch(B){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(!this.options.auxiliaryReadOnly&&this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&!this.options.auxiliaryReadOnly&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot},environmentOptions:{...u1,workingDirectory:this.executionRoot}})}catch(J){E0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof fX||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await s.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new n8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposeArtifactPaths:!U0(this.sessionId)});let $=await v4({sessionId:this.sessionId,configDir:t(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,stateStorage:this.stateStorage,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime}),Z=iJ($.filter((J)=>!J.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=e0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new o2(`${this.stateStorage.kind==="acp-remote"?this.workspaceRoot:this.projectRoot}\x00${this.sessionId}`,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(U)=>{this.applyMcpCatalog(U,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(U)=>{this.applyMcpContentCatalog(U)},Q=(U)=>{this.applyMcpResourceUpdated(U)},X=(U)=>{this.applyMcpConnectionChange(U)},z=(U)=>{this.applyMcpLog(U)},W=(U)=>{this.applyMcpInstructions(U)},V=(U)=>{if(U.owner.sessionId!==this.sessionId||F0.resolve(U.owner.projectPath)!==F0.resolve(this.workspaceRoot))return;this.applyMcpTask(U);let{owner:H,result:B,...G}=U;W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",G)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=z,this.mcpInstructionsListener=W,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",X),Z.on("log",z),Z.on("instructionsChanged",W),$$.getInstance().on("taskChanged",V);for(let[U,H]of Object.entries($))try{let B=H.type==="stdio"?{...this.sessionEnvironment,...H.env}:void 0;await Z.registerServer(U,H.type==="stdio"?{...H,...B&&Object.keys(B).length>0?{env:B}:{}}:H)}catch(B){E0.warn(`Warning: MCP server "${U}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Y6(Z)),this.baseRegistry.registerAll(KZ(Z))}catch($){E0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),z={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},W=z.added.length>0||z.removed.length>0||z.updated.length>0;J.replaceMcpTools(Q,Z&&W?z:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!X.blocked?.has(W)&&(!X.allowed||X.allowed.has(W))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return qX(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?AX(this.resourceRoot):await c0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function Z9(){let $=await B0.getInstance().reload();q0().config.actions.setConfig($),await e0.getInstance().disconnectAll(),kX(),await c0(C())}import KF from"fuse.js";import c$ from"node:path";import{Mutex as pD}from"async-mutex";var p$=new pD;async function xX($){let Z=$.getWorkspaceRoot();await f$(Z,async(J)=>{await $.reapplyEnabledSettings(),i1(Z),await l1(Z),await J9(J)})}async function lD($){let Z=$.getWorkspaceRoot();return f$(Z,async(J)=>{i1(Z);let Y=await $.refresh();return await l1(Z),await J9(J),Y})}async function Y9($){return f$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...W2.getInitializedInstances()])),Y;for(let Q of J){let X=await lD(Q);if(Q===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function iD($,Z){let J=c$.resolve($),Y=h1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function rD($){return c$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function IX($,Z){if(rD(Z)&&!vX(await a0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function V8($,Z,J,Y="local"){return p$.runExclusive(async()=>{let Q=c$.resolve($);return f$(Q,async(X)=>{let z=X.plugins.get(Z);if(!z)throw Error(`Plugin not found: ${Z}`);if(z.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await h1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let W=Y==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let H of W)await xX(H);let V=X.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let U=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:U.settings[Z]?.effectiveScope??"default"}})})}async function U8($){return p$.runExclusive(()=>f$($,async(Z)=>{i1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function Q9($,Z,J="global"){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q={...Z,...yX(Z)};return await h1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),f$(Y,async(X)=>{let z=J==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let W of z)await xX(W);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function X9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function z9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function W9($,Z,J=!1){return p$.runExclusive(async()=>{let Y=c$.resolve($);return f$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let z=await G$().uninstall(Z,J);if(!z.success)return{result:z};await iD(Y,Z);let W=await Y9(Y);return{result:z,discovery:W}})})}async function V9($,Z,J){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return G$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function U9($,Z){return p$.runExclusive(async()=>{let J=c$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(J);return G$().refreshMarketplace(Z,Y)})}async function H9($,Z=!1){return p$.runExclusive(()=>G$().removeMarketplace($,Z))}var nD={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
|
|
1111
|
+
`+" /init");if(!G&&Q&&Q!=="inherit"&&!b.some((A)=>A.id===Q))Q=void 0;let M=await z4({workspaceRoot:F,...w?{workspaceAccess:"none",resourceRoot:$.workspace.resourceRoot}:{},storeServers:_.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),E={...O.config,permissionMode:X??O.config.permissionMode??"default",lspServers:structuredClone(N.servers),permissions:w?structuredClone(O.config.permissions):await L.loadWorkspacePermissions(F,O.config.permissions),hooks:w?{enabled:!1}:await L.loadWorkspaceHooks(F,O.config.hooks??{})};L.validateConfig(E,O.catalog);let j=new q1(E,{...$,modelResources:O,lspResources:N,mcpServers:M,...Q?{modelId:Q}:{},permissionMode:E.permissionMode,reasoningEffort:z,serviceTier:W,responseVerbosity:V,communicationStyle:U,...H?{communicationStyleDigest:H}:{},...B?{projectInstructionsDigest:B}:{},...J?{taskWorktree:J}:{},...Y?{taskIsolation:Y}:{}});return await j.initialize(),j}catch(w){if(!$.auxiliaryReadOnly&&!$.subagentInfo&&!(w instanceof m4)){let q=J?await C$.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await q1.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",q??void 0,$.workspace?.kind==="acp-remote"?$.workspace.descriptor:void 0).catch((_)=>{if(_.code!=="ENOENT")E0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,_)})}throw w}}static async hasPendingInbox($,Z,J=v$($)){if(await T1(J,Z,async({inboxPath:X})=>{try{return(await BX(X)).size>0}catch(z){if(z.code!=="ENOENT")throw z;return!1}}))return!0;if(J.kind==="acp-remote")return!1;if(j0()?.agentTeamsEnabled!==!0)return!1;let Q=(await B$.getInstance(t()).listTeams()).filter((X)=>X.deletedAt===void 0&&X.leadSessionId===Z&&X.workspaceRoot===$);for(let X of Q)if((await new H$(X.name,t()).listPending("team-lead")).length>0)return!0;return!1}static async hasDurableFollowUpInbox($,Z,J=v$($)){return T1(J,Z,async({inboxPath:Y})=>{try{return await BX(Y),!0}catch(Q){if(Q.code!=="ENOENT")throw Q;return!1}})}static async hasActiveGoal($,Z,J=v$($)){return V0.hasActiveGoal($,Z,J)}static async hasRecoverableTurn($,Z,J=v$($)){return new _2($,100,void 0,J).hasRecoverableTurn(Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??C()}get executionRoot(){return this.workspace.executionRoot}get resourceRoot(){return this.workspace.resourceRoot}isRemoteWorkspace(){return this.workspace.kind==="acp-remote"}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return V2(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=g1.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued,maxQueuedBytes:$.maxQueuedBytes}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",Y={taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}},Q=this.workspace.kind==="acp-remote"?await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,Y):await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,Y);return W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:Q.taskStatus,...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,taskAdmissionPaused:g1.getStats().paused,updatedAt:Q.lastMessageTime}),Q}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=g1.getStats();W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,taskAdmissionPaused:Z.paused,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}beginProviderRecovery(){let $=this.providerRecovery.begin();return this.providerRecoveryGeneration=$,this.publishProviderRecovery(this.providerRecovery.snapshot()),$}observeProviderRecovery($,Z){let J=this.providerRecovery.observe($,Z);if(J)this.publishProviderRecovery(J);return J}clearProviderRecovery($){let Z=this.providerRecovery.clear($);if(this.providerRecoveryGeneration?.id===$.id)this.providerRecoveryGeneration=void 0;if(Z)this.publishProviderRecovery(Z);return Z}getProviderRecoveryProjection(){return this.providerRecovery.snapshot()}publishProviderRecovery($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"provider.recovery",{recovery:$})}beginTurnActivity(){let $=this.turnActivity.begin();return this.turnActivityGeneration=$,this.publishTurnActivity(this.turnActivity.snapshot()),$}observeTurnActivity($,Z){let J=this.turnActivity.observe($,Z);if(J)this.publishTurnActivity(J);return J}clearTurnActivity($){let Z=this.turnActivity.clear($);if(this.turnActivityGeneration?.id===$.id)this.turnActivityGeneration=void 0;if(Z)this.publishTurnActivity(Z);return Z}getTurnActivityProjection(){return this.turnActivity.snapshot()}publishTurnActivity($){W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"turn.activity",{activity:$})}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return this.workspace.kind==="acp-remote"?s.loadRemoteSessionModelContext(this.sessionId,this.workspaceRoot,this.workspace.descriptor):s.loadSessionModelContext(this.sessionId,this.workspaceRoot)}async askSideQuestion($,Z={}){if(!this.initialized||!this.chatService)throw Error("Session runtime is not initialized");let J=this.sideConversationOperations.enter(Z.signal),Y=this.config.permissionMode??"default",Q;try{if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");Q=this.createToolExecutor({permissionMode:Y});let X=Q.getRegistry();await X.waitForMcpCatalogIdle(J.signal);let z=[this.loadModelContext(),Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},replaceDefault:Z.systemPrompt,append:Z.appendSystemPrompt,...Y==="plan"?{mode:"plan"}:{},includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:this.executionRoot},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot}})],[W,V]=await Promise.all(z).catch(async(H)=>{throw await Promise.allSettled(z),H});if(J.signal.aborted)throw new DOMException("Side conversation aborted","AbortError");let U=SX(V.prompt,X);if(!U)throw Error("Side conversation system prompt is empty");return await MJ({question:$,sessionId:this.sessionId,workspaceRoot:this.executionRoot,systemPrompt:U,messages:W,tools:X.getFunctionDeclarationsByMode(Y),chatService:this.chatService,signal:J.signal,providerRecoveryBudgetMs:this.config.providerForegroundRecoveryMs})}finally{Q?.dispose(),J.release()}}getStartupTurnRecovery(){return this.startupTurnRecovery?structuredClone(this.startupTurnRecovery):void 0}getTurnRecoveryAssessment(){if(this.startupTurnRecoveryAcknowledged)return{state:"none"};return E3(this.startupTurnRecovery)}takeStartupTurnRecoveryAssessment(){if(this.startupTurnRecoveryAssessmentTaken)return{state:"none"};return this.startupTurnRecoveryAssessmentTaken=!0,this.getTurnRecoveryAssessment()}async acknowledgeStartupTurnRecovery(){let $=this.startupTurnRecovery;if($?.outcome==="aborted")await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeTurnRecovery(this.sessionId,$.turnId);this.startupTurnRecoveryAcknowledged=!0,this.startupTurnRecoveryAssessmentTaken=!0,await this.activeTurnMailbox?.setRecoveryProtectedIds([])}async getRecoveredFinalResponse(){let $=this.startupTurnRecovery;if(!$||$.outcome!=="completed")return;let J=(await this.loadModelContext()).findLast((z)=>z.role==="assistant"&&DX(z)?.turnId===$.turnId&&JSON.stringify(DX(z))===JSON.stringify($.finalization));if(!J||typeof J.content!=="string")return;let Y=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,Q=Y?.structuredOutput,X=Q&&typeof Q==="object"&&!Array.isArray(Q)&&Q.output&&typeof Q.output==="object"&&!Array.isArray(Q.output)?Q.output:void 0;return{turnId:$.turnId,content:J.content,...X?{structuredOutput:X}:{},...typeof Y?.structuredOutputSchemaDigest==="string"?{structuredOutputSchemaDigest:Y.structuredOutputSchemaDigest}:{}}}takeStartupAdoptedToolResults(){let $=this.startupAdoptedToolResults;return this.startupAdoptedToolResults=[],structuredClone($)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}captureBrowserScreenshot($){if(!this.browserRuntime)throw new f("browser_page_not_found","The Agent browser is not available");return this.browserRuntime.screenshot($)}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return m0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return z8(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return z8($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??jX}getProjectRuleCatalog(){return this.agentResources?.projectRules??EX.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,Y){if(this.isRemoteWorkspace())return this.getProjectRuleCatalog().contextualRules(this.projectRoot,[],Y);let Q=new Set;try{let V=this.baseRegistry.get($)?.build(Z);for(let U of V?.getAffectedPaths()??[])if(U)Q.add(U)}catch{}let X=(V)=>{if(typeof V==="string"&&V.trim())Q.add(V)};if(["Read","Edit","Write"].includes($))X(Z.file_path);else if($==="NotebookEdit")X(Z.notebook_path);else if(["Grep","Glob"].includes($))X(Z.path);else if($==="Bash")X(Z.cwd);let z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(z?.affected_paths))for(let V of z.affected_paths)X(V);if(Array.isArray(z?.changes)){for(let V of z.changes)if(V&&typeof V==="object")X(V.path)}let W=[...Q].map((V)=>F0.isAbsolute(V)?F0.resolve(V):F0.resolve(this.workspaceRoot,V)).flatMap((V)=>{let U=F0.relative(this.workspaceRoot,V);if(U===""||!U.startsWith("..")&&!F0.isAbsolute(U))return[F0.resolve(this.projectRoot,U)];let H=F0.relative(this.projectRoot,V);return H===""||!H.startsWith("..")&&!F0.isAbsolute(H)?[V]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,Y)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async prepareGoalContinuation($,Z={}){try{let J=await o6($,{configDir:t(),stateStorage:this.stateStorage}),Y=Z.observeStall===!1&&$.frontierStall?.digestSha256===J.frontier.digestSha256,Q=Z.observeStall===!1?Y?$.frontierStall:void 0:y3($.executionFrontier,J.frontier,{taskEffect:"none",prematureStopCount:$.prematureStop?.consecutiveCount??0,verificationStallCount:$.verificationStall?.consecutiveCount??0},$.frontierStall);return{ok:!0,goal:await this.goalStore.recordExecutionFrontier(J.frontier,Q,{preserveStall:Y}),...J}}catch(J){let Y=J instanceof Error?J.message:String(J),Q=null;try{Q=await this.goalStore.pause(`goal task list unavailable (${a2($)}): ${Y}`)}catch(X){E0.warn(`[SessionRuntime] Failed to pause Goal after frontier failure: ${X instanceof Error?X.message:String(X)}`)}return{ok:!1,goal:Q,error:{code:"task_list_unavailable",message:`Goal execution frontier unavailable: ${Y}`}}}}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await C$.getChangeSummary(this.sessionId):void 0;return q1.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0,this.workspace.kind==="acp-remote"?this.workspace.descriptor:void 0)}static async persistTaskStatus($,Z,J,Y,Q,X){let z=new Date().toISOString(),W=J==="failed"&&Y!==void 0?W8(Y):void 0,V=W?.message??(typeof Y==="string"?Y.slice(0,500):void 0),U={taskStatus:J,taskStatusReason:V??null,taskFailure:W??null,...Q!==void 0?{taskDiffStat:Q}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:z,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:z,taskOwnerPid:null}},H=X?await s.updateRemoteSessionMetadata($,Z,X,U):await s.updateSessionMetadata($,Z,U);return W0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:H.taskStatus,...V?{taskStatusReason:V}:{},...W?{taskFailure:W}:{},...H.taskStartedAt?{taskStartedAt:H.taskStartedAt}:{},...H.taskCompletedAt?{taskCompletedAt:H.taskCompletedAt}:{},...H.taskDiffStat?{taskDiffStat:H.taskDiffStat}:{},...H.taskQueuePosition?{taskQueuePosition:H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{taskQueueDepth:H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:H.taskConcurrencyLimit}:{},updatedAt:H.lastMessageTime}),H}createGoal($,Z){return this.goalStore.create($,Z)}async beginGoalTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.beginTurn(),Y=await this.goalStore.prepareTurnBinding(J.id,!0);if(!Y||Y.goalId!==$.goalId||Y.objective!==$.objective)return await Z.finishTurn(J).catch(()=>{return}),null;let Q=!1;try{await this.saveTurnStart(J,"goal",[],{goalId:Y.goalId,...Y.lineage}),Q=!0;let X=await this.goalStore.commitTurnBinding(Y);if(!X)throw Error("Goal changed before turn lineage commit");return{handle:J,goal:X}}catch(X){throw await this.releaseFailedTurnStart(J,Q),X}}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}clearGoalFrontierStall(){return this.goalStore.clearFrontierStall()}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),s.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){this.assertRewindIdle();let Z=await s.rewindSession(this.sessionId,this.workspaceRoot,$);return this.backgroundTaskChildIds=await this.getExecutionEngine().getContextManager().persistentStore.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear(),Z}listSubagents(){return D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return $$.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return $$.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=D0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},Y=Z.getAgent($.agentId,J);if(!Y)throw Error(`Subagent not found in this session: ${$.agentId}`);let Q=this.subagentRegistry?.getSubagent(Y.subagentType),X=Y.configSnapshot?{...Y.configSnapshot}:Q;if(!X)throw Error(`Subagent configuration is unavailable: ${Y.subagentType}`);let z=Z.resumeAgent({agentId:Y.id,prompt:$.prompt,config:X,owner:J,permissionMode:X.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:async(V)=>{await this.notifyBackgroundSubagentCompleted(V.id),await $.onCompleted?.(V)}});if(!z)throw Error(`Subagent cannot be resumed: ${Y.id}`);let W=Z.getAgent(z.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${z.agentId}`);return{source:z.source,session:W}}async beginTurn($="goal"){let Z=await this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),Y=await this.materializeUserMessage($,Z?.metadata),Q=await J.prepareInputTurn(Y.content,{...Z,...Y.metadata?{metadata:Y.metadata}:{}});if(!Q.accepted)return Q;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.handle.id,!1);if(await this.saveTurnStart(Q.handle,Q.mode==="direct"?"user":"pending",await J.reservedMessageIds(Q.handle),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before user turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q.handle,X),z}}async enqueueSteering($,Z){let J=(Z?.origin??"user")==="user"?await this.materializeUserMessage($,Z?.metadata):{content:$,metadata:Z?.metadata,offloaded:!1},Y=await this.getActiveTurnMailbox().enqueue(J.content,{...Z,...J.metadata?{metadata:J.metadata}:{}});if(Y.accepted&&Y.delivery==="current_turn"&&Y.turnId)await this.goalStore.invalidateTurnLineageRoot(Y.turnId);if(Y.accepted)this.signalBackgroundSubagentCompletionWaiters();return Y}materializeUserMessage($,Z){return this.userPromptArtifactStore.materialize($,Z)}restoreUserMessage($,Z){return this.userPromptArtifactStore.restore($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async getRecoveredEmptyFinalState($){let Z=this.startupTurnRecovery;if(!Z||Z.outcome!=="aborted")return{hadSuccessfulToolResult:!1,correctionSpent:!1};let J=await this.getClaimedTurnMessageIds($),Y=new Set(Z.inputMessageIds);if(J.length===0||J.some((Q)=>!Y.has(Q)))return{hadSuccessfulToolResult:!1,correctionSpent:!1};return{hadSuccessfulToolResult:Z.hadSuccessfulToolResult,...Z.interruptedToolCallCount?{interruptedToolCallCount:Z.interruptedToolCallCount}:{},...Z.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},correctionSpent:Z.emptyFinalCorrectionSpent}}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},Y=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let z=await this.getActiveTurnMailbox().claimedMessageIds($);await Y.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},z),await this.getActiveTurnMailbox().acknowledge(z)}else{let z=this.startupTurnRecovery,W=Z.preserveStartupRecovery&&z?.outcome==="aborted"?{hadSuccessfulToolResult:z.hadSuccessfulToolResult,interruptedToolCallCount:z.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:z.allSuccessfulToolResultsSafeForResume,correctionSpent:z.emptyFinalCorrectionSpent}:await this.getRecoveredEmptyFinalState($),V=await this.getActiveTurnMailbox().claimedMessageIds($),U=await Y.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs,recovery:{version:3,inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,interruptedToolCallCount:W.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:W.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:W.correctionSpent}},Z.acknowledgeInput?{acknowledgeInputMessageIds:V}:void 0);if(this.startupTurnRecovery=U.recovery,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,await this.getActiveTurnMailbox().setRecoveryProtectedIds(U.recovery?.inputMessageIds??[]),Z.acknowledgeInput)await this.getActiveTurnMailbox().acknowledge(U.acknowledgedInputMessageIds)}let Q=await this.getActiveTurnMailbox().finishTurn($,Z);if(!Q)return;let X=!1;try{let z=await this.goalStore.prepareTurnBinding(Q.id,!1);if(await this.saveTurnStart(Q,"pending",await this.getActiveTurnMailbox().reservedMessageIds(Q),z?{goalId:z.goalId,...z.lineage}:void 0),X=!0,z&&!await this.goalStore.commitTurnBinding(z))throw Error("Goal changed before pending turn lineage commit");return Q}catch(z){throw await this.releaseFailedTurnStart(Q,X),z}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;let J=!1;try{let Y=await this.goalStore.prepareTurnBinding(Z.id,!1);if(await this.saveTurnStart(Z,"pending",await $.reservedMessageIds(Z),Y?{goalId:Y.goalId,...Y.lineage}:void 0),J=!0,Y&&!await this.goalStore.commitTurnBinding(Y))throw Error("Goal changed before pending turn lineage commit");return Z}catch(Y){throw await this.releaseFailedTurnStart(Z,J),Y}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}async getFollowUpQueueSnapshot(){return this.getActiveTurnMailbox().getFollowUpQueueSnapshot()}async mutateFollowUpQueue($){return this.getActiveTurnMailbox().mutateFollowUpQueue($)}isIdleForResidency(){if(!this.initialized||this.disposing||this.hasActiveTurn()||this.hasTurnOwner()||this.sideConversationOperations.stats().active>0||this.getPendingSteeringCount()>0||this.executorCatalogs.size>0)return!1;if(!this.isRemoteWorkspace()&&Y0.getInstance().listForSession(this.sessionId).some((Z)=>Z.status==="running"))return!1;let $={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(D0.getInstance().listForSession($).some((Z)=>Z.status==="running")||this.getBackgroundTaskChildrenState()!=="none")return!1;return!$$.getInstance().hasActive($)}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async notifyBackgroundSubagentCompleted($){await iZ.dispatch(this.backgroundSubagentCompletionOwner,$)}registerBackgroundSubagent($){this.backgroundTaskChildIds.add($),this.backgroundTaskCompletionSettledIds.delete($)}async waitForBackgroundSubagentFollowUp($,Z){while(!Z?.aborted){if(this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.reconcileBackgroundSubagentCompletions(),this.disposing||!this.initialized||!this.activeTurnMailbox)return!1;if(await this.hasUnclaimedPendingInput($))return!0;let J=this.backgroundSubagentCompletionRevision,Y=this.getBackgroundTaskChildrenState();if(Y==="none")return!1;if(Y==="terminal_pending")continue;await this.waitForBackgroundSubagentSignal(J,Z)}return!1}async hasUnclaimedPendingInput($){let Z=new Set(await this.getActiveTurnMailbox().claimedMessageIds($));return this.getActiveTurnMailbox().pendingMessages().some((J)=>!Z.has(J.id))}signalBackgroundSubagentCompletionWaiters(){this.backgroundSubagentCompletionRevision++;for(let $ of this.backgroundSubagentCompletionWaiters)$();this.backgroundSubagentCompletionWaiters.clear()}async waitForBackgroundSubagentSignal($,Z){if(Z?.aborted||$!==this.backgroundSubagentCompletionRevision)return;await new Promise((J)=>{let Y=!1,Q=()=>{if(Y)return;Y=!0,this.backgroundSubagentCompletionWaiters.delete(Q),Z?.removeEventListener("abort",Q),J()};if(this.backgroundSubagentCompletionWaiters.add(Q),Z?.addEventListener("abort",Q,{once:!0}),Z?.aborted||$!==this.backgroundSubagentCompletionRevision)Q()})}getBackgroundTaskChildrenState(){if(this.isRemoteWorkspace())return"none";if(this.backgroundTaskChildIds.size===0)return"none";let $={sessionId:this.sessionId,projectPath:this.workspaceRoot},Z=y0.getInstance().listSessions().filter((J)=>t0(J,$)&&this.backgroundTaskChildIds.has(J.id)&&J.background===!0);if(Z.some((J)=>J.status!=="running"&&!this.backgroundTaskCompletionSettledIds.has(J.id)))return"terminal_pending";return Z.some((J)=>J.status==="running")?"running":"none"}async reconcileBackgroundSubagentCompletionSink($){try{await this.reconcileBackgroundSubagentCompletions($)}finally{this.signalBackgroundSubagentCompletionWaiters()}}async attachBackgroundSubagentCompletionDispatcher(){if(this.backgroundSubagentCompletionRegistration)return;this.backgroundSubagentCompletionRegistration=await iZ.attach(this.backgroundSubagentCompletionOwner,{reconcile:($)=>this.reconcileBackgroundSubagentCompletionSink($)})}async reconcileBackgroundSubagentCompletions($){return this.backgroundSubagentCompletionMutex.runExclusive(async()=>{if(!this.activeTurnMailbox||!this.executionEngine)return 0;let Z=this.getExecutionEngine().getContextManager().persistentStore;if(this.backgroundTaskChildIds.size===0)return 0;let J=y0.getInstance(),Y={sessionId:this.sessionId,projectPath:this.workspaceRoot},Q=$?[J.loadSession($)].filter((z)=>Boolean(z)):J.listSessions().filter((z)=>t0(z,Y)),X=0;for(let z of Q){if(!this.backgroundTaskChildIds.has(z.id)||this.backgroundTaskCompletionSettledIds.has(z.id)||z.status==="running")continue;let W=z.resumedFrom?J.loadSession(z.resumedFrom):void 0,V=lQ(z,Y,W);if(!V){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let U=await Z.persistBackgroundSubagentCompletion(this.sessionId,V);if(!U.eligible||U.acknowledged){this.backgroundTaskCompletionSettledIds.add(z.id);continue}let H=await this.activeTurnMailbox.enqueueBackgroundSubagentCompletion(V);if(!H.accepted){E0.warn(`[SessionRuntime ${this.sessionId}] Background subagent completion queue is full for ${z.id}`);continue}if(H.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);if(this.backgroundTaskCompletionSettledIds.add(z.id),H.duplicate)continue;if(X++,H.queue)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"follow_up.queue.changed",{queue:H.queue});W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"subagent.completion.queued",{childSessionId:z.id,inboxMessageId:V.inboxMessageId,status:z.status,type:z.subagentType,description:z.description,summary:V.subagentRef.subagentSummary,resumedFrom:z.resumedFrom,rootAgentId:z.rootAgentId,resumeDepth:z.resumeDepth,verificationVerdict:z.result?.verificationVerdict,queued:H.queued,delivery:H.delivery})}return X})}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[])}async recoverTeamLeadMessages(){if(this.config.agentTeamsEnabled!==!0)return;let $=(await B$.getInstance(t()).listTeams()).filter((Z)=>Z.deletedAt===void 0&&Z.leadSessionId===this.sessionId&&Z.workspaceRoot===this.workspaceRoot);for(let Z of $){let J=new H$(Z.name,t()),Y=await J.listPending("team-lead");for(let Q of Y)if((await this.enqueueSteering(N2(Q),{allowBeforeTurn:!0,messageId:Q.id,origin:"team_message",metadata:Z8(Q)})).accepted)await J.markDelivered([Q.id])}}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=mD(12),Y=this.hasTurnOwner(),Q=Z.signal??new AbortController().signal,X=async(G)=>{let D=G.type==="started"?{executionId:G.executionId,command:G.command,auxiliary:Y}:G.type==="output"?{executionId:G.executionId,stream:G.stream,chunk:G.chunk,streamedBytes:G.streamedBytes,streamTruncated:G.streamTruncated,auxiliary:Y}:{executionId:G.executionId,messageId:G.messageId,record:G.record,auxiliary:Y,delivery:G.delivery,queued:G.queued};W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${G.type}`,D),await Z.onEvent?.(G)},z=await TX($,{executionId:J,cwd:this.executionRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:Q,timeoutMs:Z.timeoutMs,executor:this.workspace.kind==="acp-remote"?this.workspace.terminal?this.options.userShellExecutor??$9():$9():this.options.userShellExecutor,onEvent:async(G)=>{if(G.type!=="completed")await X({...G,auxiliary:Y})}}),W=RX(z),U=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...Y?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(z))},this.options.subagentInfo),H=Y?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0,origin:"user_shell"}):void 0;if(H?.delivery==="current_turn"&&H.turnId)await this.goalStore.invalidateTurnLineageRoot(H.turnId);let B={executionId:J,messageId:U,record:z,modelContent:W,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{},...H?.queue?{queue:H.queue}:{}};return await X({type:"completed",executionId:J,messageId:U,record:z,auxiliary:Y,...H?.delivery?{delivery:H.delivery}:{},...H?{queued:H.queued}:{}}),B})}async initialize(){if(this.initialized)return;this.sessionLease=await c4.acquireForStorage(this.sessionId,this.stateStorage);try{if(!this.isRemoteWorkspace())await new b1(this.workspaceRoot,this.sessionId).reapOrphans(),await Y0.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),await vJ(this.workspaceRoot),await D0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await cD(this.workspaceRoot);if(await this.loadAgentResources(),!this.isRemoteWorkspace()){let W=x0.getInstance();if(W.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),W.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),this.projectRoot!==this.workspaceRoot)W.inheritProjectConfig(this.projectRoot,this.workspaceRoot);W.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??W.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??W.getConfig(this.projectRoot));let V=await W.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!V.proceed)throw Error(V.warning||"SessionStart hook blocked initialization");if(V.warning)E0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${V.warning}`);let U=_X(V.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...U}),this.config.env=this.sessionEnvironment,W.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new e8({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new cZ({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment})}await this.validateSystemPromptConfig(),this.activeTurnMailbox=await w6.create(this.workspaceRoot,this.sessionId,this.stateStorage),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let $=this.getExecutionEngine().getContextManager().persistentStore;this.backgroundTaskChildIds=await $.loadBackgroundTaskChildIds(this.sessionId),this.backgroundTaskCompletionSettledIds.clear();let Z=await $.loadInterruptedToolCalls(this.sessionId),J=new Map,Y={sessionId:this.sessionId,projectPath:this.workspaceRoot};if(!this.isRemoteWorkspace()){let W=y0.getInstance();for(let V of Z){if(V.toolName!=="Task"||!V.input||typeof V.input!=="object"||Array.isArray(V.input))continue;let U=V.input.subagent_session_id;if(typeof U!=="string")continue;let H=W.loadSession(U);if(!H)continue;let B=HQ(V,H,Y);if(B)J.set(V.toolCallId,B)}}let Q=await $.recoverInterruptedTurn(this.sessionId,{adoptedToolResults:J});if(Q)this.startupAdoptedToolResults=Z.flatMap((W)=>{let V=J.get(W.toolCallId);return V?[{call:W,result:V}]:[]});let X=await $.loadLatestGoalFinalization(this.sessionId),z=X?await this.goalStore.reconcileFinalizationReceipt(X.finalization.goalFinalization):null;if(z?.finalized)W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"goal.updated",{goal:z.goal});if(this.startupTurnRecovery=Q??(X&&z?.finalized?{turnId:X.turnId,outcome:"completed",inputMessageIds:X.finalization.inputMessageIds,hadSuccessfulToolResult:!1,emptyFinalCorrectionSpent:!1,finalization:X.finalization}:void 0),await this.activeTurnMailbox.setRecoveryProtectedIds(this.startupTurnRecovery?.outcome==="aborted"?this.startupTurnRecovery.inputMessageIds:[]),this.startupTurnRecovery?.outcome==="completed")await this.reloadPendingInbox();if(!this.isRemoteWorkspace())await this.recoverTeamLeadMessages(),await this.attachBackgroundSubagentCompletionDispatcher();if(Q)E0.warn(`[SessionRuntime ${this.sessionId}] recovered ${Q.outcome} turn ${Q.turnId}`);this.initialized=!0,E0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,Y=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,Q=$.reasoningEffort??this.selectedReasoningEffort,X=$.serviceTier??this.selectedServiceTier,z=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(z8(W,this.getCommunicationStyleCatalog()),Y&&(Y!==this.currentModelId||Q!==this.selectedReasoningEffort||X!==this.selectedServiceTier||z!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(Y),Y!==this.currentModelId?"切换模型":Q!==this.selectedReasoningEffort?"切换推理强度":X!==this.selectedServiceTier?"切换服务等级":"切换输出详略",Q,X,z);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=Q,this.selectedServiceTier=X,this.selectedResponseVerbosity=z,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new H1;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J="ReadPromptArtifact",Y=$.toolWhitelist?[...new Set([...$.toolWhitelist,J])]:void 0,Q=$.toolBlacklist?.filter((B)=>B!==J),X=Y?new Set(Y):null,z=Q?new Set(Q):null;for(let B of this.baseRegistry.getBuiltinTools()){if(z?.has(B.name))continue;if(!X||X.has(B.name))Z.register(B)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),X,z));let W=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((B)=>!z?.has(B)&&(!X||X.has(B))))for(let B of $$.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:G,...D}=B;Z.queueMcpTaskChange({revision:0,...D})}this.executorCatalogs.set(Z,{allowed:X,blocked:z});let U={...this.config.permissions,...$.permissions},H=$.permissionMode??this.config.permissionMode??"default";return new z6(Z,{permissionConfig:U,permissionMode:H,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:Y,toolBlacklist:Q,workspaceToolPolicy:this.workspaceToolPolicy,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,executionRoot:this.executionRoot,workspaceKind:this.workspace.kind,environment:this.sessionEnvironment,permissionMode:H,foregroundCommandHandoffMs:this.config.bashForegroundHandoffMs,mcpSamplingHandler:this.handleMcpSampling,notifyBackgroundSubagentCompleted:(B)=>this.notifyBackgroundSubagentCompleted(B),registerBackgroundSubagent:(B)=>this.registerBackgroundSubagent(B)},...this.lspManager?{lspManager:this.lspManager}:{},...H==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){if(this.disposePromise)return this.disposePromise;return this.disposing=!0,this.disposePromise=(async()=>{let $,Z=async(_,L)=>{try{await L()}catch(F){$??=F,E0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${_} during cleanup`,F)}},J=this.chatService,Y=this.sessionMcpRegistry,Q=this.mcpCatalogListener,X=this.mcpContentCatalogListener,z=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,V=this.mcpLogListener,U=this.mcpInstructionsListener,H=this.mcpTaskListener,B=this.sessionLease,G=this.autoVerifyRuntime,D=this.lspManager,w=this.browserRuntime,q=this.backgroundSubagentCompletionRegistration;if(this.providerRecoveryGeneration)this.clearProviderRecovery(this.providerRecoveryGeneration);if(this.turnActivityGeneration)this.clearTurnActivity(this.turnActivityGeneration);if(await Z("stop side conversations",()=>this.sideConversationOperations.shutdown("session-runtime-dispose")),await Z("close the Session browser",()=>w?.dispose()),await Z("dispose the background subagent completion registration",()=>q?.dispose()),this.backgroundSubagentCompletionRegistration=void 0,this.signalBackgroundSubagentCompletionWaiters(),this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.startupTurnRecovery=void 0,this.startupTurnRecoveryAcknowledged=!1,this.startupTurnRecoveryAssessmentTaken=!1,this.startupAdoptedToolResults=[],this.backgroundTaskChildIds.clear(),this.backgroundTaskCompletionSettledIds.clear(),this.currentModelMaxContextTokens=void 0,this.baseRegistry=new H1,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,this.browserRuntime=void 0,!this.isRemoteWorkspace())await Z("kill the session background processes",()=>Y0.getInstance().killSession(this.sessionId));if(await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>f0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>G?.dispose()),await Z("stop the session LSP servers",()=>D?.dispose()),!this.isRemoteWorkspace())await Z("release the session hook model resources",()=>x0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>C$.releaseSession(this.sessionId));if(await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>$$.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(Y&&Q)Y.off("catalogChanged",Q);if(Y&&X)Y.off("contentCatalogChanged",X);if(Y&&z)Y.off("resourceUpdated",z);if(Y&&W)Y.off("connectionLifecycleChanged",W);if(Y&&V)Y.off("log",V);if(Y&&U)Y.off("instructionsChanged",U);if(H)$$.getInstance().off("taskChanged",H);await Y?.disconnectAll()}),await Z("release the session lease",()=>B?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $})(),this.disposePromise}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((Y)=>Y.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[],Y){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{},...Y?{goalLineage:Y}:{}})}async releaseFailedTurnStart($,Z){if(Z)try{await this.finishTurn($,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}});return}catch{}await this.getActiveTurnMailbox().finishTurn($).catch(()=>{return})}assertRewindIdle(){if(this.isRemoteWorkspace())throw Error("Rewind is unavailable for ACP remote workspaces");if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(Y0.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(D0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,Y,Q){let X=m0($,this.config,J,this.modelResources.catalog,Y,Q);E0.debug(`${Z} ${X.displayName} (${$.model})`);let z=X.model.contextWindow,W=await S4(X.chat),V=this.initialized?this.chatService:void 0,U=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new V6(W,U,this.workspaceRoot,this.stateStorage),this.currentModelMaxContextTokens=z,this.currentModelId=$.id,this.currentReasoning=X.reasoning,this.currentServiceTier=X.serviceTier,this.currentResponseVerbosity=X.responseVerbosity;let H=V;try{await H?.dispose?.()}catch(B){E0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,B)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(!this.options.auxiliaryReadOnly&&this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&!this.options.auxiliaryReadOnly&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(!this.options.auxiliaryReadOnly&&Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await Y1({...this.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.resourceRoot},includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),...this.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.projectRoot},environmentOptions:{...u1,workingDirectory:this.executionRoot}})}catch(J){E0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){if(this.workspace.kind==="acp-remote"){await s.updateRemoteSessionMetadata(this.sessionId,this.workspaceRoot,this.workspace.descriptor,$);return}try{await s.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof fX||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await s.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){this.browserRuntime??=new n8(this.workspaceRoot,this.sessionId,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposeArtifactPaths:!U0(this.sessionId)});let $=await v4({sessionId:this.sessionId,configDir:t(),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle,agentTeamsEnabled:this.config.agentTeamsEnabled===!0,stateStorage:this.stateStorage,userPromptArtifactStore:this.userPromptArtifactStore,browserRuntime:this.browserRuntime}),Z=iJ($.filter((J)=>!J.name.startsWith("mcp__")),this.workspaceToolPolicy);this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=e0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new o2(`${this.stateStorage.kind==="acp-remote"?this.workspaceRoot:this.projectRoot}\x00${this.sessionId}`,{storageRoot:this.stateStorage.kind==="acp-remote"?this.stateStorage.root:t(),stateStorage:this.stateStorage,exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(U)=>{this.applyMcpCatalog(U,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let Y=(U)=>{this.applyMcpContentCatalog(U)},Q=(U)=>{this.applyMcpResourceUpdated(U)},X=(U)=>{this.applyMcpConnectionChange(U)},z=(U)=>{this.applyMcpLog(U)},W=(U)=>{this.applyMcpInstructions(U)},V=(U)=>{if(U.owner.sessionId!==this.sessionId||F0.resolve(U.owner.projectPath)!==F0.resolve(this.workspaceRoot))return;this.applyMcpTask(U);let{owner:H,result:B,...G}=U;W0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",G)};this.mcpContentCatalogListener=Y,this.mcpResourceUpdatedListener=Q,this.mcpConnectionListener=X,this.mcpLogListener=z,this.mcpInstructionsListener=W,this.mcpTaskListener=V,Z.on("contentCatalogChanged",Y),Z.on("resourceUpdated",Q),Z.on("connectionLifecycleChanged",X),Z.on("log",z),Z.on("instructionsChanged",W),$$.getInstance().on("taskChanged",V);for(let[U,H]of Object.entries($))try{let B=H.type==="stdio"?{...this.sessionEnvironment,...H.env}:void 0;await Z.registerServer(U,H.type==="stdio"?{...H,...B&&Object.keys(B).length>0?{env:B}:{}}:H)}catch(B){E0.warn(`Warning: MCP server "${U}" connection failed:`,B)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(Y6(Z)),this.baseRegistry.registerAll(KZ(Z))}catch($){E0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((Y)=>!J?.has(Y.name)&&(!Z||Z.has(Y.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,Y]of this.executorCatalogs){let Q=this.filterMcpTools($.tools,Y.allowed,Y.blocked),X=(V)=>!Y.blocked?.has(V)&&(!Y.allowed||Y.allowed.has(V)),z={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(X),removed:$.removed.filter(X),updated:$.updated.filter(X)},W=z.added.length>0||z.removed.length>0||z.updated.length>0;J.replaceMcpTools(Q,Z&&W?z:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,Y]of this.executorCatalogs)if(Z.some((X)=>!Y.blocked?.has(X)&&(!Y.allowed||Y.allowed.has(X))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...Y}=$;for(let[Q,X]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!X.blocked?.has(W)&&(!X.allowed||X.allowed.has(W))))Q.queueMcpTaskChange(Y)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),Y=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return qX(Y,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:this.isRemoteWorkspace()?AX(this.resourceRoot):await c0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function Z9(){let $=await B0.getInstance().reload();q0().config.actions.setConfig($),await e0.getInstance().disconnectAll(),kX(),await c0(C())}import KF from"fuse.js";import c$ from"node:path";import{Mutex as pD}from"async-mutex";var p$=new pD;async function xX($){let Z=$.getWorkspaceRoot();await f$(Z,async(J)=>{await $.reapplyEnabledSettings(),i1(Z),await l1(Z),await J9(J)})}async function lD($){let Z=$.getWorkspaceRoot();return f$(Z,async(J)=>{i1(Z);let Y=await $.refresh();return await l1(Z),await J9(J),Y})}async function Y9($){return f$($,async(Z)=>{let J=Array.from(new Set([Z.plugins,...W2.getInitializedInstances()])),Y;for(let Q of J){let X=await lD(Q);if(Q===Z.plugins)Y=X}return Y??{plugins:[],errors:[]}})}async function iD($,Z){let J=c$.resolve($),Y=h1();await Promise.all([Y.removePluginSetting(Z,{scope:"global",immediate:!0}),Y.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),Y.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function rD($){return c$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function IX($,Z){if(rD(Z)&&!vX(await a0.getInstance().getStatus($)))throw Error("Local plugin sources require a trusted workspace")}async function V8($,Z,J,Y="local"){return p$.runExclusive(async()=>{let Q=c$.resolve($);return f$(Q,async(X)=>{let z=X.plugins.get(Z);if(!z)throw Error(`Plugin not found: ${Z}`);if(z.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await h1().save({enabledPlugins:{[Z]:J}},{scope:Y,projectDir:Q,immediate:!0});let W=Y==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let H of W)await xX(H);let V=X.plugins.get(Z);if(!V)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let U=await B0.getInstance().loadWorkspacePluginSettingsResolution(Q);return{name:Z,requestedEnabled:J,effectiveEnabled:V.status==="active",scope:Y,source:V.source,status:V.status,effectiveScope:U.settings[Z]?.effectiveScope??"default"}})})}async function U8($){return p$.runExclusive(()=>f$($,async(Z)=>{i1(Z.workspaceRoot);let J=await Z.plugins.refresh();return await l1(Z.workspaceRoot),{registry:Z.plugins,discovery:J}}))}async function Q9($,Z,J="global"){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q={...Z,...yX(Z)};return await h1().save({pluginSourcePolicy:Q},{scope:J,projectDir:Y,immediate:!0}),f$(Y,async(X)=>{let z=J==="global"?Array.from(new Set([X.plugins,...W2.getInitializedInstances()])):[X.plugins];for(let W of z)await xX(W);return B0.getInstance().loadWorkspacePluginSourcePolicy(Y)})})}async function X9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().install(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function z9($,Z,J={}){return p$.runExclusive(async()=>{let Y=c$.resolve($),Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y),X=await G$().update(Z,{...J,workspaceRoot:Y,policy:Q});if(!X.success)return{result:X};let z=await Y9(Y);return{result:X,discovery:z}})}async function W9($,Z,J=!1){return p$.runExclusive(async()=>{let Y=c$.resolve($);return f$(Y,async(Q)=>{let X=Q.plugins.getAll().filter((V)=>V.manifest.name!==Z&&V.manifest.dependencies?.[Z]!==void 0).map((V)=>V.manifest.name).sort();if(X.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${X.join(", ")}`}};let z=await G$().uninstall(Z,J);if(!z.success)return{result:z};await iD(Y,Z);let W=await Y9(Y);return{result:z,discovery:W}})})}async function V9($,Z,J){return p$.runExclusive(async()=>{let Y=c$.resolve($);await IX(Y,Z);let Q=await B0.getInstance().loadWorkspacePluginSourcePolicy(Y);return G$().addMarketplace(Z,{workspaceRoot:Y,ref:J,policy:Q})})}async function U9($,Z){return p$.runExclusive(async()=>{let J=c$.resolve($),Y=await B0.getInstance().loadWorkspacePluginSourcePolicy(J);return G$().refreshMarketplace(Z,Y)})}async function H9($,Z=!1){return p$.runExclusive(()=>G$().removeMarketplace($,Z))}var nD={name:"btw",description:"Ask a side question without changing the main conversation",fullDescription:"Ask one context-aware question in an isolated, tool-free conversation.",usage:"/btw <question>",category:"conversation",examples:["/btw What did the last test failure mean?"],async handler($,Z){let J=$.join(" ").trim();if(!J)return{success:!1,error:"Usage: /btw <question>"};if(!Z.sideConversation)return{success:!1,error:"Side conversations require an active Session runtime"};let Y=await Z.sideConversation.ask(J,Z.signal);return{success:!0,content:`**/btw** ${J}
|
|
1112
1112
|
|
|
1113
1113
|
${Y.response}`,data:{action:"show_side_conversation",question:J,response:Y.response,durationMs:Y.durationMs,usage:Y.usage}}}},hX=nD;import bz from"node:fs/promises";import jz from"node:path";function B9($){return Number.isFinite($)?Math.max(0,$):0}function gX($){let Z=B9($.totalInputTokens),J=B9($.cacheReadTokens),Y=B9($.cacheWriteTokens),Q=Math.min(J,Z),X=Math.min(Y,Math.max(0,Z-Q)),z=Math.max(0,Z-Q-X),W=Z>0&&(J>0||Y>0);return{totalInputTokens:Z,cacheReadTokens:Q,cacheWriteTokens:X,uncachedInputTokens:z,...W?{hitRate:Q/Z}:{}}}function uX($){if($===void 0||!Number.isFinite($))return"—";return`${Math.round(Math.max(0,Math.min(1,$))*100)}%`}function dX($){return`${{model_changed:"model changed",system_prompt_changed:"system prompt changed",tools_changed:"tool definitions changed",request_policy_changed:"request policy changed",ttl_expired:"cache TTL expired",server_side:"likely Provider routing or eviction"}[$.reason]} (${$.previousCacheReadTokens.toLocaleString()} → ${$.cacheReadTokens.toLocaleString()} cache-read tokens)`}async function B8($,Z,J={}){let Y=Date.now(),Q=J.timeoutMs??20000,X="unknown";try{let z=m0($,Z,"off");X=z.model.api;let V=await new mX({...z.chat,temperature:0,maxOutputTokens:8,timeout:Q,streamIdleTimeout:Q,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(Q),{providerAdmission:{sessionId:`provider-health:${$.id}`,ownerId:`provider-health:${$.id}`,requestClass:"internal"}});if(!Boolean(V.content||V.reasoningContent||V.finishReason||V.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:"ok",message:"Provider responded successfully."}}catch(z){let W=W8(z);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:X,latencyMs:Date.now()-Y,code:W.code,message:W.message}}}import sD from"node:os";import cX from"node:path";var G9=Object.freeze(["help","version","btw","effort","speed","verbosity","style"]),aD=new Set(G9);function K9($){return aD.has($)}function c($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
1114
1114
|
|
|
@@ -1675,7 +1675,7 @@ ${J}
|
|
|
1675
1675
|
`)),{success:!0,message:"Schedules listed",content:V.join(`
|
|
1676
1676
|
`)}}case"create":{let W=aw(X);if("error"in W)return Y.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let V={prompt:W.prompt,projectPath:z,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let U=await $.create(V),H=U.nextRunAt?new Date(U.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${U.id}\`
|
|
1677
1677
|
${A9(U.trigger)} · 下次运行: ${H}`),{success:!0,message:`Schedule ${U.id} created`}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`创建失败:${H}`),{success:!1,error:H}}}case"remove":case"rm":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(W);return Y.sendMessage(V?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let W=X[0];if(!W)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(W,Q==="enable");return Y.sendMessage(V?`[OK] 已${Q==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let W=X[0];if(!W)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await sw(W),Y.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(V){let U=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${U}`),{success:!1,error:U}}}default:return Y.sendMessage(`未知子命令: ${Q}
|
|
1678
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-
|
|
1678
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var sz=ow();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function ZW($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,z=X??P6(Q??C());if(!X){let G=await tw($,Q??C(),J,Y);if(G)return G}let W;try{W=(await f2.readdir(z)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(z,D))}catch{return[]}let U=(await Promise.all(W.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),H=[],B=Y?$:$.toLowerCase();for(let G of U){if(H.length>=J)break;let D=P2.basename(G,".jsonl"),w=await ew(G,B,Y,D);if(H.push(...w),H.length>=J){H.length=J;break}}return H}async function tw($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await ez();if(!X)return null;let{SessionService:z}=await import("./chunk-k26rzh57.js");await Q(X,z.projectionDeriverForSearch());let W=P2.resolve(Z),V=$W(X,$,W,J*4),U=Y?$:$.toLowerCase(),H=[];for(let B of V){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,U,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)H.push(G);if(H.length>=J)break}return H}catch{return null}}async function ew($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),z=Q.split(`
|
|
1679
1679
|
`).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!z.some(({event:B})=>B.type==="session_created"))return $F(z,Z,J,Y);let V=new Map(z.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),U=oz(tz(Q,$)),H=new Map;for(let B of U){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))H.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:V.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=H.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...H.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function $F($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let z=Q.message;if(z?.role!=="user"&&z?.role!=="assistant"||!z.content)return[];let W=typeof z.content==="string"?z.content:Array.isArray(z.content)?z.content.filter((U)=>typeof U==="object"&&U!==null&&U.type==="text"&&typeof U.text==="string").map((U)=>U.text).join(" "):"",V=M9(W,Z,J,Y,z.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return V?[V]:[]})}function M9($,Z,J,Y,Q,X,z){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let V=W.indexOf(Z),U=Math.max(0,V-80),H=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:Q,content:(U>0?"...":"")+$.slice(U,H).replace(/\n/g," ")+(H<$.length?"...":""),timestamp:X,lineNumber:z}}function JW($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1680
1680
|
`];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1681
1681
|
`)}var ZF={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await ZW(Y,{maxResults:15,projectPath:Z.cwd}),X=JW(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},YW=ZF;var JF={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},QW=JF;import YF from"node:path";function O8($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function XW($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function zW($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function QF($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),z=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:YF.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let q=await Z.subagents.resume(D,w),_=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(_),{success:!0,message:_,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(W??z,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let V=[`**后台任务列表**
|