blade-code 0.10.132 → 0.10.136
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-0qq64xqm.js +25 -0
- package/dist/{chunk-gmqpfm52.js → chunk-13sdjfks.js} +2 -2
- package/dist/{chunk-t8rjxqp2.js → chunk-1cbaqh71.js} +2 -2
- package/dist/chunk-1dscf8xj.js +23 -0
- package/dist/chunk-1n5d6b5k.js +1 -0
- package/dist/{chunk-zwjrensv.js → chunk-1p9sjb8d.js} +1 -1
- package/dist/{chunk-dvb89529.js → chunk-1pmvyqed.js} +1 -1
- package/dist/chunk-1qdemrkr.js +1 -0
- package/dist/{chunk-6p6ts4kv.js → chunk-24rsvr6e.js} +2 -2
- package/dist/{chunk-qcydkn1n.js → chunk-46jmq302.js} +1 -1
- package/dist/{chunk-sx77dpxw.js → chunk-5sknjz9b.js} +1 -1
- package/dist/{chunk-td2jk2xn.js → chunk-6rvrx275.js} +2 -2
- package/dist/{chunk-g4xny949.js → chunk-77x1rrz9.js} +1 -1
- package/dist/{chunk-e371f7xk.js → chunk-82x77b2p.js} +2 -2
- package/dist/chunk-83nxcfz3.js +1 -0
- package/dist/{chunk-fag8rk53.js → chunk-91pb41e7.js} +1 -1
- package/dist/{chunk-g1bqjdeq.js → chunk-9y7j565j.js} +2 -2
- package/dist/{chunk-bavzm721.js → chunk-9z9v8v4j.js} +1 -1
- package/dist/{chunk-ajsw4te2.js → chunk-acsfh1cw.js} +2 -2
- package/dist/chunk-as8stb2j.js +10 -0
- package/dist/chunk-azaqc1b6.js +1 -0
- package/dist/{chunk-tkydv9k8.js → chunk-bdtpq7j9.js} +1 -1
- package/dist/chunk-c5rfnzhf.js +171 -0
- package/dist/{chunk-pqsvz99n.js → chunk-c85xvthj.js} +1 -1
- package/dist/{chunk-zssz8hc4.js → chunk-cgkbdh2m.js} +1 -1
- package/dist/chunk-e1warjkn.js +171 -0
- package/dist/{chunk-aaxc81jc.js → chunk-f7hsagj6.js} +1 -1
- package/dist/{chunk-prt6y5fv.js → chunk-ffh4c30x.js} +1 -1
- package/dist/chunk-fnc97xg7.js +2 -0
- package/dist/chunk-g13jmewd.js +1 -0
- package/dist/{chunk-9gs4eqt8.js → chunk-g45camrd.js} +1 -1
- package/dist/{chunk-6q3g5e3m.js → chunk-g4vgnxh4.js} +1 -1
- package/dist/{chunk-ar5np5h5.js → chunk-g7h0peka.js} +2 -2
- package/dist/{chunk-jkfkyedn.js → chunk-gdnyt8a7.js} +1 -1
- package/dist/chunk-gq7fdc8c.js +2 -0
- package/dist/chunk-gwjah260.js +1 -0
- package/dist/{chunk-7dy3mzgz.js → chunk-hqwpnb0x.js} +2 -2
- package/dist/{chunk-sbc90z9j.js → chunk-hx10bph0.js} +2 -2
- package/dist/{chunk-2y1qngw7.js → chunk-jb8stg10.js} +1 -1
- package/dist/{chunk-44jtpg8y.js → chunk-jc28ddt0.js} +1 -1
- package/dist/{chunk-a60cmnmz.js → chunk-kbnxbb23.js} +2 -2
- package/dist/{chunk-0bkhpd72.js → chunk-mm1atkae.js} +2 -2
- package/dist/{chunk-b5z1rec4.js → chunk-mq1mk3v5.js} +27 -27
- package/dist/{chunk-rj8mmwc6.js → chunk-mxe4pr8t.js} +2 -2
- package/dist/chunk-n238rdz8.js +1 -0
- package/dist/{chunk-pj69j4zp.js → chunk-na3nregt.js} +1 -1
- package/dist/{chunk-sj1dzeta.js → chunk-nfzad4te.js} +1 -1
- package/dist/{chunk-zkzhm39s.js → chunk-ntd69c0k.js} +1 -1
- package/dist/{chunk-sfe4810k.js → chunk-nzwh9v6t.js} +1 -1
- package/dist/chunk-pnanbvn3.js +1 -0
- package/dist/chunk-pz91qga3.js +1 -0
- package/dist/{chunk-mdew58v9.js → chunk-q0s3gcjm.js} +1 -1
- package/dist/chunk-qjydadex.js +14 -0
- package/dist/{chunk-r7kevfd3.js → chunk-qm96k94k.js} +3 -3
- package/dist/{chunk-grhsv55v.js → chunk-r51afpkk.js} +1 -1
- package/dist/{chunk-dfjmvj3d.js → chunk-s3a017q7.js} +2 -2
- package/dist/{chunk-mg1s861p.js → chunk-s4b1r3my.js} +1 -1
- package/dist/{chunk-93x9xbew.js → chunk-sv5z5sna.js} +1 -1
- package/dist/{chunk-xjrmq0pg.js → chunk-sy0vxdc3.js} +379 -377
- package/dist/{chunk-749jzrbk.js → chunk-t6cajkaj.js} +2 -2
- package/dist/chunk-tah2002b.js +1 -0
- package/dist/{chunk-mvm1rzc4.js → chunk-tev70rzj.js} +2 -2
- package/dist/chunk-tzfd2fza.js +1 -0
- package/dist/{chunk-y0kqkewg.js → chunk-v2qxszks.js} +2 -2
- package/dist/chunk-v3veeja5.js +1 -0
- package/dist/chunk-vptn8fhx.js +2 -0
- package/dist/{chunk-edtxcqxa.js → chunk-vvawhvea.js} +1 -1
- package/dist/chunk-w2n1vwzg.js +2 -0
- package/dist/{chunk-p00f53yq.js → chunk-wj16pvvn.js} +1 -1
- package/dist/chunk-wj813rcc.js +1 -0
- package/dist/{chunk-77efqpdc.js → chunk-wzkh3e6a.js} +1 -1
- package/dist/{chunk-8y08fytr.js → chunk-xtngc0th.js} +1 -1
- package/dist/{chunk-z03dtyh6.js → chunk-yacv7f7h.js} +1 -1
- package/dist/{chunk-53h87fmt.js → chunk-z3hpstky.js} +1 -1
- package/dist/{chunk-qcvxff27.js → chunk-zy2etr3v.js} +2 -2
- package/dist/web/assets/ChatView-Bc9twpWM.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-DR5RLA1_.js → CodeBlockHighlighter-41xRPXs2.js} +1 -1
- package/dist/web/assets/{FilePreview-C4tqzUOM.js → FilePreview-lcc_hL7J.js} +15 -20
- package/dist/web/assets/{KanbanBoard-D7HJQXE2.js → KanbanBoard-BHgM338V.js} +4 -4
- package/dist/web/assets/{MarkdownRenderer-Ct8vtONO.js → MarkdownRenderer-BMAuTkc6.js} +3 -3
- package/dist/web/assets/{ScrollArea-CMSE6nO4.js → ScrollArea-DJq2Kdpi.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-BPwnF9ND.js → SessionHistorySurface-DSe8ePBJ.js} +2 -2
- package/dist/web/assets/{SettingsModal-KW5WYAov.js → SettingsModal-Cih4bWul.js} +1 -1
- package/dist/web/assets/{Sidebar-8BUNEHHQ.js → Sidebar-DnWlUKmO.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-CZfkp2L_.js → TaskSwitcher-D3mrXv_i.js} +2 -2
- package/dist/web/assets/{TerminalPanel-DBBMaU_6.js → TerminalPanel-BNKHhBVM.js} +2 -2
- package/dist/web/assets/{archive-tBd5snSF.js → archive-Dof4YpyT.js} +1 -1
- package/dist/web/assets/{arrow-left-Cs_sFMp-.js → arrow-left-DGFXaGox.js} +1 -1
- package/dist/web/assets/{calendar-clock-C0ue6XTy.js → calendar-clock-BoxUNOvH.js} +1 -1
- package/dist/web/assets/{chevron-right-DZHCUfAH.js → chevron-right-Brb1rhaA.js} +1 -1
- package/dist/web/assets/chevrons-up-down-N-VshXV_.js +16 -0
- package/dist/web/assets/{clock-3-DstAM2AR.js → clock-3-gdZEKe2U.js} +1 -1
- package/dist/web/assets/{copy-BfnFXTgG.js → copy-d9M8JUfQ.js} +1 -1
- package/dist/web/assets/{download-XKyNtMnj.js → download-CQ-Pwfq0.js} +1 -1
- package/dist/web/assets/{external-link-3bcWFMya.js → external-link-GRAtjoO2.js} +1 -1
- package/dist/web/assets/{folder-D7hQLvy7.js → folder-CqLD0IBh.js} +1 -1
- package/dist/web/assets/index-CPpIFWLG.css +1 -0
- package/dist/web/assets/index-DiRs2_w4.js +203 -0
- package/dist/web/assets/{pause-CBR55GXy.js → pause-BqsFgQi0.js} +1 -1
- package/dist/web/assets/{pencil-8yqeFHC4.js → pencil-Ca9289F-.js} +1 -1
- package/dist/web/assets/{play-F_Spkp4p.js → play-DmEPnYDS.js} +1 -1
- package/dist/web/assets/{plus-CJCqq3rG.js → plus-kIBLgk0p.js} +1 -1
- package/dist/web/assets/session-events-BqQQkbAN.js +29 -0
- package/dist/web/assets/{settings-G6riyt4S.js → settings-BuSrJl6s.js} +1 -1
- package/dist/web/assets/teamService-B7Fp8Oyg.js +1 -0
- package/dist/web/assets/{terminal-_Nebc2yj.js → terminal-Qkr_gcNu.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
- package/dist/chunk-0gmbvtpp.js +0 -1
- package/dist/chunk-0z9nqbd0.js +0 -2
- package/dist/chunk-14z94k0r.js +0 -1
- package/dist/chunk-3e0t25rq.js +0 -171
- package/dist/chunk-53j6nh8j.js +0 -1
- package/dist/chunk-64kg5a9r.js +0 -1
- package/dist/chunk-9d49tj9y.js +0 -2
- package/dist/chunk-9s8saznq.js +0 -1
- package/dist/chunk-dhzbac1c.js +0 -1
- package/dist/chunk-f8gb685p.js +0 -2
- package/dist/chunk-g12kqs1b.js +0 -1
- package/dist/chunk-j3nmt09e.js +0 -25
- package/dist/chunk-kd3k1q9z.js +0 -1
- package/dist/chunk-m9mw8ppy.js +0 -1
- package/dist/chunk-pkg1bvzc.js +0 -1
- package/dist/chunk-q7m0tvhw.js +0 -1
- package/dist/chunk-sf9sbm6y.js +0 -1
- package/dist/chunk-sm9p1fkf.js +0 -14
- package/dist/chunk-v52wc8yg.js +0 -2
- package/dist/chunk-xyxjcehh.js +0 -23
- package/dist/chunk-z28dcrr9.js +0 -10
- package/dist/chunk-z83xk6jn.js +0 -1
- package/dist/chunk-znqt5g8v.js +0 -170
- package/dist/web/assets/ChatView-CkmlibKO.js +0 -53
- package/dist/web/assets/chevrons-up-down-BSa16Scz.js +0 -11
- package/dist/web/assets/index-B4186fIT.css +0 -1
- package/dist/web/assets/index-CCdnLriX.js +0 -210
- package/dist/web/assets/session-events-C6fPz20c.js +0 -22
- package/dist/web/assets/teamService-Cixkq48S.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{qf as W}from"./chunk-v2qxszks.js";import{tf as F,uf as M}from"./chunk-kbnxbb23.js";import"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import"./chunk-q0s3gcjm.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import"./chunk-mm1atkae.js";import"./chunk-gdnyt8a7.js";import"./chunk-vptn8fhx.js";import{Pi as N,Qi as B}from"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import{vj as T}from"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import"./chunk-na3nregt.js";import{zk as J}from"./chunk-ntd69c0k.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-1qdemrkr.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-pnanbvn3.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-83nxcfz3.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-9y7j565j.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-cgkbdh2m.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-1dscf8xj.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-tzfd2fza.js"),import("./chunk-pz91qga3.js"),import("./chunk-wj16pvvn.js"),import("./chunk-6rvrx275.js"),import("./chunk-yacv7f7h.js"),import("./chunk-c85xvthj.js"),import("./chunk-nzwh9v6t.js"),import("./chunk-g45camrd.js"),import("./chunk-n238rdz8.js"),import("./chunk-ffh4c30x.js"),import("./chunk-as8stb2j.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-v3veeja5.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-e1warjkn.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import{Wf as J0}from"./chunk-q0s3gcjm.js";import{Bi as r,Ei as U0,ci as x,sh as H0}from"./chunk-mm1atkae.js";import{Qi as G0}from"./chunk-jc28ddt0.js";import{Cj as A}from"./chunk-s3a017q7.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)=>{Y((Q)=>({app:{...Q.app,taskAttentionStatus:Z,taskAttentionUnreadKeys:[...X]}}))},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,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,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
|
+
[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
|
+
`));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
|
+
`)})}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(`
|
|
5
|
+
`);Z.push({type:"code",content:j0,language:G||void 0}),Q=!1,$=[],G=null,J=0,U=!1}else $.push(O);continue}let S=O.match(W.codeBlock);if(S){Q=!0,G=S[1]||null,J=0,U=!1;continue}let w=O.match(W.table),z0=O.match(W.tableSeparator);if(w&&!V){if(q+1<X.length){if(X[q+1].match(W.tableSeparator)){V=!0,F=w[1].split("|").map((P)=>P.trim()).filter((P)=>P.length>0),z=[],U=!1;continue}}}if(V&&z0)continue;if(V&&w){let E=w[1].split("|").map((P)=>P.trim()).filter((P)=>P.length>0);while(E.length<F.length)E.push("");if(E.length>F.length)E.length=F.length;z.push(E);continue}if(V&&!w){if(F.length>0&&z.length>0)Z.push({type:"table",content:"",tableData:{headers:F,rows:z}});V=!1,F=[],z=[]}let h=O.match(W.blockquote);if(h){let E=h[1].length,P=h[2]||"";if(L&&E===H)j.push(P);else{if(L)Z.push({type:"blockquote",content:j.join(`
|
|
6
|
+
`),blockquoteLevel:H,blockquoteLines:[...j]});L=!0,H=E,j=[P]}U=!1;continue}if(L)Z.push({type:"blockquote",content:j.join(`
|
|
7
|
+
`),blockquoteLevel:H,blockquoteLines:[...j]}),L=!1,j=[],H=0;let I=O.match(W.heading);if(I){Z.push({type:"heading",content:I[2],level:I[1].length}),U=!1;continue}let C=O.match(W.ulItem);if(C){Z.push({type:"list",content:C[3],listType:"ul",marker:C[2],indentation:C[1].length}),U=!1;continue}let b=O.match(W.olItem);if(b){Z.push({type:"list",content:b[3],listType:"ol",marker:b[2],indentation:b[1].length}),U=!1;continue}if(O.match(W.hr)){Z.push({type:"hr",content:""}),U=!1;continue}if(O.trim().length===0){if(!U)Z.push({type:"empty",content:""}),U=!0;continue}let l=O.match(W.commandMessage);if(l){Z.push({type:"command-message",content:l[1]}),U=!1;continue}Z.push({type:"text",content:O}),U=!1}if(Q){let q=$.join(`
|
|
8
|
+
`);Z.push({type:"code",content:q,language:G||void 0})}if(V&&F.length>0&&z.length>0)Z.push({type:"table",content:"",tableData:{headers:F,rows:z}});if(L&&j.length>0)Z.push({type:"blockquote",content:j.join(`
|
|
9
|
+
`),blockquoteLevel:H,blockquoteLines:[...j]});while(Z.length>0&&Z[Z.length-1].type==="empty")Z.pop();return Z}var N=new Map;function C0(){return{inCodeBlock:!1,codeBlockContent:[],codeBlockLang:null,codeBlockDepth:0,inTable:!1,tableHeaders:[],tableRows:[],inDiff:!1,diffContent:[],inBlockquote:!1,blockquoteLines:[],blockquoteLevel:0,lastLineEmpty:!0,pendingTableHeader:null}}function b0(Y){let Z=N.get(Y);if(Z)return Z;let X={state:C0(),blocks:[],pendingLine:"",finalized:!1};return N.set(Y,X),X}function Q0(Y){return Y.endsWith("\r")?Y.slice(0,-1):Y}function X0(Y,Z){if(Y.tableHeaders.length>0&&Y.tableRows.length>0)Z.push({type:"table",content:"",tableData:{headers:Y.tableHeaders,rows:Y.tableRows}});Y.inTable=!1,Y.tableHeaders=[],Y.tableRows=[]}function g(Y,Z){if(Y.blockquoteLines.length>0)Z.push({type:"blockquote",content:Y.blockquoteLines.join(`
|
|
10
|
+
`),blockquoteLevel:Y.blockquoteLevel,blockquoteLines:[...Y.blockquoteLines]});Y.inBlockquote=!1,Y.blockquoteLines=[],Y.blockquoteLevel=0}function Y0(Y,Z){let X=Y.codeBlockContent.join(`
|
|
11
|
+
`);Z.push({type:"code",content:X,language:Y.codeBlockLang||void 0}),Y.inCodeBlock=!1,Y.codeBlockContent=[],Y.codeBlockLang=null,Y.codeBlockDepth=0,Y.lastLineEmpty=!1}function c(Y,Z,X=!0){let{state:Q,blocks:$}=Z;if(Q.pendingTableHeader!==null){if(Y.match(W.tableSeparator)){Q.inTable=!0,Q.tableHeaders=Q.pendingTableHeader.slice(1,-1).split("|").map((H)=>H.trim()).filter((H)=>H.length>0),Q.tableRows=[],Q.pendingTableHeader=null,Q.lastLineEmpty=!1;return}$.push({type:"text",content:Q.pendingTableHeader}),Q.pendingTableHeader=null,Q.lastLineEmpty=!1}if(Q.inDiff){if(Y.match(W.diffEnd)){try{let H=JSON.parse(Q.diffContent.join(`
|
|
12
|
+
`));$.push({type:"diff",content:"",diffData:{patch:H.patch,startLine:H.startLine,matchLine:H.matchLine}})}catch(H){$.push({type:"text",content:Q.diffContent.join(`
|
|
13
|
+
`)})}Q.inDiff=!1,Q.diffContent=[],Q.lastLineEmpty=!1;return}Q.diffContent.push(Y);return}if(Y.match(W.diffStart)){Q.inDiff=!0,Q.diffContent=[],Q.lastLineEmpty=!1;return}if(Q.inCodeBlock){let H=Y.match(W.codeBlock),U=Y.trim()==="```";if(H&&H[1])Q.codeBlockDepth++,Q.codeBlockContent.push(Y);else if(U)if(Q.codeBlockDepth>0)Q.codeBlockDepth--,Q.codeBlockContent.push(Y);else Y0(Q,$);else Q.codeBlockContent.push(Y);return}let G=Y.match(W.codeBlock);if(G){Q.inCodeBlock=!0,Q.codeBlockLang=G[1]||null,Q.codeBlockDepth=0,Q.lastLineEmpty=!1;return}let J=Y.match(W.table),V=Y.match(W.tableSeparator);if(J&&!Q.inTable){Q.pendingTableHeader=Y;return}if(Q.inTable&&V)return;if(Q.inTable&&J){let H=J[1].split("|").map((U)=>U.trim()).filter((U)=>U.length>0);while(H.length<Q.tableHeaders.length)H.push("");if(H.length>Q.tableHeaders.length)H.length=Q.tableHeaders.length;Q.tableRows.push(H);return}if(Q.inTable&&!J){if(X0(Q,$),X){c(Y,Z,!1);return}}let F=Y.match(W.blockquote);if(F){let H=F[1].length,U=F[2]||"";if(Q.inBlockquote&&H===Q.blockquoteLevel)Q.blockquoteLines.push(U);else{if(Q.inBlockquote)g(Q,$);Q.inBlockquote=!0,Q.blockquoteLevel=H,Q.blockquoteLines=[U]}Q.lastLineEmpty=!1;return}if(Q.inBlockquote)g(Q,$);let z=Y.match(W.heading);if(z){$.push({type:"heading",content:z[2],level:z[1].length}),Q.lastLineEmpty=!1;return}let K=Y.match(W.ulItem);if(K){$.push({type:"list",content:K[3],listType:"ul",marker:K[2],indentation:K[1].length}),Q.lastLineEmpty=!1;return}let B=Y.match(W.olItem);if(B){$.push({type:"list",content:B[3],listType:"ol",marker:B[2],indentation:B[1].length}),Q.lastLineEmpty=!1;return}if(Y.match(W.hr)){$.push({type:"hr",content:""}),Q.lastLineEmpty=!1;return}if(Y.trim().length===0){if(!Q.lastLineEmpty)$.push({type:"empty",content:""}),Q.lastLineEmpty=!0;return}let j=Y.match(W.commandMessage);if(j){$.push({type:"command-message",content:j[1]}),Q.lastLineEmpty=!1;return}$.push({type:"text",content:Y}),Q.lastLineEmpty=!1}function X1(Y,Z){if(!Y||!Z)return;let X=b0(Y);if(X.finalized)return;let Q=X.pendingLine+Z,$=Q.split(`
|
|
14
|
+
`),G=Q.endsWith(`
|
|
15
|
+
`),J=G?$:$.slice(0,-1);X.pendingLine=G?"":$[$.length-1]??"";for(let V of J)c(Q0(V),X)}function Y1(Y){let Z=N.get(Y);if(!Z||Z.finalized)return;if(Z.pendingLine)c(Q0(Z.pendingLine),Z),Z.pendingLine="";if(Z.state.pendingTableHeader!==null)Z.blocks.push({type:"text",content:Z.state.pendingTableHeader}),Z.state.pendingTableHeader=null;if(Z.state.inCodeBlock)Y0(Z.state,Z.blocks);if(Z.state.inTable)X0(Z.state,Z.blocks);if(Z.state.inBlockquote)g(Z.state,Z.blocks);if(Z.state.inDiff)Z.blocks.push({type:"text",content:Z.state.diffContent.join(`
|
|
16
|
+
`)}),Z.state.inDiff=!1,Z.state.diffContent=[];while(Z.blocks.length>0&&Z.blocks[Z.blocks.length-1].type==="empty")Z.blocks.pop();Z.finalized=!0}function Z1(Y){let Z=N.get(Y);if(!Z||!Z.finalized)return null;return Z.blocks}function $1(Y){let Z=N.get(Y);if(!Z)return null;return Z.blocks}function M0(Y){let Z=N.get(Y);if(!Z)return null;let X=[],Q=Z.state;if(Q.inDiff)X.push("<<<DIFF>>>"),X.push(...Q.diffContent);else if(Q.inCodeBlock){let $=Q.codeBlockLang?`\`\`\`${Q.codeBlockLang}`:"```";X.push($),X.push(...Q.codeBlockContent)}else if(Q.inTable){if(Q.tableHeaders.length>0){X.push(`| ${Q.tableHeaders.join(" | ")} |`),X.push(`| ${Q.tableHeaders.map(()=>"---").join(" | ")} |`);for(let $ of Q.tableRows)X.push(`| ${$.join(" | ")} |`)}}else if(Q.inBlockquote){let $=">".repeat(Q.blockquoteLevel)+" ";for(let G of Q.blockquoteLines)X.push($+G)}else if(Q.pendingTableHeader)X.push(Q.pendingTableHeader);if(Z.pendingLine)X.push(Z.pendingLine);return X.length>0?X:null}function G1(Y){let Z=N.get(Y);if(!Z)return null;let X="text";if(Z.state.inDiff)X="diff";else if(Z.state.inCodeBlock)X="code";else if(Z.state.inTable||Z.state.pendingTableHeader)X="table";let Q=M0(Y);if(!Q||Q.length===0)return null;return{lines:Q,mode:X}}function J1(Y){N.delete(Y)}function M(){N.clear()}var Z0=2000,y=[];function h0(){let Y=y;return y=[],Y}var T={messages:[],streamingText:new Map};function I0(){T={messages:[],streamingText:new Map}}var V0={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:0,totalInputTokens:0,totalOutputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,turnCount:0,estimatedCostUsd:0},$0={sessionId:J0("tui"),workspaceRoot:G0(),messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...V0},currentThinkingContent:null,thinkingExpanded:!1,clearCount:0,historyExpanded:!1,expandedMessageCount:100,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null,providerAdmission:null,providerCircuit:null,providerRetry:null,providerStall:null,actionStationarity:null},d=(Y,Z)=>({...$0,actions:{addMessage:(X)=>{Y((Q)=>({session:{...Q.session,messages:[...Q.session.messages,X],error:null}}))},addUserMessage:(X)=>{let Q={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:X,timestamp:Date.now()};Z().session.actions.addMessage(Q)},addAssistantMessage:(X,Q)=>{let $={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:Q};Z().session.actions.addMessage($)},replaceLastAssistantMessage:(X)=>{Y((Q)=>{let $=Q.session.messages.findLastIndex((G)=>G.role==="assistant");if($<0)return{session:{...Q.session,messages:[...Q.session.messages,{id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now()}]}};return{session:{...Q.session,messages:Q.session.messages.map((G,J)=>J===$?{...G,content:X}:G)}}})},addAssistantMessageAndClearThinking:(X)=>{let Q=Z().session.currentThinkingContent,$={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:X,timestamp:Date.now(),thinkingContent:Q||void 0};Y((G)=>({session:{...G.session,messages:[...G.session.messages,$],currentThinkingContent:null,error:null}}))},addToolMessage:(X,Q)=>{let $={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:X,timestamp:Date.now(),metadata:Q};Z().session.actions.addMessage($)},setCompacting:(X)=>{Y((Q)=>({session:{...Q.session,isCompacting:X}}))},setCommand:(X)=>{Y((Q)=>({session:{...Q.session,currentCommand:X}}))},setError:(X)=>{Y((Q)=>({session:{...Q.session,error:X}}))},clearMessages:()=>{M(),Y((X)=>({session:{...X.session,messages:[],restoredContextMessages:null,restoredVisibleMessageCount:0,error:null,clearCount:X.session.clearCount+1}}))},setCompactedContext:(X)=>{Y((Q)=>({session:{...Q.session,restoredContextMessages:[...X],restoredVisibleMessageCount:Q.session.messages.length}}))},resetSession:()=>{M(),Y((X)=>({session:{...X.session,...$0,sessionId:X.session.sessionId,isActive:!0},app:{...X.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...X.command,followUpPresentations:{}}}))},restoreSession:(X,Q,$,G)=>{M(),Y((J)=>({session:{...J.session,sessionId:X,workspaceRoot:G??J.session.workspaceRoot,messages:Q,restoredContextMessages:$??null,restoredVisibleMessageCount:$?Q.length:0,error:null,isActive:!0},app:{...J.app,followUpQueue:null,followUpQueueOwner:null,followUpQueueMutation:{pending:!1,supersededVersions:[]}},command:{...J.command,followUpPresentations:{}}}))},updateTokenUsage:(X)=>{Y((Q)=>{let $=Q.session.tokenUsage,{costUsd:G,...J}=X,V=Math.max(0,X.inputTokens??0),F=Math.max(0,X.outputTokens??0),z=Math.max(0,X.cacheReadTokens??0),K=Math.max(0,X.cacheWriteTokens??0),B=$.totalInputTokens+V,L=$.totalOutputTokens+F,j=$.cacheReadTokens+z,H=$.cacheWriteTokens+K,U=Q.config?.config,q=U?.models?.find((w)=>w.id===U.currentModelId),O=q?.model??"",S=G??e(O,Math.max(0,V-z-K),F,z,K,q?.provider);return{session:{...Q.session,tokenUsage:{...$,...J,totalInputTokens:B,totalOutputTokens:L,cacheReadTokens:j,cacheWriteTokens:H,estimatedCostUsd:$.estimatedCostUsd+Math.max(0,S)}}}})},resetContextUsage:()=>{Y((X)=>({session:{...X.session,tokenUsage:{...X.session.tokenUsage,inputTokens:0,outputTokens:0,totalTokens:0}}}))},resetTokenUsage:()=>{Y((X)=>({session:{...X.session,tokenUsage:{...V0}}}))},setCurrentThinkingContent:(X)=>{if(Z().session.currentThinkingContent===X)return;Y((Q)=>({session:{...Q.session,currentThinkingContent:X}}))},appendThinkingContent:(X)=>{Y((Q)=>({session:{...Q.session,currentThinkingContent:(Q.session.currentThinkingContent||"")+X}}))},setThinkingExpanded:(X)=>{Y((Q)=>({session:{...Q.session,thinkingExpanded:X}}))},toggleThinkingExpanded:()=>{Y((X)=>({session:{...X.session,thinkingExpanded:!X.session.thinkingExpanded}}))},setHistoryExpanded:(X)=>{Y((Q)=>({session:{...Q.session,historyExpanded:X}}))},toggleHistoryExpanded:()=>{Y((X)=>({session:{...X.session,historyExpanded:!X.session.historyExpanded}}))},setExpandedMessageCount:(X)=>{Y((Q)=>({session:{...Q.session,expandedMessageCount:X}}))},incrementClearCount:()=>{Y((X)=>({session:{...X.session,clearCount:X.session.clearCount+1}}))},startStreamingAssistantMessage:()=>{let X=`assistant-${Date.now()}-${Math.random()}`,Q={id:X,role:"assistant",content:"",timestamp:Date.now()};return y=[],Y(($)=>({session:{...$.session,messages:[...$.session.messages,Q],currentStreamingMessageId:X,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,error:null}})),X},appendAssistantContent:(X)=>{let Q=Z().session.currentStreamingMessageId,$=Q??`assistant-${Date.now()}-${Math.random()}`;return y.push(X),Y((G)=>{let J=(q)=>q.endsWith("\r")?q.slice(0,-1):q,V=Q?G.session.currentStreamingLines:[],F=Q?G.session.currentStreamingTail:"",z=Q?G.session.currentStreamingLineCount:0,K=Q?G.session.currentStreamingVersion:0,L=(F+X).split(`
|
|
17
|
+
`),j=L.slice(0,-1).map(J),H=J(L[L.length-1]??""),U=V;if(j.length>0){if(U=[...V,...j],U.length>Z0){let q=U.length-Z0;U=U.slice(q)}}return{session:{...G.session,currentStreamingMessageId:$,currentStreamingLines:U,currentStreamingTail:H,currentStreamingLineCount:z+j.length,currentStreamingVersion:K+1,error:null}}}),$},finalizeStreamingMessage:(X,Q)=>{let $=h0();Y((G)=>{let J=G.session.currentStreamingMessageId,F=$.join("")+(X||""),z=(G.session.currentThinkingContent||"")+(Q||"");if(F.length>0){let K={id:J||`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:F,timestamp:Date.now(),thinkingContent:z||void 0};return{session:{...G.session,messages:[...G.session.messages,K],currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:K.id}}}return{session:{...G.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,currentThinkingContent:null,finalizingStreamingMessageId:null}}})},clearFinalizingStreamingMessageId:()=>{Y((X)=>({session:{...X.session,finalizingStreamingMessageId:null}}))},discardStreamingMessage:()=>{y=[],Y((X)=>({session:{...X.session,currentStreamingMessageId:null,currentStreamingChunks:[],currentStreamingLines:[],currentStreamingTail:"",currentStreamingLineCount:0,currentStreamingVersion:0,finalizingStreamingMessageId:null}}))},setProviderAdmission:(X)=>{Y((Q)=>({session:{...Q.session,providerAdmission:X}}))},setProviderCircuit:(X)=>{Y((Q)=>({session:{...Q.session,providerCircuit:X}}))},setProviderRetry:(X)=>{Y((Q)=>({session:{...Q.session,providerRetry:X}}))},setProviderStall:(X)=>{Y((Q)=>({session:{...Q.session,providerStall:X}}))},setActionStationarity:(X)=>{Y((Q)=>({session:{...Q.session,actionStationarity:X}}))},applyCommittedEvent:(X)=>{s(T,X),Y((Q)=>({session:{...Q.session,messages:[...T.messages],error:null}}))},applyStreamingDelta:(X)=>{t(T,X),Y((Q)=>({session:{...Q.session,messages:[...T.messages]}}))},resetConversationProjection:()=>{I0()}}});var u0=f0()(v0(k0((...Y)=>({session:d(...Y),app:k(...Y),config:u(...Y),focus:p(...Y),command:f(...Y)})),{name:"BladeStore",enabled:!0})),_=()=>u0.getState(),T1=()=>_().session.actions,y1=()=>_().app.actions,S1=()=>_().session.messages,D=()=>_().config.config,R=null;async function C1(){if(D()!==null)return;if(R)return R;return R=(async()=>{try{let X=await U0.getInstance().initialize();_().config.actions.setConfig(X)}catch(Z){throw R=null,Error(`[FAIL] Store 未初始化且无法自动初始化
|
|
18
|
+
|
|
19
|
+
`+`原因: ${Z instanceof Error?Z.message:"未知错误"}
|
|
20
|
+
|
|
21
|
+
`+`请确保:
|
|
22
|
+
`+`1. 配置文件格式正确 (~/.blade/config.json)
|
|
23
|
+
`+`2. 运行 blade 进行首次配置
|
|
24
|
+
`+"3. 配置文件权限正确")}finally{R=null}})(),R}var b1=()=>_().config.config?.models??[],M1=()=>{let Y=D();if(!Y)return;let Z=Y.currentModelId;return Y.models.find((Q)=>Q.id===Z)??Y.models[0]},h1=(Y)=>{let Z=D();if(!Z)return;return Z.models.find((X)=>X.id===Y)},I1=()=>_().config.config?.mcpServers??{},v1=()=>_().app.reasoningEffort!=="off",k1=()=>_().app.reasoningEffort,f1=()=>_().app.serviceTier,u1=()=>_().app.responseVerbosity,p1=()=>_().app.communicationStyle,F0=()=>({setPermissionMode:async(Y)=>{_().config.actions.updateConfig({permissionMode:Y})},setTheme:async(Y,Z={})=>{try{a.setTheme(Y)}catch{return}_().config.actions.updateConfig({codeTheme:Y}),await x().save({codeTheme:Y},{scope:"global",...Z})},setLanguage:async(Y,Z={})=>{_().config.actions.updateConfig({language:Y}),await x().save({language:Y},{scope:"global",...Z})},setDebug:async(Y,Z={})=>{_().config.actions.updateConfig({debug:Y}),await x().save({debug:Y},{scope:"global",...Z})},setTemperature:async(Y,Z={})=>{_().config.actions.updateConfig({temperature:Y}),await x().save({temperature:Y},{scope:"global",...Z})},updateConfig:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");let Q={...X};_().config.actions.updateConfig(Y);try{await x().save(Y,Z)}catch($){throw _().config.actions.setConfig(Q),$}},flush:async()=>{await x().flush()},appendPermissionAllowRule:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");let Q=X.permissions?.allow||[];if(!Q.includes(Y)){let $=[...Q,Y];_().config.actions.updateConfig({permissions:{...X.permissions,allow:$}})}await x().appendPermissionRule(Y,Z)},appendLocalPermissionAllowRule:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");let Q=X.permissions?.allow||[];if(!Q.includes(Y)){let $=[...Q,Y];_().config.actions.updateConfig({permissions:{...X.permissions,allow:$}})}await x().appendLocalPermissionRule(Y,Z)},setCurrentModel:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");if(!X.models.find(($)=>$.id===Y))throw Error(`Model not found: ${Y}`);_().config.actions.updateConfig({currentModelId:Y}),await x().save({currentModelId:Y},{scope:"global",...Z})},addModel:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");let Q="id"in Y?Y:{id:r(Y,X.models),...Y};if(X.models.find((V)=>V.provider===Q.provider&&V.model===Q.model))throw Error(`Model already configured: ${Q.provider}/${Q.model}`);let J={models:[...X.models,Q]};if(X.models.length===0)J.currentModelId=Q.id;return _().config.actions.updateConfig(J),await x().save(J,{scope:"global",...Z}),Q},addModelWithProvider:async(Y,Z,X={})=>{let Q=D();if(!Q)throw Error("Config not initialized");let $=Y.provider;if(Q.modelProviders[$])throw Error(`Model provider already configured: ${$}`);let G="id"in Y?Y:{id:r(Y,Q.models),...Y};if(Q.models.find((K)=>K.provider===$&&K.model===G.model))throw Error(`Model already configured: ${$}/${G.model}`);let V=Q,F=[...Q.models,G],z={modelProviders:{...Q.modelProviders,[$]:Z},models:F};if(Q.models.length===0)z.currentModelId=G.id;A().registerModelProvider($,Z,[G.model]),_().config.actions.updateConfig(z);try{return await x().save(z,{scope:"global",...X}),G}catch(K){throw _().config.actions.setConfig(V),A().configureModelProviders(V.modelProviders,V.models),K}},updateModelWithProvider:async(Y,Z,X,Q={})=>{let $=D();if(!$)throw Error("Config not initialized");let G=Z.provider;if(!G)throw Error("Model provider is required");if($.modelProviders[G])throw Error(`Model provider already configured: ${G}`);let J=$.models.findIndex((B)=>B.id===Y);if(J===-1)throw Error(`Model not found: ${Y}`);let V={...$.models[J],...Z};if(!V.model)throw Error("Model ID is required");let F=$,z=[...$.models];z[J]=V;let K={modelProviders:{...$.modelProviders,[G]:X},models:z};A().registerModelProvider(G,X,[V.model]),_().config.actions.updateConfig(K);try{await x().save(K,{scope:"global",...Q})}catch(B){throw _().config.actions.setConfig(F),A().configureModelProviders(F.modelProviders,F.models),B}},updateModelProvider:async(Y,Z,X={})=>{let Q=D();if(!Q)throw Error("Config not initialized");if(!Q.modelProviders[Y])throw Error(`Model provider not found: ${Y}`);let $=Q.models.filter((G)=>G.provider===Y).map((G)=>G.model);A().registerModelProvider(Y,Z,$),await F0().updateConfig({modelProviders:{...Q.modelProviders,[Y]:Z}},{scope:"global",immediate:!0,...X})},removeModelProvider:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");if(!X.modelProviders[Y])throw Error(`Model provider not found: ${Y}`);let Q=X.models.filter((j)=>j.provider===Y),$=X.models.filter((j)=>j.fallbackModels?.some((H)=>H.provider===Y));if(!Z.removeModels&&(Q.length>0||$.length>0))throw Error(`Model provider is still referenced by ${Q.length} model(s) and ${$.length} fallback configuration(s)`);let G=Q.map((j)=>j.id),J=X.models.filter((j)=>j.provider!==Y).map((j)=>{let H=j.fallbackModels?.filter((O)=>O.provider!==Y),{fallbackModels:U,...q}=j;return H?.length?{...q,fallbackModels:H}:q});if(J.length===0)throw Error("Cannot remove the provider that owns the only model");let V={...X.modelProviders};delete V[Y];let F={modelProviders:V,models:J};if(G.includes(X.currentModelId))F.currentModelId=J[0].id;let z=A(),K=await z.credentials.read(Y);await z.credentials.delete(Y);let{removeModels:B,...L}=Z;try{return await F0().updateConfig(F,{scope:"global",immediate:!0,...L}),{removedModelIds:G}}catch(j){if(K)await z.credentials.modify(Y,async()=>K);throw j}},updateModel:async(Y,Z,X={})=>{let Q=D();if(!Q)throw Error("Config not initialized");let $=Q.models.findIndex((J)=>J.id===Y);if($===-1)throw Error(`Model not found: ${Y}`);let G=[...Q.models];G[$]={...G[$],...Z},_().config.actions.updateConfig({models:G}),await x().save({models:G},{scope:"global",...X})},removeModel:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");if(X.models.length===1)throw Error("Cannot remove the only model");let Q=X.models.filter((G)=>G.id!==Y),$={models:Q};if(X.currentModelId===Y)$.currentModelId=Q[0].id;_().config.actions.updateConfig($),await x().save($,{scope:"global",...Z})},addMcpServer:async(Y,Z,X={})=>{let Q=D();if(!Q)throw Error("Config not initialized");let $=Q.mcpServers??{},G=H0(Z),J={...Z,...G?{oauth:G}:{}},V={...$,[Y]:J};_().config.actions.updateConfig({mcpServers:V}),await x().save({mcpServers:V},{scope:"project",...X})},removeMcpServer:async(Y,Z={})=>{let X=D();if(!X)throw Error("Config not initialized");let $={...X.mcpServers??{}};delete $[Y],_().config.actions.updateConfig({mcpServers:$}),await x().save({mcpServers:$},{scope:"project",...Z})}});
|
|
25
|
+
export{i as vf,a as wf,W as xf,t0 as yf,X1 as zf,Y1 as Af,Z1 as Bf,$1 as Cf,G1 as Df,J1 as Ef,u0 as Ff,_ as Gf,T1 as Hf,y1 as If,S1 as Jf,D as Kf,C1 as Lf,b1 as Mf,M1 as Nf,h1 as Of,I1 as Pf,v1 as Qf,k1 as Rf,f1 as Sf,u1 as Tf,p1 as Uf,F0 as Vf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{Z as
|
|
1
|
+
import{jh as Q}from"./chunk-sv5z5sna.js";import{Ri as F,Ti as k,Wi as G}from"./chunk-nfzad4te.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
|
|
2
|
+
export{Z as nf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Tg as A1,Ug as L0,Vg as M1,_g as v0}from"./chunk-5sknjz9b.js";import{fh as SO,gh as F1}from"./chunk-f7hsagj6.js";import{jh as x1}from"./chunk-sv5z5sna.js";import{kh as A0,mh as J0}from"./chunk-qm96k94k.js";import{Ai as WO,Ei as b0,zi as z0}from"./chunk-mm1atkae.js";import{Qi as M}from"./chunk-jc28ddt0.js";import{Ri as u,Ti as L,Wi as l1}from"./chunk-nfzad4te.js";import{wj as P,xj as S}from"./chunk-g7h0peka.js";import{Kj as c0}from"./chunk-w2n1vwzg.js";import{Rj as N}from"./chunk-zy2etr3v.js";import{mk as qO}from"./chunk-na3nregt.js";import N0 from"node:path";import YO from"node:path";import y0 from"node:fs";import W0 from"node:os";import E from"node:path";import pO from"yaml";var V1=2000,j1=50,B1=1000,X4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:V1},findings:{type:"array",maxItems:j1,items:{type:"string",minLength:1,maxLength:B1}}},required:["verdict","summary","findings"],additionalProperties:!1};function U1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function kO(O){if(O.length<=v0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,v0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function S1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>V1||!Array.isArray($.findings)||$.findings.length>j1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=B1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function H4(O,$){let Q=S1(O);if(!Q)return;let Z=U1(Q.summary,$),J=Q.findings.map((K)=>U1(K,$));return kO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -730,4 +730,4 @@ ${Z.join(`
|
|
|
730
730
|
</${Q}>`:"";return{content:K,files:[...O],references:O.map($4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:D0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
|
|
731
731
|
`))}}function TO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=G1(O),this.definitions=Object.freeze([...$].sort(W1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=D0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
|
|
732
732
|
`))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=l$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&L1(J.scopeDirectory,Q));return q0(TO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=s$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>Y1(z.relative(this.projectRoot,G1(G)))).filter(X1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!L1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>_O(U,{dot:!0})(X)))continue}else if(L1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=TO([...q.values()].sort(W1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(W1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=Y1(z.relative(this.projectRoot,G1(O)));if($&&!X1($))throw Error("Project instruction source is outside the catalog root");return $}}async function Q4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>IO)throw Error(`Project rule exceeds ${IO} bytes`);let Z=await d.realpath($),J=Y1(z.relative(O,Z));if(!X1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(wO(K))throw Error("Project rule contains hidden control characters");let q=c$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=e$(q.data.paths),Y=O4(J),X=D0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${D0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function DO(O,$){let Q=r$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=u$.stream([...a$],{cwd:Z,absolute:!0,dot:!0,deep:n$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...t$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>MO)throw Error(`Project rule catalog exceeds ${MO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await Q4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>bO)throw Error(`Project rule catalog exceeds ${bO} bytes`);W.push(X)}catch(X){o$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var CO=32,C0=64;class NO extends Error{capacity=C0;constructor(){super(`Workspace agent resource capacity is full (${C0})`);this.name="WorkspaceAgentResourceCapacityError"}}var T=new Map,H1=0,EO=[];async function Z4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await K1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function J4(O){let $={...O};for(let Q of Object.values(A0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function K5(O){EO=[...new Set(O.map(($)=>N0.resolve($)))]}function vO(O,$){HO(O,$.plugins),w.releaseInstance(O,$.subagents),h.releaseInstance({cwd:O},$.skills),x.releaseInstance(O,$.commands),C.releaseInstance(O,$.plugins)}function RO(O){vO(O.workspaceRoot,O)}function K0(){while(T.size>CO){let O=!1;for(let[$,Q]of T){if(!Q.resources||Q.users>0)continue;if(T.get($)!==Q)continue;T.delete($),RO(Q.resources),O=!0;break}if(!O)return}}function q4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function K4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=x.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??EO])]),x0(O),await J1(O);let W=await K1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await DO(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw vO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function G4(O,$){let Q={generation:H1,users:0};return Q.promise=K4(O,$).then((Z)=>{if(Q.generation!==H1||T.get(O)!==Q)return RO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(T.get(O)===Q)T.delete(O);throw Z}),T.set(O,Q),Q}async function yO(O,$){let Q=N0.resolve(O),Z=T.get(Q);if(!Z){if(K0(),T.size>=C0)throw new NO;Z=G4(Q,$)}else T.delete(Q),T.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function fO(O,$){if(!$)return;x0(O.workspaceRoot),await J1(O.workspaceRoot),await Z4(O)}async function G5(O,$={}){let Q=await yO(O,$);try{return await fO(Q.resources,$.reconcilePlugins),Q.resources}finally{q4(Q.entry)}}async function L5(O,$,Q={}){let Z=await yO(O,Q);try{return await fO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function W5(){let O=0,$=0;for(let Q of T.values()){if(Q.resources)O++;$+=Q.users}return{capacity:CO,activeCapacity:C0,entries:T.size,initialized:O,inFlight:T.size-O,activeUsers:$}}function Y5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:N0.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??F1.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:J4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function X5(O){let $=N0.resolve(O);return{projectRoot:$,subagents:new w,skills:new h,commands:x.empty($),hooks:{enabled:!1},communicationStyles:F1.snapshot(),projectRules:m.empty($)}}function H5(){H1++;for(let[O,$]of T)if($.resources)x0(O);T.clear(),w.resetInstances(),h.resetInstance(),x.resetInstance(),C.resetInstance()}
|
|
733
|
-
export{X4 as
|
|
733
|
+
export{X4 as qg,H4 as rg,F4 as sg,I1 as tg,S4 as ug,z4 as vg,o as wg,f4 as xg,D1 as yg,g as zg,x as Ag,e0 as Bg,I0 as Cg,C as Dg,Q0 as Eg,J1 as Fg,x0 as Gg,m as Hg,CO as Ig,C0 as Jg,NO as Kg,Z4 as Lg,K5 as Mg,G5 as Ng,L5 as Og,W5 as Pg,Y5 as Qg,X5 as Rg,H5 as Sg};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{v as ez,w as zJ}from"./chunk-9z9v8v4j.js";import{A as S,x as hz,y as kz,z as Cz}from"./chunk-46jmq302.js";import{B as tz,C as Ez,D as Tz,E as xz,F as bz,G as Rz}from"./chunk-g4vgnxh4.js";import{Aa as yz,Ba as Mz,Ca as Iz,N as R,W as wz,X as Oz,ca as Nz,fa as Az,ga as qz,ja as Pz,za as Sz}from"./chunk-sy0vxdc3.js";import"./chunk-24rsvr6e.js";import{Qa as sz}from"./chunk-hx10bph0.js";import{Sa as Fz,Wa as l}from"./chunk-gq7fdc8c.js";import{Fb as Kz,Rb as Dz,_b as d}from"./chunk-c5rfnzhf.js";import{jc as m}from"./chunk-wzkh3e6a.js";import{Dd as M,Ed as v,Fd as jz,Kd as Gz,Nd as Vz,Pd as y,Sd as Uz,Xd as _z,_d as D,td as Qz}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import{De as i,Ee as Bz,we as Xz}from"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import{pf as JJ}from"./chunk-v2qxszks.js";import"./chunk-kbnxbb23.js";import{Kf as rz,Lf as az}from"./chunk-0qq64xqm.js";import"./chunk-v508x7cg.js";import{Wf as s}from"./chunk-q0s3gcjm.js";import{$f as Hz}from"./chunk-acsfh1cw.js";import"./chunk-tev70rzj.js";import{kg as oz}from"./chunk-vvawhvea.js";import"./chunk-82x77b2p.js";import"./chunk-1cbaqh71.js";import"./chunk-5sknjz9b.js";import{eh as nz}from"./chunk-f7hsagj6.js";import"./chunk-sv5z5sna.js";import"./chunk-qm96k94k.js";import"./chunk-77x1rrz9.js";import{hi as lz,ki as iz}from"./chunk-mm1atkae.js";import"./chunk-gdnyt8a7.js";import{Ii as g,Ji as Wz,Li as c,Mi as p}from"./chunk-vptn8fhx.js";import{Qi as n}from"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-jb8stg10.js";import{wj as I}from"./chunk-g7h0peka.js";import"./chunk-s3a017q7.js";import{Dj as vz,Gj as dz}from"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-zy2etr3v.js";import"./chunk-1p9sjb8d.js";import{Uj as Lz,Vj as pz,Zj as t,bk as e,ck as mz,dk as zz}from"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";import{Readable as KJ,Writable as DJ}from"node:stream";import*as f from"@agentclientprotocol/sdk";import r from"node:path";import{PROTOCOL_VERSION as jJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as fz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=I("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Yz(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function YJ(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Yz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Yz("headers"in z?z.headers:void 0)};return null}function LJ(z){let J={};for(let Z of z){let L=YJ(Z);if(L)J[Z.name]=L}return J}function uz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,L=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!L)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:L[1]??"image/png",data:L[2]??""}]})}function WJ(z){let J=Bz(z.metadata);return J?[{type:"text",text:i(J)}]:uz(z.content)}function HJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}function QJ(z){if(!Hz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function XJ(z){if(!(z instanceof fz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!jz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}function BJ(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,L,H={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=L;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Rz({maxPendingItems:Ez,maxPendingBytes:Tz,writeTimeoutMs:xz,signal:Z.signal,sizeOf:(Q)=>Buffer.byteLength(JSON.stringify(Q)),write:async(Q)=>{await Z.sessionUpdate(Q)},onFailure:(Q)=>this.handleUpdateEgressFailure(Q)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?D.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):D.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?D.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):D.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await D.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await D.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof _z)&&Z.code!=="ENOENT")throw Z;await D.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await D.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await D.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){V.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(W)=>{await this.sendUpdateAndWait(W)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?LJ(this.options.mcpServers):void 0,L=R.getInstance().getTerminalService(this.id),H=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Nz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...H?{workspace:H}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,j)=>{let G=await L.execute(W,{cwd:j.cwd,env:j.env,timeout:j.timeoutMs,signal:j.signal,allowLocalFallback:!1,onOutput:(U)=>j.onOutput?.("stdout",U)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.failureKind==="timeout",aborted:G.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.roots.hostStateRoot)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="follow_up.queue.changed"){let j=l.safeParse(W.properties.queue);if(j.success)this.sendFollowUpQueueSnapshot(j.data);return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:j,messageId:G,content:U}=W.properties,E=W.properties.metadata;if(W.type==="team.message.received"&&typeof j==="string"&&typeof G==="string"&&typeof U==="string"&&Oz(E,{messageId:G,teamName:j}))(async()=>{let q=await this.runtime?.enqueueSteering(U,{allowBeforeTurn:!0,messageId:G,origin:"team_message",metadata:E});if(!q?.accepted)return;if(q.queue)this.sendFollowUpQueueSnapshot(q.queue);if(await new wz(j,Lz()).markDelivered([G]),q.delivery==="next_turn")this.requestPendingResume()})().catch((q)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,q)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Y?.status==="active"||Y?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Xz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let L of WJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:L}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot())}catch{V.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Y);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Y)=>{if(await this.setReasoningEffort(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Y)=>{if(await this.setServiceTier(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Y)=>{if(await this.setResponseVerbosity(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Y)=>{if(await this.setCommunicationStyle(Y),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,W,j=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Y,prompt:X,onCompleted:(U)=>{if(B)j(U);else W=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,W)j(W);return G}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Y)},getPrompt:async(Y,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Y,X,B)},complete:async(Y,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Y,X,B)},listTasks:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Y)},getTask:async(Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Y)},cancelTask:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Y,X)},getLogs:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Y,X)},setLoggingLevel:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Y,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Y,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Y,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Y,signal:X,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),W=await B.completion,j=(await S.list(this.roots.hostStateRoot,this.id)).find((G)=>G.start.reviewId===B.reviewId);if(!j)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:W.status,findings:W.findings.length,content:Qz(j.start,W)}}}}:{},signal:J,acp:{sendMessage:(Y)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}})},sendToolStart:(Y,X,B)=>{let W=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W,status:"in_progress",title:`${Y}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:j})},sendToolResult:(Y,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},L=await Mz(z,Z),H=L.data?.action;if(H==="start_goal"||H==="resume_goal")this.requestPendingResume();if(H==="rewind_session"&&Array.isArray(L.data?.messages))this.messages=[...L.data.messages],this.contextMessages=await this.loadModelContextOr(L.data.messages);if((L.message==="compact_completed"||L.message==="compact_fallback")&&L.data?.compactedMessages){this.contextMessages=[...L.data.compactedMessages];let Y=await this.loadPersistedMessages();if(Y.length>0)this.messages=Y}let Q=L.content||L.message;if(Q)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}});if(L.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${L.error}`}});return await this.flushUpdates(),{stopReason:L.success?"end_turn":"cancelled"}}catch(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,L=new Promise((H)=>{Z=H});this.pendingSideConversation=J,this.pendingSideConversationCompletion=L;try{return await this.handleSlashCommand(z,J.signal)}catch(H){if(J.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(Z(),this.pendingSideConversationCompletion===L)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Iz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],L=z.filter((H)=>!J.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let Q;if(H.usage){let Y=H.usage.replace(/^\/\w+\s*/,"").trim();if(Y)Q=Y}if(H.aliases?.length){let Y=`Aliases: ${H.aliases.join(", ")}`;Q=Q?`${Q} | ${Y}`:Y}return{name:H.name,description:H.description,input:Q?{hint:Q}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(L.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:L}),V.info(`[AcpSession ${this.id}] Sent ${L.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),L=Z.content,H=Z.displayText,Q=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((_)=>_.outputSchema)?.outputSchema:void 0),Y;if(Q!==void 0)Y=Uz(Q).schema;if(H.trimStart().startsWith("!")){if(Y)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let X=Fz(H);if(X){if(Y)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(L)&&L.some((_)=>_.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(X.question?`/btw ${X.question}`:"/btw")}if(this.pendingPrompt){if(Y)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let _=await this.runtime.enqueueSteering(L,{allowBeforeTurn:!0});if(!_.accepted)throw Error(_.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${_.queued})`),this.sendFollowUpQueueSnapshot(_.queue??await this.runtime.getFollowUpQueueSnapshot()),_.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,W=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)W();else J.abortSignal?.addEventListener("abort",W,{once:!0});let j=!1,G=!1,U=!1,E,q=new Promise((_)=>{E=_});this.pendingPrompt=B,this.pendingPromptCompletion=q;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Sz(H)){if(Y)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,B.signal)}let _={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Dz(this.agent.chatStream(L,_,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Y}),async($)=>{switch($.kind){case"content_delta":if(Y)break;if($.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{U=!0;let K=$.toolCall,N=K.function.name;if(N===y)break;let P=this.mapToolKind($.toolKind),F=`Executing ${N}`;if(N==="Task"&&"function"in K)try{let b=JSON.parse(K.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")F=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:F,content:[],kind:P});break}case"tool_progress":{U=!0;let K=$.toolCall;if(K.function.name===y)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{U=!0;let K=$.toolCall;if(K.function.name===y)break;let N=$.result,P=[],F=N.metadata;if(F?.kind==="patch"&&Array.isArray(F.changes))for(let w of F.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;P.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(F?.kind==="edit"&&typeof F.file_path==="string"&&typeof F.oldContent==="string"&&(typeof F.newContent==="string"||F.newContent===void 0))P.push({type:"diff",path:F.file_path,oldText:F.oldContent,newText:F.newContent??null});else{let w=K.function.name,ZJ=qz(Vz(Az(w,N),Gz));P.push({type:"content",content:{type:"text",text:ZJ}})}if(K.function.name==="Task"&&(F?.verificationVerdict==="pass"||F?.verificationVerdict==="fail"||F?.verificationVerdict==="partial"))P.unshift({type:"content",content:{type:"text",text:`Verification result: ${F.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:b,content:P});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"provider_admission":j=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":this.sendFollowUpQueueSnapshot($.queue);break;case"follow_up_queue_changed":this.sendFollowUpQueueSnapshot($.queue);break;case"follow_up_started":{this.sendFollowUpQueueSnapshot($.queue);let K=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let P of uz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:P});J.projectedRecoveredInputIds?.add(N.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[..._.messages];let Zz=await this.loadPersistedMessages();if(this.messages=Zz.length>0?Zz:[..._.messages],!O.success){let $=O.error?.type??"unknown",K=O.error?.details??O.error?.message??"Agent execution failed",N=QJ(K)??v(K);throw fz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:G,toolExecutionStarted:U,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let $z={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys($z).length>0?{_meta:$z}:{}}}catch(_){if(B.signal.aborted||_ instanceof Error&&_.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,_),_}finally{if(J.abortSignal?.removeEventListener("abort",W),j&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(E(),this.pendingPromptCompletion===q)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,L,H=new Promise((X)=>{L=X});this.pendingUserShell=Z,this.pendingUserShellCompletion=H;let Q,Y="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(W)=>{if(Q=W.executionId,W.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:W.executionId,status:"in_progress",title:`! ${W.command}`,content:[],kind:"execute"});return}if(W.type==="output"){Y+=W.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.chunk}}]});return}let j=i(W.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.executionId,status:W.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Y?HJ(W.record):j}}]})}}),B={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(B),this.contextMessages.push(B),X.queue)this.sendFollowUpQueueSnapshot(X.queue);if(X.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(Q)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Q,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(L(),this.pendingUserShellCompletion===H)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:hz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",L=!1,H,Q=null;try{let Y=this.runtime.getPendingSteeringCount()>0,X=Y?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=X?.status==="active"||X?.status==="verifying",W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none"&&(W.state==="requires_attention"||!Y&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}});if(!Y&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(W.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Y?"pending_input":"goal",L=!0;let j=kz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(j<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let G=new AbortController;Q=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},j),Q.unref?.();let U=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Y,goalContinuationOnly:B,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(U.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Y){if(z!==this.pendingResumeGeneration)return;let X=L?XJ(Y):{taskFailure:v(Y),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,W=Cz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:X});if(W.phase==="retry_scheduled")this.pendingResumeRequested=!0,H=W.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:X?.taskFailure,delayMs:W.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${W.delayMs}ms`);else{let j=W.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(j,{attempt:J,kind:Z,taskFailure:X?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${W.retryable}, phase=${j})`,Y),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(Q!==null)clearTimeout(Q);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=H??0}}cancel(){V.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",L=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(L),this.mode=Z,V.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((L)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,L)});throw Z}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(L){throw await this.runtime.refresh({communicationStyle:J.selection}),L}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new bz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,L=this.pendingPromptCompletion,H=this.pendingUserShellCompletion,Q=this.pendingSideConversationCompletion,Y=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let X,B=async(W)=>{try{await W()}catch(j){X??=j}};if(await B(()=>this.cancel()),L)await B(()=>L);if(H)await B(()=>H);if(Q)await B(()=>Q);if(Y)await B(()=>Y);if(z&&L&&Z)await B(()=>Z.discardPendingInput());if(J)await B(()=>J.destroy());if(Z)await B(()=>Z.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,V.debug(`[AcpSession ${this.id}] Destroyed`),X!==void 0)throw X}resolvePrompt(z){let J=[],Z=[],L=0,H=0,Q=0,Y=(W)=>{if(Z.length>0)Z.push({type:"text",text:`
|
|
13
|
+
`}),Q+=1;if(Z.push(W),W.type==="text")Q+=W.text.length};for(let W of z)if(W.type==="text")J.push(W.text),Y({type:"text",text:W.text});else if(W.type==="image"){let j=`data:${W.mimeType};base64,${W.data}`;L+=1,H+=j.length,J.push(`[Image: ${W.mimeType}]`),Y({type:"image_url",image_url:{url:j}})}else if(W.type==="resource"){let j=W.resource;if("text"in j){let G=`<file path="${j.uri}">
|
|
14
|
+
${j.text}
|
|
15
|
+
</file>`;J.push(G),Y({type:"text",text:G})}}else if(W.type==="resource_link"){let j=`[Resource: ${W.uri}]`;J.push(j),Y({type:"text",text:j})}if(L>g)throw Error(`ACP prompt contains more than ${g} images`);if(H>Wz)throw Error("ACP prompt images exceed the 5 MiB limit");if(Q>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
+
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=J.join(`
|
|
17
|
+
`);return{content:L>0?Z:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendFollowUpQueueSnapshot(z){let J=l.safeParse(z);if(!J.success)return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/followUpQueue":BJ(J.data)}})}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;V.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return V.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let L=u(),H=[];if(z.message)H.push({type:"content",content:{type:"text",text:z.message}});if(z.details)H.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
+
- ${z.risks.join(`
|
|
19
|
+
- `)}`}});let Q=this.mapToolKind(Z),Y={sessionId:this.id,options:z.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:L,status:"pending",title:z.title||"Permission Required",content:H,kind:Q}},X=await this.waitForClientInteraction(this.connection.requestPermission(Y),J);if(!X)return{approved:!1,reason:m};let B=X.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let W=B.optionId;if(W==="allow_always")return{approved:!0,scope:"project"};if(W==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let j=W==="allow_once";return{approved:j,scope:"once",reason:j?void 0:"User denied the operation"}}catch(L){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,L),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let L={};try{for(let[H,Q]of Z.entries()){let Y=Q.options.map((j,G)=>`answer:${H}:${G}`),X=`answer:${H}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.options.map((j,G)=>({optionId:Y[G],name:j.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:Q.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Q.question,...Q.options.map((j)=>`${j.label}: ${j.description}`)].join(`
|
|
20
|
+
`)}}]}}),J);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let W=Y.indexOf(B.outcome.optionId);if(W<0)return{approved:!1,reason:"User cancelled the question prompt"};L[Q.header]=Q.options[W].label}return{approved:!0,answers:L}}catch(H){return V.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let L=Object.create(null);for(let H of Z.fields??[]){let Q=await this.collectAcpElicitationField(H,J);if(Q.cancelled)return{approved:!1,reason:Q.reason,elicitation:{action:"cancel"}};if(Q.value!==void 0)L[H.name]=Q.value}return{approved:!0,elicitation:{action:"accept",content:L}}}catch(L){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,L),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Q,Y)=>({id:`option:${Y}`,label:Q.label,value:Q.value})),L=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
+
`),[...Z.map((Q)=>({id:Q.id,label:Q.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(L==="skip")return{cancelled:!1};let H=Z.find((Q)=>Q.id===L);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(z.defaultValue!==void 0){let Z=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
+
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,Z,L){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((Q)=>({optionId:Q.id,name:Q.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),L);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,L)=>{let H=!1,Q=(X)=>{if(H)return;H=!0,J.removeEventListener("abort",Y),X()},Y=()=>Q(()=>Z(void 0));if(J.addEventListener("abort",Y,{once:!0}),J.aborted)Y();z.then((X)=>Q(()=>Z(X)),(X)=>Q(()=>L(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=I("Agent"),GJ="remote task isolation is not supported";function h(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function VJ(z){return C.invalidParams({code:z.code,reason:z.reason})}function UJ(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:GJ})}function gz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function cz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return t(z)}catch(J){if(J instanceof pz)throw VJ(J);throw J}}function a(z,J){let Z=e(z);return Object.freeze({kind:"acp-remote",hostStateRoot:zz(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function o(z,J){let Z=mz(z.remoteWorkspace),L=zz(Z.collisionIdentity);if(z.projectPath!==L)throw Error("ACP remote workspace durable state is invalid");let H=t(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:L,executionRoot:Z.wirePath,hostResourceRoot:J,profile:H,descriptor:Z})}function _J(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class Jz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=r.resolve(n())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=rz();this.runtimeResidencyValue=new zJ({maxResident:z?.maxResidentSessionRuntimes??lz,idleMs:z?.sessionRuntimeIdleMs??iz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof ez)throw C.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:jJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=s("acp"),Z=z.cwd||n(),L=h(this.clientCapabilities),H=L?k(Z):void 0,Q=z._meta?.["blade/taskIsolation"],Y=Q==="local"||Q==="worktree"?Q:void 0;if(L&&Y)throw UJ();let X=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(J),W;try{let j,G;if(H){let E=a(H,this.hostResourceRoot);j=await D.createRemoteSessionMetadata(J,E.hostStateRoot,E.descriptor,{}),G=o(j,this.hostResourceRoot)}else G=T(Z);let U=!L&&Y?await tz.createSessionTask({sessionId:J,prompt:typeof X==="string"&&X.trim()?X:"ACP task session",sourceProjectPath:Z,isolation:Y}):void 0;if(U)G=T(U.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${G.kind}`),W=new x(J,G,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...U?.taskWorktree?{taskWorktree:U.taskWorktree}:{},...U?.metadata.taskIsolation?{taskIsolation:U.metadata.taskIsolation}:{}}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(J,W,B),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,U?.metadata,W.getModelConfiguration())}catch(j){throw B.cancel(),await W?.destroy().catch(()=>{return}),j}}async listSessions(z){let J=h(this.clientCapabilities);if(!J&&z.cwd!=null&&!r.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await D.listRemoteSessionPage({...z.cwd!=null?{descriptor:e(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await D.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((L)=>({sessionId:L.sessionId,cwd:J?_J(L):L.projectPath,title:L.title??null,updatedAt:L.lastMessageTime,_meta:{"blade/taskStatus":L.taskStatus,...L.taskStatusReason?{"blade/taskStatusReason":L.taskStatusReason}:{},...L.taskFailure?{"blade/taskFailure":L.taskFailure}:{},...L.taskStartedAt?{"blade/taskStartedAt":L.taskStartedAt}:{},...L.taskCompletedAt?{"blade/taskCompletedAt":L.taskCompletedAt}:{},...L.taskModelId?{"blade/taskModelId":L.taskModelId}:{},...L.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...L.taskRetriedFrom?{"blade/taskRetriedFrom":L.taskRetriedFrom}:{},...L.taskDelivery?{"blade/taskDelivery":L.taskDelivery}:{},...L.taskIsolation?{"blade/taskIsolation":L.taskIsolation}:{},...L.taskSourceProjectPath?{"blade/taskSourceProjectPath":L.taskSourceProjectPath}:{},...L.taskWorktreeBranch?{"blade/taskWorktreeBranch":L.taskWorktreeBranch}:{},...L.taskBaseCommit?{"blade/taskBaseCommit":L.taskBaseCommit}:{},...L.taskDiffStat?{"blade/taskDiffStat":L.taskDiffStat}:{},...L.taskQueuePosition?{"blade/taskQueuePosition":L.taskQueuePosition}:{},...L.taskQueueDepth!==void 0?{"blade/taskQueueDepth":L.taskQueueDepth}:{},...L.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":L.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=h(this.clientCapabilities),Z=J?a(k(z.cwd),this.hostResourceRoot):void 0;if(!J&&!r.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let L=s("fork"),H=await this.reserveSessionRuntime(L),Q;try{let Y;try{Y=await D.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:L,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(B){if(cz(B))throw gz();throw B}this.assertNotDestroyed();let X=J?o(Y.metadata,this.hostResourceRoot):T(Y.projectPath??z.cwd);return Q=new x(Y.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:Y.messages,permissionMode:Y.metadata.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),this.assertNotDestroyed(),this.commitSession(Y.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Y.sessionId,J?void 0:Y.metadata,Q.getModelConfiguration())}catch(Y){throw H.cancel(),await Q?.destroy().catch(()=>{return}),Y}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),L=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,L);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===L)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!h(this.clientCapabilities)){await D.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),B;try{let[W,j]=await Promise.all([D.loadSession(z.sessionId,z.cwd),D.findSessionMetadata(z.sessionId,z.cwd)]);if(!j)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,T(z.cwd),this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:j.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,X),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(W){throw X.cancel(),await B?.destroy().catch(()=>{return}),W}}let Z=a(k(z.cwd),this.hostResourceRoot),L;try{L=await D.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(X){if(cz(X))throw gz();throw X}let H=o(L,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let Q=await this.reserveSessionRuntime(z.sessionId),Y;try{let X=await D.loadRemoteSession(z.sessionId,H.hostStateRoot,H.descriptor);return Y=new x(z.sessionId,H,this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:L.permissionMode,mcpServers:z.mcpServers}),await Y.initialize(),await Y.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Y,Q),Y.sendAvailableCommandsDelayed(),this.buildSessionSetup(Y.getModelConfiguration(),Y.getMode())}catch(X){throw Q.cancel(),await Y?.destroy().catch(()=>{return}),X}}commitSession(z,J,Z){let L=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),L.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let L=this.runtimeResidency.owns(z,Z),H;try{await Z.destroy(J)}catch(Y){H=Y}let Q=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(L&&!Q&&H===void 0)throw Error(`ACP Session is still active: ${z}`);if(H!==void 0)throw H}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],L=(z?.currentModelId&&Z.some((Y)=>Y.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],Q=[];if(Z.length>0)Q.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:L,options:Z.map((Y)=>({value:Y.id,name:Y.displayName??Y.model,description:`${z?.modelProviders[Y.provider]?.name??Y.provider} · ${Y.model}`}))});if(z?.reasoning)Q.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:Y==="off"?"Disable model reasoning":`Use ${Y} reasoning effort`}))]});if(z?.serviceTier)Q.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:Y==="fast"?"Use the provider priority tier":Y==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Q.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Y)=>({value:Y,name:Y[0].toUpperCase()+Y.slice(1),description:`Use ${Y} response verbosity`}))]});if(z?.communicationStyle)Q.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Y)=>({value:Y.id,name:Y.name,description:`${Y.description} · ${Y.source}`}))});return{modes:{availableModes:H,currentModeId:J},configOptions:Q.length>0?Q:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),L=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,L);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===L)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&dz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&nz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await sz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function KZ(){let z=DJ.toWeb(process.stdout),J=KJ.toWeb(process.stdin),Z=f.ndJsonStream(z,J),L,H=new f.AgentSideConnection((Y)=>{return L=new Jz(Y),L},Z),Q=JJ(async()=>{await L?.destroy()});try{await H.closed}finally{Q(),await L?.destroy()}}export{KZ as runAcpIntegration,T as createLocalAcpSessionRoots};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Ud as a,Vd as b,Wd as c,Xd as d,Yd as e,Zd as f,_d as g}from"./chunk-mxe4pr8t.js";import"./chunk-z3hpstky.js";import"./chunk-mq1mk3v5.js";import"./chunk-fnc97xg7.js";import"./chunk-vvawhvea.js";import"./chunk-f7hsagj6.js";import"./chunk-77x1rrz9.js";import"./chunk-vptn8fhx.js";import"./chunk-jc28ddt0.js";import"./chunk-nfzad4te.js";import"./chunk-g7h0peka.js";import"./chunk-bdtpq7j9.js";import"./chunk-w2n1vwzg.js";import"./chunk-na3nregt.js";import"./chunk-ntd69c0k.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
|
|
2
|
-
export{N as
|
|
2
|
+
export{N as Sj,S as Tj};
|