blade-code 0.10.28 → 0.10.29
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-a1a4351m.js → chunk-0mq1yd3k.js} +2 -2
- package/dist/{chunk-0pbvrw1c.js → chunk-0prp87ys.js} +1 -1
- package/dist/{chunk-6vfctcqp.js → chunk-0rwz7tm0.js} +1 -1
- package/dist/{chunk-2gre3vrn.js → chunk-0yy41vwq.js} +2 -2
- package/dist/{chunk-2ycs4wce.js → chunk-1ggxyyar.js} +1 -1
- package/dist/chunk-1p45ytbg.js +1 -0
- package/dist/chunk-1yyyt228.js +1 -0
- package/dist/{chunk-t0n90d7w.js → chunk-1zpqxjj7.js} +2 -2
- package/dist/{chunk-stmsk0kz.js → chunk-2d35rmyg.js} +2 -2
- package/dist/chunk-33wkt12h.js +1 -0
- package/dist/{chunk-0pcwv1h8.js → chunk-37se34rx.js} +1 -1
- package/dist/{chunk-yv2sdpxk.js → chunk-39gb49pv.js} +1 -1
- package/dist/{chunk-287fabvz.js → chunk-48tz6s0s.js} +2 -2
- package/dist/{chunk-jvtzyba4.js → chunk-4djps7bz.js} +1 -1
- package/dist/{chunk-j9djsqqy.js → chunk-4p9cwr9s.js} +2 -2
- package/dist/{chunk-hbhcj665.js → chunk-4qtb8yf6.js} +2 -2
- package/dist/{chunk-k3wmp1xm.js → chunk-4qyhtrhx.js} +1 -1
- package/dist/chunk-5dt6199b.js +1 -0
- package/dist/{chunk-axcaxcgk.js → chunk-5jxm20vq.js} +2 -2
- package/dist/{chunk-69r9j0ms.js → chunk-5m5nxkfs.js} +1 -1
- package/dist/{chunk-apq6qqjg.js → chunk-5x26t0c4.js} +3 -3
- package/dist/{chunk-wn60hv0w.js → chunk-66f2fv34.js} +16 -16
- package/dist/{chunk-sh2kjand.js → chunk-6kc12pma.js} +1 -1
- package/dist/{chunk-0xhd2mzm.js → chunk-8gv6hsrf.js} +2 -2
- package/dist/{chunk-1ycv8b9t.js → chunk-9pww3s5m.js} +1 -1
- package/dist/chunk-a5yd0c77.js +1 -0
- package/dist/{chunk-dx5996qr.js → chunk-amm31k3r.js} +1 -1
- package/dist/{chunk-gpa4y0xk.js → chunk-b5btamzc.js} +1 -1
- package/dist/{chunk-cbyewxx4.js → chunk-bbfeb6ry.js} +1 -1
- package/dist/{chunk-1e9cpchh.js → chunk-bk649qwy.js} +1 -1
- package/dist/{chunk-a1ftc84p.js → chunk-c2sxy022.js} +2 -2
- package/dist/{chunk-5wkv5g4v.js → chunk-d4327k1v.js} +1 -1
- package/dist/{chunk-djzy4zgc.js → chunk-d9gthet1.js} +2 -2
- package/dist/{chunk-dny4h2gz.js → chunk-ej1z75jf.js} +1 -1
- package/dist/{chunk-p4hf7agx.js → chunk-ekv4hpy8.js} +2 -2
- package/dist/{chunk-sjbqm4be.js → chunk-fewpzx8s.js} +2 -2
- package/dist/{chunk-p2j0wcca.js → chunk-fvfwmdp0.js} +2 -2
- package/dist/{chunk-xqapcfw3.js → chunk-gdp6fg4e.js} +1 -1
- package/dist/{chunk-78bknnzt.js → chunk-grt2wftd.js} +2 -2
- package/dist/chunk-h45x1nem.js +1 -0
- package/dist/{chunk-6qdwp1t3.js → chunk-hdr8bcxt.js} +1 -1
- package/dist/{chunk-rqvejn8x.js → chunk-heydawsf.js} +2 -2
- package/dist/{chunk-d6a4qw1m.js → chunk-js9g83ty.js} +1 -1
- package/dist/{chunk-tct2ybbh.js → chunk-k98n1xwg.js} +2 -2
- package/dist/chunk-m9rg16w4.js +10 -0
- package/dist/chunk-mqezgpcw.js +1 -0
- package/dist/{chunk-ecvk8npm.js → chunk-p6s92zj1.js} +1 -1
- package/dist/{chunk-8djaj8m7.js → chunk-pamjbphm.js} +2 -2
- package/dist/chunk-pdkj959x.js +1 -0
- package/dist/chunk-pwwm04bc.js +1 -0
- package/dist/chunk-q0c3fww1.js +22 -0
- package/dist/chunk-qgp7sqh2.js +1 -0
- package/dist/{chunk-rf3jf275.js → chunk-qv9xa4h1.js} +3 -3
- package/dist/{chunk-x3dche8v.js → chunk-rezjy4mp.js} +2 -2
- package/dist/chunk-rfybbxab.js +4 -0
- package/dist/{chunk-9ev9k5bd.js → chunk-s0txchah.js} +2 -2
- package/dist/{chunk-70kccy7a.js → chunk-s3zfyy7r.js} +1 -1
- package/dist/chunk-s6rdv601.js +2 -0
- package/dist/chunk-szmm21q9.js +1 -0
- package/dist/chunk-tf9jmrwk.js +1 -0
- package/dist/chunk-v5q235ny.js +1 -0
- package/dist/{chunk-tdevyej4.js → chunk-vz0zsct0.js} +1 -1
- package/dist/chunk-vz7hpwf0.js +1 -0
- package/dist/chunk-wxzsnptj.js +6 -0
- package/dist/{chunk-q4fy74fz.js → chunk-x1p5dmfv.js} +2 -2
- package/dist/{chunk-4y6pjd2n.js → chunk-xn5zf98b.js} +2 -2
- package/dist/{chunk-taj3qfn3.js → chunk-xr033fd3.js} +1 -1
- package/dist/{chunk-ae7f5mh9.js → chunk-z5eaph4a.js} +1 -1
- package/dist/{chunk-gbmnbckj.js → chunk-z9ytq8tq.js} +2 -2
- package/dist/chunk-zx8ktpc4.js +9 -0
- package/package.json +1 -1
- package/dist/chunk-03633tsz.js +0 -10
- package/dist/chunk-1kxz32m6.js +0 -1
- package/dist/chunk-1sregjyz.js +0 -1
- package/dist/chunk-2byq2qja.js +0 -1
- package/dist/chunk-3t5gqr9e.js +0 -1
- package/dist/chunk-6znn1a5v.js +0 -1
- package/dist/chunk-7hjz5jjn.js +0 -9
- package/dist/chunk-8k9ark1n.js +0 -1
- package/dist/chunk-98rbxm1y.js +0 -22
- package/dist/chunk-br9230a2.js +0 -2
- package/dist/chunk-hb9yjfja.js +0 -1
- package/dist/chunk-jk66yar2.js +0 -1
- package/dist/chunk-k52a3bq6.js +0 -1
- package/dist/chunk-n1qmwjmc.js +0 -1
- package/dist/chunk-p2yb40zk.js +0 -4
- package/dist/chunk-qewf02br.js +0 -1
- package/dist/chunk-qsj712zc.js +0 -1
- package/dist/chunk-ry7226b5.js +0 -6
- package/dist/chunk-x1a5wv45.js +0 -1
- package/dist/chunk-z516a7nx.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{da as j,ea as g0,ja as sJ,ka as a8,la as x0}from"./chunk-xn5zf98b.js";import{Fa as y7,ma as I7,oa as v7,pa as b4}from"./chunk-1zpqxjj7.js";import{Ga as K$,Ha as F2,Ia as I8,Ja as b1,Ka as N9,Na as _0,Pa as j2,Qa as y8,Ra as x8,Sa as h8,Va as u2,Xa as j6,Ya as d2,Za as g2,ab as o0,gb as J5,hb as uJ,ib as zJ,qb as Q9}from"./chunk-5x26t0c4.js";import{$b as NJ,Ab as M4,Bb as x2,Cb as h2,Mb as o2,Nb as E0,Ob as c0,Xb as P4,Yb as _1,Zb as t$,_b as AJ,cc as cJ,gc as W9,lc as TJ,mc as fJ,oc as n,wb as V0,xb as V1,yb as C$,zb as a1}from"./chunk-fvfwmdp0.js";import{pc as T9,qc as f9,rc as T2}from"./chunk-4djps7bz.js";import{Dc as d7,Jc as g7,sc as h7,vc as u7}from"./chunk-rezjy4mp.js";import{Uc as bZ,Vc as wZ}from"./chunk-d9gthet1.js";import{fd as m2,gd as B0,hd as k,kd as G0,ld as M2,md as $1,nd as w$,od as x6,pd as I$,qd as H9,vd as s$}from"./chunk-pamjbphm.js";import{wd as H$}from"./chunk-6kc12pma.js";import{Cd as PJ,Dd as C2}from"./chunk-4qtb8yf6.js";import{Fd as M0,Gd as j$}from"./chunk-4p9cwr9s.js";import{Hd as gJ}from"./chunk-vz0zsct0.js";import{Jd as FJ,Kd as wJ,Ld as DJ}from"./chunk-grt2wftd.js";import{$d as c$,Md as k2,Nd as I2,Pd as v2,Qd as y2,Rd as N$,Sd as S9,Ud as I0,Vd as o7,Wd as y0,Xd as m0,Yd as L5,Zd as t2,_d as Z$,ae as l$,be as LJ,ce as Z4,ee as Y0,fe as R2,ge as MJ}from"./chunk-k98n1xwg.js";import{ie as Z1,ke as s0,le as q2}from"./chunk-0prp87ys.js";import{me as H7,oe as bJ,pe as s2,qe as LZ}from"./chunk-9pww3s5m.js";import{se as K4,ue as b0}from"./chunk-qv9xa4h1.js";import{ve as g1,we as j4,xe as m1,ye as n$}from"./chunk-s3zfyy7r.js";import{$e as d$,Ae as HZ,Fe as WZ,He as V4,Me as aJ,Qe as QZ,Se as GJ,Ue as P8,Ve as k8,bf as a4,df as CJ,ef as qJ,ff as o8,gf as t8,hf as e8,if as $9,jf as Z9,kf as J9,lf as X0}from"./chunk-0yy41vwq.js";import{of as $2,pf as p4,qf as _,rf as P9,sf as S,tf as i}from"./chunk-4qyhtrhx.js";import{vf as OJ,wf as VJ}from"./chunk-s6rdv601.js";import{Af as N,yf as H2}from"./chunk-1ggxyyar.js";import{Ef as l}from"./chunk-ekv4hpy8.js";import{Jf as KJ,Kf as EJ}from"./chunk-8gv6hsrf.js";import{Lf as Q7,Of as X7}from"./chunk-5m5nxkfs.js";import{Sf as B7}from"./chunk-x1p5dmfv.js";import{Xf as P0}from"./chunk-2d35rmyg.js";import{_f as r1,ag as h$,cg as _J,dg as m4,fg as w0}from"./chunk-heydawsf.js";import{hg as e0}from"./chunk-37se34rx.js";import{randomUUID as V3}from"crypto";var e7=String.raw`
|
|
2
2
|
const { spawn } = require('node:child_process');
|
|
3
3
|
const [ownerPidValue, command, ...args] = process.argv.slice(1);
|
|
4
4
|
const ownerPid = Number(ownerPidValue);
|
|
@@ -610,7 +610,7 @@ ${Y.join(`
|
|
|
610
610
|
`)}`:X}function j8($,Z){let J=$.snapshot,U=J.stdout.accountingComplete&&J.stderr.accountingComplete;return{capture_truncated:$.captureTruncated,projection_truncated:$.projectionTruncated,output_truncated:$.captureTruncated||$.projectionTruncated,stdout_projection_truncated:$.stdoutProjectionTruncated,stderr_projection_truncated:$.stderrProjectionTruncated,stdout_total_bytes:J.stdout.totalBytes,stdout_retained_bytes:J.stdout.retainedBytes,stdout_omitted_bytes:J.stdout.omittedBytes,stderr_total_bytes:J.stderr.totalBytes,stderr_retained_bytes:J.stderr.retainedBytes,stderr_omitted_bytes:J.stderr.omittedBytes,raw_output_bytes:J.stdout.totalBytes+J.stderr.totalBytes,has_stderr:J.stderr.totalBytes>0||J.stderr.totalChars>0,output_accounting_complete:U,terminal_transport:Z,terminal_output_merged:J.terminalOutputMerged,...U?{stdout_length:J.stdout.totalChars,stderr_length:J.stderr.totalChars}:{}}}function M8($,Z,J,U){let X=$.snapshot;return{stdout:$.stdout,stderr:$.stderr,execution_time:Z,exit_code:J,...U!==void 0?{signal:U}:{},output_truncated:$.captureTruncated||$.projectionTruncated,stdout_omitted_bytes:X.stdout.omittedBytes,stderr_omitted_bytes:X.stderr.omittedBytes,stdout_total_bytes:X.stdout.totalBytes,stderr_total_bytes:X.stderr.totalBytes,output_accounting_complete:X.stdout.accountingComplete&&X.stderr.accountingComplete,...X.terminalOutputMerged?{terminal_output_merged:!0}:{},...$.truncationInfo&&{truncation_info:$.truncationInfo}}}async function IX($,Z,J,U,X,Y,H){let W=Date.now();try{let O=await I4(Y).execute($,{cwd:Z||N(),env:J,timeout:U,signal:X,allowLocalFallback:!1,durableOwnership:H}),V=Date.now()-W,z=O.capture?z6(O.capture,$):void 0,B=z?j8(z,O.transport):{};if(O.failureKind==="aborted")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,...z?{stdout:z.stdout,stderr:z.stderr}:{},execution_time:V,exit_code:O.exitCode,acp_mode:!0,...B}};if(O.failureKind==="timeout")return{success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,...z?{stdout:z.stdout,stderr:z.stderr}:{},execution_time:V,exit_code:O.exitCode,acp_mode:!0,...B}};let G=$.length>30?`${$.substring(0,30)}...`:$,K=O.success?`执行命令成功 (${V}ms): ${G}`:O.failureKind?`执行命令失败 (${O.failureKind}, ${V}ms): ${G}`:`执行命令完成 (退出码 ${O.exitCode}, ${V}ms): ${G}`,E={command:$,execution_time:V,exit_code:O.exitCode,acp_mode:!0,summary:K,...B};if(!z){let q=O.error??"ACP terminal execution failed";return{success:!1,llmContent:`Command execution failed: ${q}`,error:{type:"execution_error",message:q},metadata:E}}return{success:O.success,llmContent:M8(z,V,O.exitCode),...O.success?{}:{error:{type:"execution_error",message:O.failureKind?[O.error??`Terminal failure: ${O.failureKind}`,z.stderr?`stderr:
|
|
611
611
|
${z.stderr}`:"",z.stdout?`stdout:
|
|
612
612
|
${z.stdout}`:""].filter(Boolean).join(`
|
|
613
|
-
`):f8(O.exitCode,void 0,z.stdout,z.stderr)}},metadata:E}}catch(Q){let O=Q,V=Date.now()-W;return{success:!1,llmContent:`Command execution failed: ${O.message}`,error:{type:"execution_error",message:O.message,details:O},metadata:{command:$,execution_time:V,error:O.message}}}}async function vX($,Z,J,U,X,Y,H){let W=Date.now(),Q=Y?.executable??"bash",O=Y?.args??["-c",$],V=Y?.inheritProcessEnv===!1?yX(process.env):process.env,z;try{z=await e1(Q,O,{cwd:Z||N(),env:{...V,...J,...Y?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},H)}catch(B){throw Y?.cleanup(),B}return new Promise((B)=>{let{child:G,processTree:K}=z,E=new _$,q=!1,w=!1,F=!1,D,b,A,L,T=()=>{return L??=K.terminate(),L},C=setTimeout(()=>{if(w)return;q=!0,T()},U),f=()=>{if(w)return;T(),clearTimeout(C)},M=()=>{if(X.removeEventListener)X.removeEventListener("abort",f);else if("onabort"in X)X.onabort=null},R=()=>{if(w)return;w=!0;let I={timedOut:q,aborted:X.aborted};return clearTimeout(C),M(),I},d=()=>{Y?.cleanup(),clearTimeout(C),M()},
|
|
613
|
+
`):f8(O.exitCode,void 0,z.stdout,z.stderr)}},metadata:E}}catch(Q){let O=Q,V=Date.now()-W;return{success:!1,llmContent:`Command execution failed: ${O.message}`,error:{type:"execution_error",message:O.message,details:O},metadata:{command:$,execution_time:V,error:O.message}}}}async function vX($,Z,J,U,X,Y,H){let W=Date.now(),Q=Y?.executable??"bash",O=Y?.args??["-c",$],V=Y?.inheritProcessEnv===!1?yX(process.env):process.env,z;try{z=await e1(Q,O,{cwd:Z||N(),env:{...V,...J,...Y?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},H)}catch(B){throw Y?.cleanup(),B}return new Promise((B)=>{let{child:G,processTree:K}=z,E=new _$,q=!1,w=!1,F=!1,D,b,A,L,T=()=>{return L??=K.terminate(),L},C=setTimeout(()=>{if(w)return;q=!0,T()},U),f=()=>{if(w)return;T(),clearTimeout(C)},M=()=>{if(X.removeEventListener)X.removeEventListener("abort",f);else if("onabort"in X)X.onabort=null},R=()=>{if(w)return;w=!0;let I={timedOut:q,aborted:X.aborted};return clearTimeout(C),M(),I},d=()=>{Y?.cleanup(),clearTimeout(C),M()},r=()=>{return E.finish(),z6(E.snapshot(),$)},P=(I,y)=>{return{...y,...j8(I,"local")}},$0=(I,y,t,g)=>M8(I,y,t,g),J0=(I)=>{if(F)return;F=!0,d(),B(I)};if(G.stdout?.on("data",(I)=>{E.append("stdout",I)}),G.stderr?.on("data",(I)=>{E.append("stderr",I)}),X.addEventListener)X.addEventListener("abort",f);else if("onabort"in X)X.onabort=f;if(X.aborted)f();if(G.on("close",async(I,y)=>{let t=R();if(!t)return;if(await A,t.timedOut||t.aborted||D)await T();try{await z.finalize()}catch(T4){b=T4 instanceof Error?T4:Error("Foreground command finalization failed")}let g=Date.now()-W,c=r();if(t.timedOut){J0({success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{...P(c,{command:$,sandboxed:Boolean(Y)}),timeout:!0,stdout:c.stdout,stderr:c.stderr,execution_time:g}});return}if(t.aborted){J0({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{...P(c,{command:$,sandboxed:Boolean(Y)}),aborted:!0,stdout:c.stdout,stderr:c.stderr,execution_time:g}});return}if(D){J0({success:!1,llmContent:"Command execution blocked before durable admission",error:{type:"execution_error",message:"Foreground command admission failed"},metadata:{...P(c,{command:$,sandboxed:Boolean(Y)}),admission_failed:!0,stdout:c.stdout,stderr:c.stderr,execution_time:g}});return}if(b){J0({success:!1,llmContent:"Command process group could not be finalized",error:{type:"execution_error",message:"Foreground command finalization failed"},metadata:{...P(c,{command:$,sandboxed:Boolean(Y)}),finalization_failed:!0,stdout:c.stdout,stderr:c.stderr,execution_time:g}});return}if(Y&&t1(I,c.snapshot.stderr.content)){J0({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:c.stderr||"Workspace sandbox failed to start"},metadata:{...P(c,{command:$}),sandbox_required:!0,sandboxed:!1,execution_time:g,exit_code:I,stdout:c.stdout,stderr:c.stderr,summary:"Workspace sandbox failed closed"}});return}let M$=$.length>30?`${$.substring(0,30)}...`:$,N0=I===0?`执行命令成功 (${g}ms): ${M$}`:`执行命令完成 (退出码 ${I}, ${g}ms): ${M$}`,d1={...P(c,{command:$}),command:$,execution_time:g,exit_code:I,signal:y,sandboxed:Boolean(Y),summary:N0},z5=$0(c,g,I,y),N4=I===0;J0({success:N4,llmContent:z5,...N4?{}:{error:{type:"execution_error",message:f8(I,y,c.stdout,c.stderr)}},metadata:d1})}),G.on("error",async(I)=>{let y=R();if(!y)return;if(await A,y.timedOut||y.aborted||D)await T();try{await z.finalize()}catch(c){b=c instanceof Error?c:Error("Foreground command finalization failed")}let t=r(),g=Date.now()-W;J0({success:!1,llmContent:y.timedOut?`Command execution timed out (${U}ms)`:y.aborted?"Command execution aborted by user":D?"Command execution blocked before durable admission":b?"Command process group could not be finalized":`Command execution failed: ${I.message}`,error:{type:y.timedOut?"timeout_error":"execution_error",message:y.timedOut?"命令执行超时":y.aborted?"操作被中止":D?"Foreground command admission failed":b?"Foreground command finalization failed":I.message,...y.timedOut||y.aborted||D||b?{}:{details:I}},metadata:P(t,{command:$,sandboxed:Boolean(Y),...y.timedOut?{timeout:!0}:y.aborted?{aborted:!0}:D?{admission_failed:!0}:b?{finalization_failed:!0}:{error:I.message},stdout:t.stdout,stderr:t.stderr,execution_time:g})})}),!X.aborted)A=z.release().catch(async(I)=>{D=I instanceof Error?I:Error("Command admission failed"),await T()})})}function yX($){return Object.fromEntries(["CI","COLORTERM","FORCE_COLOR","LANG","LANGUAGE","LC_ALL","LC_CTYPE","NO_COLOR","PATH","TERM","TZ"].flatMap((J)=>{let U=$[J];return U===void 0?[]:[[J,U]]}))}var _6=j({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:_.Object({shell_id:_.String({minLength:1,description:"Background Shell ID to terminate"})}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
614
614
|
- Kills a running background bash shell by its ID
|
|
615
615
|
- Takes a shell_id parameter identifying the shell to kill
|
|
616
616
|
- Returns a success or failure status
|
|
@@ -767,14 +767,14 @@ ${V.additionalContext}`};if(V.warning)console.warn(`[ToolExecutor] PostToolUseFa
|
|
|
767
767
|
`+` /model add
|
|
768
768
|
|
|
769
769
|
`+`或运行初始化向导:
|
|
770
|
-
`+" /init");let J=G0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");X0.getInstance().validateConfig(J);let X={...$};if(!X.toolWhitelist&&J.allowedTools?.length)X.toolWhitelist=J.allowedTools;if(!X.toolBlacklist&&J.disallowedTools?.length)X.toolBlacklist=J.disallowedTools;let Y=new j0(J,X);if(await Y.initialize(),X.toolWhitelist&&X.toolWhitelist.length>0)Y.applyToolWhitelist(X.toolWhitelist);if(X.toolBlacklist&&X.toolBlacklist.length>0)Y.applyToolBlacklist(X.toolBlacklist);return Y}static async createWithRuntime($,Z={}){let J=G0(),U={...Z};if(!U.toolWhitelist&&J?.allowedTools?.length)U.toolWhitelist=J.allowedTools;if(!U.toolBlacklist&&J?.disallowedTools?.length)U.toolBlacklist=J.disallowedTools;let X=new j0($.getConfig(),U,$.createToolExecutor(U),$);return await X.initialize(),X}async initialize(){if(this.isInitialized)return;try{if(this.log("初始化Agent..."),this.sessionRuntime){await this.initializeSystemPrompt(),await this.sessionRuntime.refresh(this.runtimeOptions),this.syncRuntimeState(),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`);return}await this.initializeSystemPrompt(),await this.loadSubagents(),await this.registerBuiltinTools();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"使用模型:"),this.attachmentCollector=new w1({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async*chatStream($,Z,J){let U=this.sessionRuntime;if(!U||!Z?.sessionId)return yield*this.chatStreamInternal($,Z,J);let X,Y=!1,H=!1,W=(Q)=>{if(!Y||!X)return;X.release(),X=void 0;try{U.publishTaskAdmissionCapacity(Q)}catch(O){u.warn("[Agent] Failed to publish task admission capacity:",O)}};try{if(U.isTaskSession?.()===!0){Y=J?.taskAdmission===void 0;let V=J?.taskAdmission??e$.admit({key:`${U.workspaceRoot}\x00${U.sessionId}`,...U.getTaskAdmissionLimits(),signal:Z.signal,onUpdate:(z)=>{U.setTaskAdmission(z).catch((B)=>{u.warn("[Agent] Failed to persist task admission update:",B)})}});try{X=await V.ready}catch(z){if(z instanceof C1||Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};throw z}if(Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,W("cancelled"),{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}}}await U.setTaskStatus("running");let Q=yield*this.chatStreamInternal($,Z,J),O=Z.signal?.aborted?"cancelled":Q.success?"completed":"failed";return await U.setTaskStatus(O,O==="failed"&&Q.error?Q.error:void 0),H=!0,W(O),Q}catch(Q){let O=Z.signal?.aborted?"cancelled":"failed";try{await U.setTaskStatus(O,Q)}catch(V){u.warn("[Agent] Failed to persist terminal task status:",V)}throw H=!0,W(O),Q}finally{if(!H)await U.setTaskStatus("interrupted","Task stream closed before completion").catch((Q)=>{u.warn("[Agent] Failed to persist interrupted task status:",Q)}),W("interrupted");if(Y)X?.release()}}async*chatStreamInternal($,Z,J){if(!this.isInitialized)throw Error("Agent未初始化");if(Z?.workspaceRoot)this.attachmentCollector?.setCwd(Z.workspaceRoot);let U=J?.pendingInputOnly===!0,X=J?.goalContinuationOnly===!0;if(U&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with pendingInputOnly");if(U&&X)throw Error("goalContinuationOnly cannot be combined with pendingInputOnly");if(X&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with goalContinuationOnly");if(!Z&&J?.preparedInputTurn)throw Error("preparedInputTurn requires a ChatContext");if(X&&(!Z||!this.sessionRuntime))throw Error("goalContinuationOnly requires a SessionRuntime and ChatContext");let Y=J?.outputSchema?W9(J.outputSchema).schema:void 0,H=J?.preparedInputTurn;if(Z&&this.sessionRuntime&&!U&&!X){if(!H){let B=Y?await this.sessionRuntime.prepareInputTurn($,{outputSchema:Y}):await this.sessionRuntime.prepareInputTurn($);if(!B.accepted)throw Error(B.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");H=B}}let W=$,Q=null;if(X){if(Q=await this.sessionRuntime.beginGoalContinuation(),!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};W=n5(Q)}else if(!U&&H?.mode!=="pending")try{W=await this.processAtMentionsForContent($)}catch(B){if(this.sessionRuntime&&H)await this.sessionRuntime.finishTurn(H.handle,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});throw B}else if(!Z||!this.sessionRuntime)W=await this.processAtMentionsForContent($);if(Z){let B=W,G=Z,K=U,E=X,q=E?void 0:Y,w=Q,F,D;if(this.sessionRuntime)if(E)D=await this.sessionRuntime.beginTurn("goal");else if(K)D=await this.sessionRuntime.beginPendingTurn();else{let C=H;if(D=C.handle,C.mode==="pending")K=!0,B="";else F=C.messageId}let b=0;if(K&&this.sessionRuntime&&!D)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let A=()=>this.sessionRuntime.getPendingSteeringMessages().map((C)=>({...C,persisted:G.messages.some((f)=>{let M=f.metadata;return M!==null&&typeof M==="object"&&!Array.isArray(M)&&M.inboxMessageId===C.id})})),L=()=>{let C=this.sessionRuntime.getPendingSteeringMessages().flatMap((M)=>M.outputSchema?[M.outputSchema]:[]);if(C.length<=1)return C[0];let f=JSON.stringify(C[0]);if(C.some((M)=>JSON.stringify(M)!==f))throw Error("Queued inputs contain conflicting structured output schemas");return C[0]};if(K&&this.sessionRuntime)q=L();let T=async(C)=>Promise.all(C.map(async(f)=>({...f,content:await this.processAtMentionsForContent(f.content)})));try{if(K&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};if(E&&w)yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w};while(!0){let C=D,f=w??await this.sessionRuntime?.getGoal()??null,M={...J,pendingInputOnly:K,goalContinuationOnly:void 0,preparedInputTurn:void 0,inputMessageId:K?void 0:F,transientInput:E?"goal_continuation":void 0,outputSchema:E?void 0:q,...this.sessionRuntime?{goalLifecycle:{snapshot:f,getSnapshot:()=>this.sessionRuntime.getGoal(),recordVerification:(P)=>this.sessionRuntime.recordGoalCompletionVerification(P),invalidateVerification:(P)=>this.sessionRuntime.invalidateGoalCompletionVerification(P),finalizeCompletion:()=>this.sessionRuntime.finalizeVerifiedGoalCompletion()}}:{},signal:G.signal,turnSteering:this.sessionRuntime&&C?{drain:async()=>T(await this.sessionRuntime.drainSteering(C)),drainOrSeal:async()=>{let P=await this.sessionRuntime.drainSteeringOrSeal(C);return{...P,messages:await T(P.messages)}}}:void 0,turnFinalization:this.sessionRuntime&&C?{turnId:C.id,getInputMessageIds:()=>this.sessionRuntime.getClaimedTurnMessageIds(C)}:void 0},R;if(G.permissionMode==="plan")R=yield*this.runPlanLoop(B,G,M);else R=yield*this.runLoop(B,G,M);if(R.success&&R.metadata?.targetMode&&G.permissionMode==="plan"){let P=R.metadata.targetMode,$0=R.metadata.planContent;if(u.debug(`Plan 模式已批准,切换到 ${P} 模式并重新执行`),this.sessionRuntime&&G.sessionId)await
|
|
770
|
+
`+" /init");let J=G0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");X0.getInstance().validateConfig(J);let X={...$};if(!X.toolWhitelist&&J.allowedTools?.length)X.toolWhitelist=J.allowedTools;if(!X.toolBlacklist&&J.disallowedTools?.length)X.toolBlacklist=J.disallowedTools;let Y=new j0(J,X);if(await Y.initialize(),X.toolWhitelist&&X.toolWhitelist.length>0)Y.applyToolWhitelist(X.toolWhitelist);if(X.toolBlacklist&&X.toolBlacklist.length>0)Y.applyToolBlacklist(X.toolBlacklist);return Y}static async createWithRuntime($,Z={}){let J=G0(),U={...Z};if(!U.toolWhitelist&&J?.allowedTools?.length)U.toolWhitelist=J.allowedTools;if(!U.toolBlacklist&&J?.disallowedTools?.length)U.toolBlacklist=J.disallowedTools;let X=new j0($.getConfig(),U,$.createToolExecutor(U),$);return await X.initialize(),X}async initialize(){if(this.isInitialized)return;try{if(this.log("初始化Agent..."),this.sessionRuntime){await this.initializeSystemPrompt(),await this.sessionRuntime.refresh(this.runtimeOptions),this.syncRuntimeState(),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`);return}await this.initializeSystemPrompt(),await this.loadSubagents(),await this.registerBuiltinTools();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"使用模型:"),this.attachmentCollector=new w1({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.toolExecutor.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async*chatStream($,Z,J){let U=this.sessionRuntime;if(!U||!Z?.sessionId)return yield*this.chatStreamInternal($,Z,J);let X,Y=!1,H=!1,W=(Q)=>{if(!Y||!X)return;X.release(),X=void 0;try{U.publishTaskAdmissionCapacity(Q)}catch(O){u.warn("[Agent] Failed to publish task admission capacity:",O)}};try{if(U.isTaskSession?.()===!0){Y=J?.taskAdmission===void 0;let V=J?.taskAdmission??e$.admit({key:`${U.workspaceRoot}\x00${U.sessionId}`,...U.getTaskAdmissionLimits(),signal:Z.signal,onUpdate:(z)=>{U.setTaskAdmission(z).catch((B)=>{u.warn("[Agent] Failed to persist task admission update:",B)})}});try{X=await V.ready}catch(z){if(z instanceof C1||Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};throw z}if(Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,W("cancelled"),{success:!1,error:{type:"aborted",message:"Task admission was cancelled"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}}}await U.setTaskStatus("running");let Q=yield*this.chatStreamInternal($,Z,J),O=Z.signal?.aborted?"cancelled":Q.success?"completed":"failed";return await U.setTaskStatus(O,O==="failed"&&Q.error?Q.error:void 0),H=!0,W(O),Q}catch(Q){let O=Z.signal?.aborted?"cancelled":"failed";try{await U.setTaskStatus(O,Q)}catch(V){u.warn("[Agent] Failed to persist terminal task status:",V)}throw H=!0,W(O),Q}finally{if(!H)await U.setTaskStatus("interrupted","Task stream closed before completion").catch((Q)=>{u.warn("[Agent] Failed to persist interrupted task status:",Q)}),W("interrupted");if(Y)X?.release()}}async*chatStreamInternal($,Z,J){if(!this.isInitialized)throw Error("Agent未初始化");if(Z?.workspaceRoot)this.attachmentCollector?.setCwd(Z.workspaceRoot);let U=J?.pendingInputOnly===!0,X=J?.goalContinuationOnly===!0;if(U&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with pendingInputOnly");if(U&&X)throw Error("goalContinuationOnly cannot be combined with pendingInputOnly");if(X&&J?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with goalContinuationOnly");if(!Z&&J?.preparedInputTurn)throw Error("preparedInputTurn requires a ChatContext");if(X&&(!Z||!this.sessionRuntime))throw Error("goalContinuationOnly requires a SessionRuntime and ChatContext");let Y=J?.outputSchema?W9(J.outputSchema).schema:void 0,H=J?.preparedInputTurn;if(Z&&this.sessionRuntime&&!U&&!X){if(!H){let B=Y?await this.sessionRuntime.prepareInputTurn($,{outputSchema:Y}):await this.sessionRuntime.prepareInputTurn($);if(!B.accepted)throw Error(B.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");H=B}}if(Z&&this.sessionRuntime&&(U||X||H?.mode==="pending")){let B=await this.sessionRuntime.loadModelContext();Z.messages.splice(0,Z.messages.length,...B)}let W=$,Q=null;if(X){if(Q=await this.sessionRuntime.beginGoalContinuation(),!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};W=n5(Q)}else if(!U&&H?.mode!=="pending")try{W=await this.processAtMentionsForContent($)}catch(B){if(this.sessionRuntime&&H)await this.sessionRuntime.finishTurn(H.handle,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});throw B}else if(!Z||!this.sessionRuntime)W=await this.processAtMentionsForContent($);if(Z){let B=W,G=Z,K=U,E=X,q=E?void 0:Y,w=Q,F,D;if(this.sessionRuntime)if(E)D=await this.sessionRuntime.beginTurn("goal");else if(K)D=await this.sessionRuntime.beginPendingTurn();else{let C=H;if(D=C.handle,C.mode==="pending")K=!0,B="";else F=C.messageId}let b=0;if(K&&this.sessionRuntime&&!D)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let A=()=>this.sessionRuntime.getPendingSteeringMessages().map((C)=>({...C,persisted:G.messages.some((f)=>{let M=f.metadata;return M!==null&&typeof M==="object"&&!Array.isArray(M)&&M.inboxMessageId===C.id})})),L=()=>{let C=this.sessionRuntime.getPendingSteeringMessages().flatMap((M)=>M.outputSchema?[M.outputSchema]:[]);if(C.length<=1)return C[0];let f=JSON.stringify(C[0]);if(C.some((M)=>JSON.stringify(M)!==f))throw Error("Queued inputs contain conflicting structured output schemas");return C[0]};if(K&&this.sessionRuntime)q=L();let T=async(C)=>Promise.all(C.map(async(f)=>({...f,content:await this.processAtMentionsForContent(f.content)})));try{if(K&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};if(E&&w)yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w};while(!0){let C=D,f=w??await this.sessionRuntime?.getGoal()??null,M={...J,pendingInputOnly:K,goalContinuationOnly:void 0,preparedInputTurn:void 0,inputMessageId:K?void 0:F,transientInput:E?"goal_continuation":void 0,outputSchema:E?void 0:q,...this.sessionRuntime?{goalLifecycle:{snapshot:f,getSnapshot:()=>this.sessionRuntime.getGoal(),recordVerification:(P)=>this.sessionRuntime.recordGoalCompletionVerification(P),invalidateVerification:(P)=>this.sessionRuntime.invalidateGoalCompletionVerification(P),finalizeCompletion:()=>this.sessionRuntime.finalizeVerifiedGoalCompletion()}}:{},signal:G.signal,turnSteering:this.sessionRuntime&&C?{drain:async()=>T(await this.sessionRuntime.drainSteering(C)),drainOrSeal:async()=>{let P=await this.sessionRuntime.drainSteeringOrSeal(C);return{...P,messages:await T(P.messages)}}}:void 0,turnFinalization:this.sessionRuntime&&C?{turnId:C.id,getInputMessageIds:()=>this.sessionRuntime.getClaimedTurnMessageIds(C)}:void 0},R;if(G.permissionMode==="plan")R=yield*this.runPlanLoop(B,G,M);else R=yield*this.runLoop(B,G,M);if(R.success&&R.metadata?.targetMode&&G.permissionMode==="plan"){let P=R.metadata.targetMode,$0=R.metadata.planContent;if(u.debug(`Plan 模式已批准,切换到 ${P} 模式并重新执行`),this.sessionRuntime&&G.sessionId)await n.setSessionPermissionMode(G.sessionId,this.sessionRuntime.workspaceRoot,P);await G.onPermissionModeChange?.(P),G={...G,permissionMode:P};let J0=B;if($0){let I=`
|
|
771
771
|
|
|
772
772
|
<approved-plan>
|
|
773
773
|
${$0}
|
|
774
774
|
</approved-plan>
|
|
775
775
|
|
|
776
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof B==="string")J0=B+I;else J0=[...B,{type:"text",text:I}]}R=yield*this.runLoop(J0,G,{...M,inputMessageId:void 0})}if(!this.sessionRuntime||!C)return R;let d=await this.sessionRuntime.recordGoalProgress({tokens:R.metadata?.tokensUsed??0,elapsedMs:R.metadata?.duration??0});if(d)yield{kind:"goal_updated",goal:d};if(!R.success||G.signal?.aborted){if(d=await this.sessionRuntime.pauseActiveGoal(G.signal?.aborted?"goal paused after user cancellation":R.error?.message??"goal paused after turn failure"),d)yield{kind:"goal_updated",goal:d}}let
|
|
777
|
-
`),V={id:this.generateTaskId(),type:"simple",prompt:O};return{success:!0,finalMessage:(await this.executeTask(V)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-
|
|
776
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof B==="string")J0=B+I;else J0=[...B,{type:"text",text:I}]}R=yield*this.runLoop(J0,G,{...M,inputMessageId:void 0})}if(!this.sessionRuntime||!C)return R;let d=await this.sessionRuntime.recordGoalProgress({tokens:R.metadata?.tokensUsed??0,elapsedMs:R.metadata?.duration??0});if(d)yield{kind:"goal_updated",goal:d};if(!R.success||G.signal?.aborted){if(d=await this.sessionRuntime.pauseActiveGoal(G.signal?.aborted?"goal paused after user cancellation":R.error?.message??"goal paused after turn failure"),d)yield{kind:"goal_updated",goal:d}}let r=R.success&&!G.signal?.aborted&&b<20;if(D=await this.sessionRuntime.finishTurn(C,{continuePending:r,outcome:R.success&&!G.signal?.aborted?{status:"completed",turnsCount:R.metadata?.turnsCount??0,toolCallsCount:R.metadata?.toolCallsCount??0,durationMs:R.metadata?.duration??0}:{status:"aborted",cause:G.signal?.aborted?"cancelled":"failed",turnsCount:R.metadata?.turnsCount??0,toolCallsCount:R.metadata?.toolCallsCount??0,durationMs:R.metadata?.duration??0}}),D){b++,K=!0,E=!1,w=null,B="",F=void 0,q=L(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:A()};continue}if(!R.success||G.signal?.aborted)return R;if(d=await this.sessionRuntime.getGoal(),!d||d.status!=="active"&&d.status!=="verifying")return R;if(w=await this.sessionRuntime.beginGoalContinuation(),!w)return R;D=await this.sessionRuntime.beginTurn("goal"),K=!1,E=!0,B=n5(w),F=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w}}}finally{if(this.sessionRuntime&&D)await this.sessionRuntime.finishTurn(D)}}let O=typeof W==="string"?W:W.filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
777
|
+
`),V={id:this.generateTaskId(),type:"simple",prompt:O};return{success:!0,finalMessage:(await this.executeTask(V)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-vz7hpwf0.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){u.debug("Processing Plan mode message...");let{prompt:U}=await v$({projectPath:Z.workspaceRoot||N(),mode:"plan",includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),X;if(typeof $==="string")X=q1($);else{let Y=$.filter((H)=>H.type==="text");if(Y.length>0){let H=Y[0];X=$.map((W)=>W===H?{type:"text",text:q1(H.text)}:W)}else X=[{type:"text",text:q1("")},...$]}return yield*this.executeLoop(X,Z,J,U)}async*runLoop($,Z,J){u.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||N());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await v$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,U){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return Q9(X,$,Z,J,U)}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,u.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,U)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,U):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),U=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of U)Z.unregister(X.name);u.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${U.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let U of Z.getAll())if(J.has(U.name))Z.unregister(U.name);u.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let U=Z.get(J.kind)||0;Z.set(J.kind,U+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){this.log("销毁Agent...");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){u.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){u.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await v$({projectPath:this.sessionRuntime?.workspaceRoot??N(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),u.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await S2({sessionId:"default",configDir:V9.join(O9.homedir(),".blade"),workspaceRoot:N(),resourceRoot:N(),agentResources:this.agentResources});u.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;u.debug(`Builtin tools registered: ${Z} tools`),u.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw u.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W2({workspaceRoot:N(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){u.debug("No MCP servers configured");return}let Z=x0.createIsolated({artifactWriter:new E1(`legacy-${GY()}`)});this.legacyMcpRegistry=Z;for(let[Y,H]of Object.entries($))try{u.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,H),u.debug(`MCP server "${Y}" connected`)}catch(W){u.warn(`Warning: MCP server "${Y}" connection failed:`,W)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(A1(Z));let X=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),Z.on("catalogChanged",(Y)=>{J.replaceMcpTools(Y.tools,Y)}),Z.on("contentCatalogChanged",(Y)=>{J.queueMcpContentChange(Y)}),Z.on("resourceUpdated",(Y)=>{J.queueMcpResourceUpdated(Y)}),Z.on("connectionLifecycleChanged",(Y)=>{J.queueMcpConnectionChange(Y)}),Z.on("log",(Y)=>{J.queueMcpLog(Y)}),Z.on("instructionsChanged",(Y)=>{J.queueMcpInstructionsChange({revision:Y.revision,reason:Y.reason,replace:!1,instructions:Y.action==="added"&&Y.instruction?[{serverName:Y.serverName,...Y.instruction}]:[],removed:Y.action==="removed"?[Y.serverName]:[]})}),U.tools.length>0)u.debug(`Registered ${U.tools.length} MCP tools`),u.debug(`[MCP Tools] ${U.tools.map((Y)=>Y.name).join(", ")}`)}catch($){u.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await Y0(N());if(this.agentResources=R2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)u.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else u.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;u.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((U)=>{return Z.some((X)=>{if(X===U.name)return!0;let Y=X.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===U.name)return!0;return!1})});return u.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)u.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let U of $)if(U.type==="text")Z.push(U.text);if(Z.length===0)return $;let J=Z.join(`
|
|
778
778
|
`);try{let U=await this.attachmentCollector.collect(J);if(U.length===0)return $;u.debug(`Processed ${U.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(U);if(!X)return $;return[...$,{type:"text",text:X}]}catch(U){return u.error("Failed to process @ mentions in multimodal message:",U),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let Y=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${Y?` range="${Y}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let U="";if(Z.length>0)U+=`
|
|
779
779
|
|
|
780
780
|
<system-reminder>
|
|
@@ -805,7 +805,7 @@ Warning: Some files could not be loaded:
|
|
|
805
805
|
`):G.stdout,E=/^Binary files .+ differ$/m.test(K)||K.includes("GIT binary patch"),q=E?{additions:0,deletions:0}:kY(K),w=q9(K,_9);return{path:z,patch:w.patch,...q,binary:E,truncated:w.truncated}})),Q=RY,O=Y.length>H.length,V=W.map((z)=>{let B=q9(z.patch,Q);return Q=Math.max(0,Q-Buffer.byteLength(B.patch)),O||=B.truncated,B.truncated?{...z,patch:B.patch,truncated:!0}:z});return{baseCommit:$.baseCommit,files:V,truncated:O}}async inspectChanges($){let[Z,J,U,X]=await Promise.all([x($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),x($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`]),x($.worktreeRoot,["diff","--numstat",$.baseCommit,"--"]),x($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(Z.code!==0||J.code!==0||U.code!==0||X.code!==0)return null;let Y=0,H=0;for(let W of U.stdout.split(`
|
|
806
806
|
`)){let[Q,O]=W.split("\t");if(/^\d+$/.test(Q??""))Y+=Number(Q);if(/^\d+$/.test(O??""))H+=Number(O)}for(let W of X.stdout.split("\x00").filter(Boolean))try{let Q=q0($.worktreeRoot,W),O=await h6(Q);if(!O.isFile()||O.size>10485760)continue;let V=await DY(Q);if(V.includes(0))continue;let z=V.toString("utf8");if(z.length>0)Y+=z.split(`
|
|
807
807
|
`).length-(z.endsWith(`
|
|
808
|
-
`)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...X.stdout.split("\x00").filter(Boolean)]).size,additions:Y,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var a0=new D9;function vY($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class b9{manager;constructor($=a0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:vY($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,U=await this.manager.getChangeSummary(J);if($.success&&this.isClean(U))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:U?.changedFiles,commits:U?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var D$=new b9;var Q0=l("Agent"),L9="Subagent execution was interrupted by a process restart. Durable progress was recovered; resume this agent to continue from the committed history.",xY="Subagent execution was interrupted by a process restart, and its durable history could not be validated. Resume is disabled for this run.",hY="Session was orphaned (process restart or timeout)",uY=1000;function dY($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}function gY($){if($.processId===void 0)return;if(!dY($.processId))return!1;return $.processIdentity?a1($.processId,$.processIdentity):!0}function A9($){return JSON.stringify($)}function mY($,Z){let J=Math.min($.length,Z.length);for(let U=J;U>0;U--){let X=$.length-U,Y=!0;for(let H=0;H<U;H++)if(A9($[X+H])!==A9(Z[H])){Y=!1;break}if(Y)return[...$,...Z.slice(U)]}return[...$,...Z]}function pY($){if(typeof $.content==="string")return $.content;return $.content.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join("")}function iY($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.role!=="assistant")continue;let U=pY(J).trim();if(U)return U}return""}class Z0{static instance=null;runningAgents=new Map;sessionStore=l0.getInstance();constructor(){}static getInstance(){if(!Z0.instance)Z0.instance=new Z0;return Z0.instance}async cleanupOrphanedSessions($){let Z=$?L2($):void 0,J=this.sessionStore.listSessions().filter((Y)=>!Z||A2(Y,Z)),U=Date.now(),X=1800000;for(let Y of J){let H=this.runningAgents.has(Y.id),W=gY(Y);if(!H&&W!==!0&&Y.status==="failed"&&Y.restartRecovery===void 0&&(Y.result?.error===hY||Y.result?.error===L9)){await this.reconcileOrphanedSession(Y);continue}if(Y.status==="running"){let Q=U-Y.lastActiveAt,O=Y.processId===void 0&&Q<=1800000;if(!H&&W===!1&&!O)Q0.warn(`Cleaning up orphaned agent session: ${Y.id}`),await this.reconcileOrphanedSession(Y);else if(!H&&W===void 0&&!O)await this.reconcileOrphanedSession(Y)}}}async reconcileOrphanedSession($){let Z=Date.now(),J=$.worktree?.workspaceRoot??$.workspaceRoot??$.parentProjectPath;if(!J){this.markRecoveryFailed($.id,Z);return}let U;try{U=await h2.acquire($.id,J)}catch(X){if(X instanceof x2)return;this.markRecoveryFailed($.id,Z);return}try{await new S$(J,$.id).reapOrphans(),await e.getInstance().reapOrphanedSession($.id,J);let X=new j2(J);await X.initialize(),await X.recoverInterruptedTurn($.id);let[Y,H]=await Promise.all([X.loadEvents($.id),r.loadSessionModelContext($.id,J)]);if(!Y){this.markRecoveryFailed($.id,Z);return}let W=mY($.messages,H),Q=N9(Y),O=Q.lastTerminal?.type==="turn_completed",V=O?iY(H):"",z=O&&V?"completed":"interrupted",B=Q.lastTerminal?.data,G=await this.reconcileOrphanedWorktree($,z==="completed");this.sessionStore.updateSession($.id,{status:z==="completed"?"completed":"failed",messages:W,result:{success:z==="completed",message:V,...z==="completed"?{}:{error:L9}},completedAt:Z,processId:void 0,processIdentity:void 0,worktree:G,restartRecovery:{outcome:z,recoveredAt:Z},...B?{stats:{toolCalls:B.toolCallsCount,duration:B.durationMs}}:{}})}catch(X){Q0.warn(`Failed to reconcile orphaned agent ${$.id}`,X),this.markRecoveryFailed($.id,Z)}finally{await U.release().catch((X)=>{Q0.warn(`Failed to release recovered agent lease ${$.id}`,X)})}}async reconcileOrphanedWorktree($,Z){if(!$.worktree)return;try{await yY($.worktree.worktreeRoot)}catch(J){if(J.code==="ENOENT")return;return Q0.warn(`Failed to inspect recovered worktree ${$.id}`,J),$.worktree}try{let J=await D$.prepare({agentId:$.id,sourceWorkspaceRoot:$.workspaceRoot??$.parentProjectPath??$.worktree.originalWorkspaceRoot,isolation:"worktree",restoredWorktree:$.worktree});return(await D$.finalize({agentId:$.id,lease:J,success:Z})).worktree}catch(J){return Q0.warn(`Failed to finalize recovered worktree ${$.id}`,J),$.worktree}}markRecoveryFailed($,Z){this.sessionStore.updateSession($,{status:"failed",result:{success:!1,message:"",error:xY},completedAt:Z,processId:void 0,processIdentity:void 0,restartRecovery:{outcome:"failed",recoveredAt:Z}})}async reconcileOrphanedSessions($){await this.cleanupOrphanedSessions($)}startBackgroundAgent($){let{config:Z,description:J,prompt:U,parentSessionId:X,parentProjectPath:Y,permissionMode:H,reasoningEffort:W,serviceTier:Q,responseVerbosity:O,communicationStyle:V,agentId:z,existingMessages:B,taskListId:G,workspaceRoot:K=N(),isolation:E=Z.isolation??"none",restoredWorktree:q,rootAgentId:w,resumedFrom:F,resumeDepth:D=0,agentResources:b,modelResources:A,lspResources:L,onEvent:T,onCompleted:C}=$,f=z||H$("agent");if(this.runningAgents.has(f)||this.sessionStore.loadSession(f))throw Error(`Subagent session already exists: ${f}`);let M=new AbortController,R={schemaVersion:2,id:f,subagentType:Z.name,description:J,prompt:U,messages:B||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,processIdentity:C$(process.pid),parentSessionId:X,parentProjectPath:Y,rootAgentId:w??f,resumedFrom:F,resumeDepth:D,configSnapshot:b2(Z),taskListId:G,workspaceRoot:K,isolation:E,worktree:q};this.sessionStore.saveSession(R);let d=Date.now(),n=this.executeAgent(f,Z,U,X,H,W,Q,O,V,M.signal,B,G,K,E,q,b,A,L,T,C);return this.runningAgents.set(f,{id:f,promise:n,abortController:M,startTime:d}),n.then(()=>this.runningAgents.delete(f),()=>this.runningAgents.delete(f)),Q0.info(`Background agent started: ${f} (${Z.name})`),f}async executeAgent($,Z,J,U,X,Y,H,W,Q,O,V,z,B=N(),G="none",K,E,q,w,F,D){let b=Date.now(),A,L,T,C=!1,f=async(M)=>{if(!T||C)return;let R=await D$.finalize({agentId:$,lease:T,success:M});return C=!0,this.sessionStore.updateSession($,{worktree:R.worktree}),R};try{if(O.aborted)throw Error("Agent execution was cancelled");T=await D$.prepare({agentId:$,sourceWorkspaceRoot:B,isolation:G,restoredWorktree:K}),this.sessionStore.updateSession($,{worktree:T.worktree});let M=Z.systemPrompt?.trim(),R=Z.model&&Z.model!=="inherit"?Z.model:void 0,d=Z.permissionMode??X,n=this.sessionStore.loadSession($);A=await b$.create({sessionId:$,workspaceRoot:T.workspaceRoot,modelId:R,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,agentResources:E,modelResources:q,lspResources:w,...(V?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:U?{parentSessionId:U,subagentType:Z.name,isSidechain:!1,resumedFrom:n?.resumedFrom,rootAgentId:n?.rootAgentId??$,resumeDepth:n?.resumeDepth??0}:void 0}),L=await j0.createWithRuntime(A,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:R,maxTurns:Z.maxTurns,permissionMode:d,...M?{appendSystemPrompt:M}:{}});let P={messages:V||[],userId:"subagent",sessionId:$,taskListId:z,workspaceRoot:T.workspaceRoot,worktreeActive:Boolean(T.worktree),permissionMode:d,subagentInfo:{parentSessionId:U||"",subagentType:Z.name,isSidechain:!1,resumedFrom:n?.resumedFrom,rootAgentId:n?.rootAgentId??$,resumeDepth:n?.resumeDepth??0}},$0=new Set,J0=new Set,I=b,y=await o0(L.chatStream(J,P,{signal:O,...Z.name===Z1?{outputSchema:k2}:s0(Z.name)?{outputSchema:v2}:{}}),async(N0)=>{let d1=Date.now();if(d1-I>=uY)this.sessionStore.updateSession($,{}),I=d1;if(N0.kind==="tool_result"&&"function"in N0.toolCall)g2(J0,N0.toolCall.function.name,N0.result,P.workspaceRoot),u2($0,N0.toolCall.function.name,N0.result,P.workspaceRoot);try{await F?.(N0,$)}catch(z5){Q0.warn(`Subagent event observer failed: ${$}`,z5)}});this.sessionStore.updateSession($,{messages:P.messages});let t=Date.now()-b,g=y.success?{success:!0,message:y.finalMessage||"",agentId:$,verificationCommands:[...$0],verificationVerdict:Z.name===Z1?I2(y.metadata?.structuredOutput):s0(Z.name)?y2(y.metadata?.structuredOutput)??d2(y.finalMessage):void 0,modifiedFiles:[...J0],stats:{tokens:y.metadata?.tokensUsed||0,toolCalls:y.metadata?.toolCallsCount||0,duration:t}}:{success:!1,message:"",agentId:$,error:y.error?.message||"Unknown error",stats:{duration:t}},c=await f(g.success);if(c?.preserved)g.worktreePath=c.worktreePath,g.worktreeBranch=c.worktreeBranch,g.worktree=c.worktree;let M$=this.sessionStore.markCompleted($,{success:g.success,message:g.message,error:g.error,verificationCommands:g.verificationCommands,verificationVerdict:g.verificationVerdict,modifiedFiles:g.modifiedFiles},g.stats);if(M$)try{await D?.(M$)}catch(N0){Q0.warn(`Subagent completion observer failed: ${$}`,N0)}return Q0.info(`Background agent completed: ${$} (success=${g.success})`),g}catch(M){let R=Date.now()-b,d=M instanceof Error?M.message:String(M),n;try{n=await f(!1)}catch($0){Q0.warn(`Failed to preserve worktree for background agent ${$}`,$0)}let P=this.sessionStore.markCompleted($,{success:!1,message:"",error:d},{duration:R});if(P)try{await D?.(P)}catch($0){Q0.warn(`Subagent completion observer failed: ${$}`,$0)}return Q0.warn(`Background agent failed: ${$}`,M),{success:!1,message:"",agentId:$,error:d,stats:{duration:R},worktreePath:n?.worktreePath,worktreeBranch:n?.worktreeBranch,worktree:n?.worktree}}finally{try{if(L&&typeof L.destroy==="function")await L.destroy()}finally{await A?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return A2(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let U=this.runningAgents.get($);if(!U)return this.getAgent($,J);if(Z>0){let X=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([U.promise,X])==="timeout")return this.getAgent($,J)}else await U.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:U,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,newAgentId:O=H$("agent"),agentResources:V,modelResources:z,lspResources:B,onEvent:G,onCompleted:K}=$,E=L2($.owner),q=this.getAgent(Z,E);if(!q){Q0.warn(`Cannot resume agent ${Z}: session not found`);return}if(q.subagentType!==U.name){Q0.warn(`Cannot resume agent ${Z}: requested type ${U.name} does not match ${q.subagentType}`);return}if(q.restartRecovery?.outcome==="failed"){Q0.warn(`Cannot resume agent ${Z}: restart recovery failed`);return}if(this.isRunning(Z)||q.status==="running"){Q0.warn(`Cannot resume agent ${Z}: still running`);return}if(O===Z){Q0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let w=q.configSnapshot?{...q.configSnapshot}:U;return{agentId:this.startBackgroundAgent({config:w,description:q.description,prompt:J,parentSessionId:E.sessionId,parentProjectPath:E.projectPath,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,agentId:O,existingMessages:q.messages,taskListId:q.taskListId,workspaceRoot:q.workspaceRoot,isolation:q.isolation,restoredWorktree:q.worktree,rootAgentId:q.rootAgentId,resumedFrom:q.id,resumeDepth:q.resumeDepth+1,agentResources:V,modelResources:z,lspResources:B,onEvent:G,onCompleted:K}),source:q}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let U=this.sessionStore.loadSession($);if(U&&U.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),Q0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:A2(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),U=0;for(let X of this.listForSession($)){if(X.status==="running")continue;if(J-X.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(X.id))U++}return U}}class u6{config;agentResources;modelResources;lspResources;constructor($,Z,J,U){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=U}async execute($){let Z=Date.now(),J=$.subagentSessionId??H$("agent"),U,X,Y;try{let H=this.getAppendSystemPrompt(),W=$.workspaceRoot||N(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:$.modelId,O=this.config.permissionMode??$.permissionMode,V={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};X=await b$.create({sessionId:J,workspaceRoot:W,modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:V,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),U=await j0.createWithRuntime(X,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:O,...H?{appendSystemPrompt:H}:{}});let z="",B=0,G=0,K=new Set,E=new Set;Y={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:W,completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:O,subagentInfo:V,signal:$.signal};let q=async(b)=>{if(b.kind==="tool_result"&&"function"in b.toolCall)g2(E,b.toolCall.function.name,b.result,W),u2(K,b.toolCall.function.name,b.result,W);await $.onEvent?.(b)},w=this.config.name===Z1?U.chatStream($.prompt,Y,{outputSchema:k2}):s0(this.config.name)?U.chatStream($.prompt,Y,{outputSchema:v2}):U.chatStream($.prompt,Y),F=await o0(w,q);if(F.success)z=F.finalMessage||"",B=F.metadata?.toolCallsCount||0,G=F.metadata?.tokensUsed||0;else throw Error(F.error?.message||"Subagent execution failed");let D=Date.now()-Z;return{success:!0,message:z,agentId:J,messages:Y.messages,verificationCommands:[...K],verificationVerdict:this.config.name===Z1?I2(F.metadata?.structuredOutput):s0(this.config.name)?y2(F.metadata?.structuredOutput)??d2(z):void 0,modifiedFiles:[...E],stats:{tokens:G,toolCalls:B,duration:D}}}catch(H){let W=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:Y?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:W}}}finally{if(U&&typeof U.destroy==="function")await U.destroy().catch(()=>{return});await X?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as L$}from"node:path";function d6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?L$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?L$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,U=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${U>0?` to ${U} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?L$(J):"file"}`}case"Bash":{let{command:J,description:U}=Z;if(U)return`${U}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:U}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(U){let Y=L$(U);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:U}=Z;return J?`Updating task ${U||""}: ${J}`.trim():`Updating task ${U||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?L$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:U}=Z,X=Z.resume_from||Z.resume;if(X)return`Resuming ${U||"agent"} from ${X}`;if(J)return`${U||"Agent"}: ${J}`;return`Running ${U||"agent"}`}case"LSP":{let{operation:J,filePath:U}=Z,X=U?L$(U):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?L$(J):"notebook"}`}default:return`${$}`}}function cY($,Z){if(!Z?.success&&!Z?.metadata&&$!=="Bash")return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function lY($,Z){if(!Z?.success&&$!=="Bash")return null;switch($){case"Glob":{if(!T9(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let U=5,X=J.slice(0,U).map((Y)=>Y.relative_path);if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
|
|
808
|
+
`)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...X.stdout.split("\x00").filter(Boolean)]).size,additions:Y,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var a0=new D9;function vY($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class b9{manager;constructor($=a0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:vY($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,U=await this.manager.getChangeSummary(J);if($.success&&this.isClean(U))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:U?.changedFiles,commits:U?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var D$=new b9;var Q0=l("Agent"),L9="Subagent execution was interrupted by a process restart. Durable progress was recovered; resume this agent to continue from the committed history.",xY="Subagent execution was interrupted by a process restart, and its durable history could not be validated. Resume is disabled for this run.",hY="Session was orphaned (process restart or timeout)",uY=1000;function dY($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}function gY($){if($.processId===void 0)return;if(!dY($.processId))return!1;return $.processIdentity?a1($.processId,$.processIdentity):!0}function A9($){return JSON.stringify($)}function mY($,Z){let J=Math.min($.length,Z.length);for(let U=J;U>0;U--){let X=$.length-U,Y=!0;for(let H=0;H<U;H++)if(A9($[X+H])!==A9(Z[H])){Y=!1;break}if(Y)return[...$,...Z.slice(U)]}return[...$,...Z]}function pY($){if(typeof $.content==="string")return $.content;return $.content.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join("")}function iY($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.role!=="assistant")continue;let U=pY(J).trim();if(U)return U}return""}class Z0{static instance=null;runningAgents=new Map;sessionStore=l0.getInstance();constructor(){}static getInstance(){if(!Z0.instance)Z0.instance=new Z0;return Z0.instance}async cleanupOrphanedSessions($){let Z=$?L2($):void 0,J=this.sessionStore.listSessions().filter((Y)=>!Z||A2(Y,Z)),U=Date.now(),X=1800000;for(let Y of J){let H=this.runningAgents.has(Y.id),W=gY(Y);if(!H&&W!==!0&&Y.status==="failed"&&Y.restartRecovery===void 0&&(Y.result?.error===hY||Y.result?.error===L9)){await this.reconcileOrphanedSession(Y);continue}if(Y.status==="running"){let Q=U-Y.lastActiveAt,O=Y.processId===void 0&&Q<=1800000;if(!H&&W===!1&&!O)Q0.warn(`Cleaning up orphaned agent session: ${Y.id}`),await this.reconcileOrphanedSession(Y);else if(!H&&W===void 0&&!O)await this.reconcileOrphanedSession(Y)}}}async reconcileOrphanedSession($){let Z=Date.now(),J=$.worktree?.workspaceRoot??$.workspaceRoot??$.parentProjectPath;if(!J){this.markRecoveryFailed($.id,Z);return}let U;try{U=await h2.acquire($.id,J)}catch(X){if(X instanceof x2)return;this.markRecoveryFailed($.id,Z);return}try{await new S$(J,$.id).reapOrphans(),await e.getInstance().reapOrphanedSession($.id,J);let X=new j2(J);await X.initialize(),await X.recoverInterruptedTurn($.id);let[Y,H]=await Promise.all([X.loadEvents($.id),n.loadSessionModelContext($.id,J)]);if(!Y){this.markRecoveryFailed($.id,Z);return}let W=mY($.messages,H),Q=N9(Y),O=Q.lastTerminal?.type==="turn_completed",V=O?iY(H):"",z=O&&V?"completed":"interrupted",B=Q.lastTerminal?.data,G=await this.reconcileOrphanedWorktree($,z==="completed");this.sessionStore.updateSession($.id,{status:z==="completed"?"completed":"failed",messages:W,result:{success:z==="completed",message:V,...z==="completed"?{}:{error:L9}},completedAt:Z,processId:void 0,processIdentity:void 0,worktree:G,restartRecovery:{outcome:z,recoveredAt:Z},...B?{stats:{toolCalls:B.toolCallsCount,duration:B.durationMs}}:{}})}catch(X){Q0.warn(`Failed to reconcile orphaned agent ${$.id}`,X),this.markRecoveryFailed($.id,Z)}finally{await U.release().catch((X)=>{Q0.warn(`Failed to release recovered agent lease ${$.id}`,X)})}}async reconcileOrphanedWorktree($,Z){if(!$.worktree)return;try{await yY($.worktree.worktreeRoot)}catch(J){if(J.code==="ENOENT")return;return Q0.warn(`Failed to inspect recovered worktree ${$.id}`,J),$.worktree}try{let J=await D$.prepare({agentId:$.id,sourceWorkspaceRoot:$.workspaceRoot??$.parentProjectPath??$.worktree.originalWorkspaceRoot,isolation:"worktree",restoredWorktree:$.worktree});return(await D$.finalize({agentId:$.id,lease:J,success:Z})).worktree}catch(J){return Q0.warn(`Failed to finalize recovered worktree ${$.id}`,J),$.worktree}}markRecoveryFailed($,Z){this.sessionStore.updateSession($,{status:"failed",result:{success:!1,message:"",error:xY},completedAt:Z,processId:void 0,processIdentity:void 0,restartRecovery:{outcome:"failed",recoveredAt:Z}})}async reconcileOrphanedSessions($){await this.cleanupOrphanedSessions($)}startBackgroundAgent($){let{config:Z,description:J,prompt:U,parentSessionId:X,parentProjectPath:Y,permissionMode:H,reasoningEffort:W,serviceTier:Q,responseVerbosity:O,communicationStyle:V,agentId:z,existingMessages:B,taskListId:G,workspaceRoot:K=N(),isolation:E=Z.isolation??"none",restoredWorktree:q,rootAgentId:w,resumedFrom:F,resumeDepth:D=0,agentResources:b,modelResources:A,lspResources:L,onEvent:T,onCompleted:C}=$,f=z||H$("agent");if(this.runningAgents.has(f)||this.sessionStore.loadSession(f))throw Error(`Subagent session already exists: ${f}`);let M=new AbortController,R={schemaVersion:2,id:f,subagentType:Z.name,description:J,prompt:U,messages:B||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,processIdentity:C$(process.pid),parentSessionId:X,parentProjectPath:Y,rootAgentId:w??f,resumedFrom:F,resumeDepth:D,configSnapshot:b2(Z),taskListId:G,workspaceRoot:K,isolation:E,worktree:q};this.sessionStore.saveSession(R);let d=Date.now(),r=this.executeAgent(f,Z,U,X,H,W,Q,O,V,M.signal,B,G,K,E,q,b,A,L,T,C);return this.runningAgents.set(f,{id:f,promise:r,abortController:M,startTime:d}),r.then(()=>this.runningAgents.delete(f),()=>this.runningAgents.delete(f)),Q0.info(`Background agent started: ${f} (${Z.name})`),f}async executeAgent($,Z,J,U,X,Y,H,W,Q,O,V,z,B=N(),G="none",K,E,q,w,F,D){let b=Date.now(),A,L,T,C=!1,f=async(M)=>{if(!T||C)return;let R=await D$.finalize({agentId:$,lease:T,success:M});return C=!0,this.sessionStore.updateSession($,{worktree:R.worktree}),R};try{if(O.aborted)throw Error("Agent execution was cancelled");T=await D$.prepare({agentId:$,sourceWorkspaceRoot:B,isolation:G,restoredWorktree:K}),this.sessionStore.updateSession($,{worktree:T.worktree});let M=Z.systemPrompt?.trim(),R=Z.model&&Z.model!=="inherit"?Z.model:void 0,d=Z.permissionMode??X,r=this.sessionStore.loadSession($);A=await b$.create({sessionId:$,workspaceRoot:T.workspaceRoot,modelId:R,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,agentResources:E,modelResources:q,lspResources:w,...(V?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:U?{parentSessionId:U,subagentType:Z.name,isSidechain:!1,resumedFrom:r?.resumedFrom,rootAgentId:r?.rootAgentId??$,resumeDepth:r?.resumeDepth??0}:void 0}),L=await j0.createWithRuntime(A,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:R,maxTurns:Z.maxTurns,permissionMode:d,...M?{appendSystemPrompt:M}:{}});let P={messages:V||[],userId:"subagent",sessionId:$,taskListId:z,workspaceRoot:T.workspaceRoot,worktreeActive:Boolean(T.worktree),permissionMode:d,subagentInfo:{parentSessionId:U||"",subagentType:Z.name,isSidechain:!1,resumedFrom:r?.resumedFrom,rootAgentId:r?.rootAgentId??$,resumeDepth:r?.resumeDepth??0}},$0=new Set,J0=new Set,I=b,y=await o0(L.chatStream(J,P,{signal:O,...Z.name===Z1?{outputSchema:k2}:s0(Z.name)?{outputSchema:v2}:{}}),async(N0)=>{let d1=Date.now();if(d1-I>=uY)this.sessionStore.updateSession($,{}),I=d1;if(N0.kind==="tool_result"&&"function"in N0.toolCall)g2(J0,N0.toolCall.function.name,N0.result,P.workspaceRoot),u2($0,N0.toolCall.function.name,N0.result,P.workspaceRoot);try{await F?.(N0,$)}catch(z5){Q0.warn(`Subagent event observer failed: ${$}`,z5)}});this.sessionStore.updateSession($,{messages:P.messages});let t=Date.now()-b,g=y.success?{success:!0,message:y.finalMessage||"",agentId:$,verificationCommands:[...$0],verificationVerdict:Z.name===Z1?I2(y.metadata?.structuredOutput):s0(Z.name)?y2(y.metadata?.structuredOutput)??d2(y.finalMessage):void 0,modifiedFiles:[...J0],stats:{tokens:y.metadata?.tokensUsed||0,toolCalls:y.metadata?.toolCallsCount||0,duration:t}}:{success:!1,message:"",agentId:$,error:y.error?.message||"Unknown error",stats:{duration:t}},c=await f(g.success);if(c?.preserved)g.worktreePath=c.worktreePath,g.worktreeBranch=c.worktreeBranch,g.worktree=c.worktree;let M$=this.sessionStore.markCompleted($,{success:g.success,message:g.message,error:g.error,verificationCommands:g.verificationCommands,verificationVerdict:g.verificationVerdict,modifiedFiles:g.modifiedFiles},g.stats);if(M$)try{await D?.(M$)}catch(N0){Q0.warn(`Subagent completion observer failed: ${$}`,N0)}return Q0.info(`Background agent completed: ${$} (success=${g.success})`),g}catch(M){let R=Date.now()-b,d=M instanceof Error?M.message:String(M),r;try{r=await f(!1)}catch($0){Q0.warn(`Failed to preserve worktree for background agent ${$}`,$0)}let P=this.sessionStore.markCompleted($,{success:!1,message:"",error:d},{duration:R});if(P)try{await D?.(P)}catch($0){Q0.warn(`Subagent completion observer failed: ${$}`,$0)}return Q0.warn(`Background agent failed: ${$}`,M),{success:!1,message:"",agentId:$,error:d,stats:{duration:R},worktreePath:r?.worktreePath,worktreeBranch:r?.worktreeBranch,worktree:r?.worktree}}finally{try{if(L&&typeof L.destroy==="function")await L.destroy()}finally{await A?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return A2(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let U=this.runningAgents.get($);if(!U)return this.getAgent($,J);if(Z>0){let X=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([U.promise,X])==="timeout")return this.getAgent($,J)}else await U.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:U,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,newAgentId:O=H$("agent"),agentResources:V,modelResources:z,lspResources:B,onEvent:G,onCompleted:K}=$,E=L2($.owner),q=this.getAgent(Z,E);if(!q){Q0.warn(`Cannot resume agent ${Z}: session not found`);return}if(q.subagentType!==U.name){Q0.warn(`Cannot resume agent ${Z}: requested type ${U.name} does not match ${q.subagentType}`);return}if(q.restartRecovery?.outcome==="failed"){Q0.warn(`Cannot resume agent ${Z}: restart recovery failed`);return}if(this.isRunning(Z)||q.status==="running"){Q0.warn(`Cannot resume agent ${Z}: still running`);return}if(O===Z){Q0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let w=q.configSnapshot?{...q.configSnapshot}:U;return{agentId:this.startBackgroundAgent({config:w,description:q.description,prompt:J,parentSessionId:E.sessionId,parentProjectPath:E.projectPath,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:W,communicationStyle:Q,agentId:O,existingMessages:q.messages,taskListId:q.taskListId,workspaceRoot:q.workspaceRoot,isolation:q.isolation,restoredWorktree:q.worktree,rootAgentId:q.rootAgentId,resumedFrom:q.id,resumeDepth:q.resumeDepth+1,agentResources:V,modelResources:z,lspResources:B,onEvent:G,onCompleted:K}),source:q}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let U=this.sessionStore.loadSession($);if(U&&U.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),Q0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:A2(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),U=0;for(let X of this.listForSession($)){if(X.status==="running")continue;if(J-X.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(X.id))U++}return U}}class u6{config;agentResources;modelResources;lspResources;constructor($,Z,J,U){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=U}async execute($){let Z=Date.now(),J=$.subagentSessionId??H$("agent"),U,X,Y;try{let H=this.getAppendSystemPrompt(),W=$.workspaceRoot||N(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:$.modelId,O=this.config.permissionMode??$.permissionMode,V={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};X=await b$.create({sessionId:J,workspaceRoot:W,modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:V,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),U=await j0.createWithRuntime(X,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:O,...H?{appendSystemPrompt:H}:{}});let z="",B=0,G=0,K=new Set,E=new Set;Y={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:W,completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:O,subagentInfo:V,signal:$.signal};let q=async(b)=>{if(b.kind==="tool_result"&&"function"in b.toolCall)g2(E,b.toolCall.function.name,b.result,W),u2(K,b.toolCall.function.name,b.result,W);await $.onEvent?.(b)},w=this.config.name===Z1?U.chatStream($.prompt,Y,{outputSchema:k2}):s0(this.config.name)?U.chatStream($.prompt,Y,{outputSchema:v2}):U.chatStream($.prompt,Y),F=await o0(w,q);if(F.success)z=F.finalMessage||"",B=F.metadata?.toolCallsCount||0,G=F.metadata?.tokensUsed||0;else throw Error(F.error?.message||"Subagent execution failed");let D=Date.now()-Z;return{success:!0,message:z,agentId:J,messages:Y.messages,verificationCommands:[...K],verificationVerdict:this.config.name===Z1?I2(F.metadata?.structuredOutput):s0(this.config.name)?y2(F.metadata?.structuredOutput)??d2(z):void 0,modifiedFiles:[...E],stats:{tokens:G,toolCalls:B,duration:D}}}catch(H){let W=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:Y?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:W}}}finally{if(U&&typeof U.destroy==="function")await U.destroy().catch(()=>{return});await X?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as L$}from"node:path";function d6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?L$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?L$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,U=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${U>0?` to ${U} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?L$(J):"file"}`}case"Bash":{let{command:J,description:U}=Z;if(U)return`${U}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:U}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(U){let Y=L$(U);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:U}=Z;return J?`Updating task ${U||""}: ${J}`.trim():`Updating task ${U||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?L$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:U}=Z,X=Z.resume_from||Z.resume;if(X)return`Resuming ${U||"agent"} from ${X}`;if(J)return`${U||"Agent"}: ${J}`;return`Running ${U||"agent"}`}case"LSP":{let{operation:J,filePath:U}=Z,X=U?L$(U):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?L$(J):"notebook"}`}default:return`${$}`}}function cY($,Z){if(!Z?.success&&!Z?.metadata&&$!=="Bash")return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function lY($,Z){if(!Z?.success&&$!=="Bash")return null;switch($){case"Glob":{if(!T9(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let U=5,X=J.slice(0,U).map((Y)=>Y.relative_path);if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
|
|
809
809
|
`)}case"Grep":{let J=Z.llmContent;if(!Array.isArray(J)||!J.length)return null;let U=5,X=J.slice(0,U).map((Y)=>{let H=L$(Y.file_path);if(Y.line_number)return`${H}:${Y.line_number}`;return H});if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
|
|
810
810
|
`)}case"Read":{let J=Z.metadata?.content_preview||Z.llmContent;if(typeof J!=="string"||!J)return null;let U=J.split(`
|
|
811
811
|
`),X=U.length,Y=3;if(X<=Y+1)return J;return`${U.slice(0,Y).join(`
|
|
@@ -866,7 +866,7 @@ Usage notes:
|
|
|
866
866
|
- Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
|
|
867
867
|
- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
|
|
868
868
|
- If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.
|
|
869
|
-
`.trim()}function p2($=N$(),Z,J,U,X,Y,H,W){return j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(Q)=>rY($,Q),(Q)=>`Invalid subagent type: "${Q}". Available: ${aY($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(i(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return sY($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(Q,O){let{subagent_type:V,description:z,prompt:B,run_in_background:G=!1,isolation:K,resume:E,resume_from:q,subagent_session_id:w}=Q,F=q??E,D=tY(O);if(!D)return A$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let b=X?.(),A=Y?.(),L=H?.(),T=W?.(),C=Z0.getInstance(),f=F?C.getAgent(F,D):void 0;if(F&&!f)return A$(`Cannot resume agent ${F}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${F}`);if(f&&(C.isRunning(f.id)||f.status==="running"))return A$(`Cannot resume agent ${f.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${f.id}`);if(f&&V&&f.subagentType!==V)return A$(`Cannot resume with subagent_type "${V}": source agent used "${f.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let M=f?.subagentType??V;if(!M)return A$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let R=$.getSubagent(M),n=(f?.configSnapshot?{...f.configSnapshot}:void 0)??R;if(!n)return A$(`Unknown subagent type: ${M}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${M}`);let P={...n,model:n.model&&n.model!=="inherit"?n.model:O.modelId??n.model,permissionMode:n.permissionMode??O.permissionMode},$0=typeof w==="string"&&w.length>0?w:H$("agent"),J0=f?.isolation??K??P.isolation??"none",I=f?.rootAgentId??$0,y=f?f.resumeDepth+1:0,t=eY({owner:D,subagentSessionId:$0,type:P.name,description:z,resumedFrom:f?.id,rootAgentId:I,resumeDepth:y});if(G){let g=f?C.resumeAgent({agentId:f.id,prompt:B,config:P,owner:D,permissionMode:O.permissionMode,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T,newAgentId:$0,agentResources:Z,modelResources:J,lspResources:U,onEvent:t.onEvent,onCompleted:t.onCompleted})?.agentId:C.startBackgroundAgent({config:P,description:z,prompt:B,parentSessionId:D.sessionId,parentProjectPath:D.projectPath,permissionMode:O.permissionMode,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T,agentId:$0,workspaceRoot:D.projectPath,isolation:J0,agentResources:Z,modelResources:J,lspResources:U,onEvent:t.onEvent,onCompleted:t.onCompleted});if(!g)return A$(`Failed to resume agent ${f?.id??$0}`,"恢复 Agent 失败");return t.onStarted(),ZH({sessionId:g,config:P,description:z,isolation:J0,resumedFrom:f?.id,rootAgentId:I,resumeDepth:y})}return $H({config:P,description:z,prompt:B,context:O,owner:D,subagentSessionId:$0,isolation:J0,source:f,eventBridge:t,agentResources:Z,modelResources:J,lspResources:U,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(Q)=>`${Q.subagent_type||"resume"}:${Q.resume_from||Q.resume||""}:${Q.description}`,abstractPermissionRule:()=>""})}var oY=p2(S9);function tY($){if(!$.sessionId)return;let Z=$.workspaceRoot||N();if(!C9.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:C9.resolve(Z)}}function A$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function eY($){let Z=nY(8),J=!1,U={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{m2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),_0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...U})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let Y=X.toolCall,H="function"in Y?Y.function.name:"Unknown";if(m2.getState().app.actions.updateSubagentTool(Z,H),_0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in Y)_0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:H,arguments:Y.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let Y=X.toolCall;if(!("function"in Y))break;_0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:M9(j9(Y.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let Y=X.toolCall;if(!("function"in Y))break;_0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,...X.update});break}case"content_delta":_0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":_0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":_0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(X)=>{if(J)return;J=!0,m2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed"),_0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:X.result?.message?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...U})}}}async function $H($){let{config:Z,description:J,prompt:U,context:X,owner:Y,subagentSessionId:H,isolation:W,source:Q,eventBridge:O,agentResources:V,modelResources:z,lspResources:B}=$,G=l0.getInstance(),K=Q?.workspaceRoot??Y.projectPath,E=Q?.rootAgentId??H,q=Q?Q.resumeDepth+1:0,w,F=!1,D=!1,b=async(A)=>{if(!w||F)return;let L=await D$.finalize({agentId:H,lease:w,success:A});return F=!0,L};try{w=await D$.prepare({agentId:H,sourceWorkspaceRoot:K,isolation:W,restoredWorktree:Q?.worktree});let A=Date.now();G.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:U,messages:[...Q?.messages??[]],status:"running",createdAt:A,lastActiveAt:A,processId:process.pid,processIdentity:C$(process.pid),parentSessionId:Y.sessionId,parentProjectPath:Y.projectPath,rootAgentId:E,resumedFrom:Q?.id,resumeDepth:q,configSnapshot:b2(Z),workspaceRoot:K,isolation:W,worktree:w.worktree}),D=!0,O.onStarted(),X.updateOutput?.(`${Q?"恢复":"启动"} ${Z.name} subagent: ${J}`);let L=new u6(Z,V,z,B),T={prompt:U,parentSessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:Q?.id,rootAgentId:E,resumeDepth:q,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),existingMessages:Q?.messages,onEvent:O.onEvent},C=Date.now(),f=await L.execute(T);try{let d=await b0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:w.workspaceRoot,sessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:f.success,resultSummary:f.message.slice(0,500),error:f.error});if(!d.shouldStop&&d.continueReason)f=await L.execute({...T,prompt:d.continueReason,existingMessages:f.messages});if(d.warning)console.warn(`[Task] SubagentStop hook warning: ${d.warning}`)}catch(d){console.warn("[Task] SubagentStop hook execution failed:",d)}let M=await b(f.success);if(M?.preserved)f.worktreePath=M.worktreePath,f.worktreeBranch=M.worktreeBranch,f.worktree=M.worktree;G.updateSession(H,{messages:f.messages??[],worktree:M?.worktree});let R=G.markCompleted(H,{success:f.success,message:f.message,error:f.error,verificationCommands:f.verificationCommands,verificationVerdict:f.verificationVerdict,modifiedFiles:f.modifiedFiles},{...f.stats,duration:Date.now()-C});if(R)O.onCompleted(R);return JH({result:f,sessionId:H,config:Z,description:J,isolation:W,resumedFrom:Q?.id,rootAgentId:E,resumeDepth:q})}catch(A){let L=A,T;try{T=await b(!1)}catch(C){console.warn("[Task] Failed to preserve subagent worktree:",C)}if(D){let C=G.markCompleted(H,{success:!1,message:"",error:L.message});if(C)O.onCompleted(C)}return{...A$(`Subagent execution error: ${L.message}`,`Subagent 执行异常: ${R9(L)}`),metadata:{summary:`Subagent 执行异常: ${R9(L)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:Q?.id,subagentRootId:E,subagentResumeDepth:q,isolation:W,worktreePath:T?.worktreePath,worktreeBranch:T?.worktreeBranch}}}}function ZH($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function JH($){let Z=$.result.worktreePath?`
|
|
869
|
+
`.trim()}function p2($=N$(),Z,J,U,X,Y,H,W){return j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(Q)=>rY($,Q),(Q)=>`Invalid subagent type: "${Q}". Available: ${aY($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(i(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return sY($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(Q,O){let{subagent_type:V,description:z,prompt:B,run_in_background:G=!1,isolation:K,resume:E,resume_from:q,subagent_session_id:w}=Q,F=q??E,D=tY(O);if(!D)return A$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let b=X?.(),A=Y?.(),L=H?.(),T=W?.(),C=Z0.getInstance(),f=F?C.getAgent(F,D):void 0;if(F&&!f)return A$(`Cannot resume agent ${F}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${F}`);if(f&&(C.isRunning(f.id)||f.status==="running"))return A$(`Cannot resume agent ${f.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${f.id}`);if(f&&V&&f.subagentType!==V)return A$(`Cannot resume with subagent_type "${V}": source agent used "${f.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let M=f?.subagentType??V;if(!M)return A$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let R=$.getSubagent(M),r=(f?.configSnapshot?{...f.configSnapshot}:void 0)??R;if(!r)return A$(`Unknown subagent type: ${M}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${M}`);let P={...r,model:r.model&&r.model!=="inherit"?r.model:O.modelId??r.model,permissionMode:r.permissionMode??O.permissionMode},$0=typeof w==="string"&&w.length>0?w:H$("agent"),J0=f?.isolation??K??P.isolation??"none",I=f?.rootAgentId??$0,y=f?f.resumeDepth+1:0,t=eY({owner:D,subagentSessionId:$0,type:P.name,description:z,resumedFrom:f?.id,rootAgentId:I,resumeDepth:y});if(G){let g=f?C.resumeAgent({agentId:f.id,prompt:B,config:P,owner:D,permissionMode:O.permissionMode,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T,newAgentId:$0,agentResources:Z,modelResources:J,lspResources:U,onEvent:t.onEvent,onCompleted:t.onCompleted})?.agentId:C.startBackgroundAgent({config:P,description:z,prompt:B,parentSessionId:D.sessionId,parentProjectPath:D.projectPath,permissionMode:O.permissionMode,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T,agentId:$0,workspaceRoot:D.projectPath,isolation:J0,agentResources:Z,modelResources:J,lspResources:U,onEvent:t.onEvent,onCompleted:t.onCompleted});if(!g)return A$(`Failed to resume agent ${f?.id??$0}`,"恢复 Agent 失败");return t.onStarted(),ZH({sessionId:g,config:P,description:z,isolation:J0,resumedFrom:f?.id,rootAgentId:I,resumeDepth:y})}return $H({config:P,description:z,prompt:B,context:O,owner:D,subagentSessionId:$0,isolation:J0,source:f,eventBridge:t,agentResources:Z,modelResources:J,lspResources:U,reasoningEffort:b,serviceTier:A,responseVerbosity:L,communicationStyle:T})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(Q)=>`${Q.subagent_type||"resume"}:${Q.resume_from||Q.resume||""}:${Q.description}`,abstractPermissionRule:()=>""})}var oY=p2(S9);function tY($){if(!$.sessionId)return;let Z=$.workspaceRoot||N();if(!C9.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:C9.resolve(Z)}}function A$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function eY($){let Z=nY(8),J=!1,U={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{m2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),_0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...U})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let Y=X.toolCall,H="function"in Y?Y.function.name:"Unknown";if(m2.getState().app.actions.updateSubagentTool(Z,H),_0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in Y)_0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:H,arguments:Y.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let Y=X.toolCall;if(!("function"in Y))break;_0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:M9(j9(Y.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let Y=X.toolCall;if(!("function"in Y))break;_0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,...X.update});break}case"content_delta":_0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":_0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":_0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(X)=>{if(J)return;J=!0,m2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed"),_0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:X.result?.message?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...U})}}}async function $H($){let{config:Z,description:J,prompt:U,context:X,owner:Y,subagentSessionId:H,isolation:W,source:Q,eventBridge:O,agentResources:V,modelResources:z,lspResources:B}=$,G=l0.getInstance(),K=Q?.workspaceRoot??Y.projectPath,E=Q?.rootAgentId??H,q=Q?Q.resumeDepth+1:0,w,F=!1,D=!1,b=async(A)=>{if(!w||F)return;let L=await D$.finalize({agentId:H,lease:w,success:A});return F=!0,L};try{w=await D$.prepare({agentId:H,sourceWorkspaceRoot:K,isolation:W,restoredWorktree:Q?.worktree});let A=Date.now();G.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:U,messages:[...Q?.messages??[]],status:"running",createdAt:A,lastActiveAt:A,processId:process.pid,processIdentity:C$(process.pid),parentSessionId:Y.sessionId,parentProjectPath:Y.projectPath,rootAgentId:E,resumedFrom:Q?.id,resumeDepth:q,configSnapshot:b2(Z),workspaceRoot:K,isolation:W,worktree:w.worktree}),D=!0,O.onStarted(),X.updateOutput?.(`${Q?"恢复":"启动"} ${Z.name} subagent: ${J}`);let L=new u6(Z,V,z,B),T={prompt:U,parentSessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:Q?.id,rootAgentId:E,resumeDepth:q,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),existingMessages:Q?.messages,onEvent:O.onEvent},C=Date.now(),f=await L.execute(T);try{let d=await b0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:w.workspaceRoot,sessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:f.success,resultSummary:f.message.slice(0,500),error:f.error});if(!d.shouldStop&&d.continueReason)f=await L.execute({...T,prompt:d.continueReason,existingMessages:f.messages});if(d.warning)console.warn(`[Task] SubagentStop hook warning: ${d.warning}`)}catch(d){console.warn("[Task] SubagentStop hook execution failed:",d)}let M=await b(f.success);if(M?.preserved)f.worktreePath=M.worktreePath,f.worktreeBranch=M.worktreeBranch,f.worktree=M.worktree;G.updateSession(H,{messages:f.messages??[],worktree:M?.worktree});let R=G.markCompleted(H,{success:f.success,message:f.message,error:f.error,verificationCommands:f.verificationCommands,verificationVerdict:f.verificationVerdict,modifiedFiles:f.modifiedFiles},{...f.stats,duration:Date.now()-C});if(R)O.onCompleted(R);return JH({result:f,sessionId:H,config:Z,description:J,isolation:W,resumedFrom:Q?.id,rootAgentId:E,resumeDepth:q})}catch(A){let L=A,T;try{T=await b(!1)}catch(C){console.warn("[Task] Failed to preserve subagent worktree:",C)}if(D){let C=G.markCompleted(H,{success:!1,message:"",error:L.message});if(C)O.onCompleted(C)}return{...A$(`Subagent execution error: ${L.message}`,`Subagent 执行异常: ${R9(L)}`),metadata:{summary:`Subagent 执行异常: ${R9(L)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:Q?.id,subagentRootId:E,subagentResumeDepth:q,isolation:W,worktreePath:T?.worktreePath,worktreeBranch:T?.worktreeBranch}}}}function ZH($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function JH($){let Z=$.result.worktreePath?`
|
|
870
870
|
|
|
871
871
|
Worktree preserved at ${$.result.worktreePath}${$.result.worktreeBranch?` on branch ${$.result.worktreeBranch}`:""}.`:"",J=`
|
|
872
872
|
|
|
@@ -1018,13 +1018,13 @@ ${W.slice(0,t6).join(`
|
|
|
1018
1018
|
**Auto-Verify: issues after ${Y.length===1?W$.basename(Y[0]):`${Y.length} patched files`}:**
|
|
1019
1019
|
\`\`\`
|
|
1020
1020
|
${O}
|
|
1021
|
-
\`\`\``,UJ.info(`[AutoVerify] injected type diagnostics (${Y.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??U0(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await P0.getInstance().getStatus(this.options.projectRoot)).state==="trusted"}runOwnedCommand($,Z,J,U,X){if(this.disposed||X?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:1,timedOut:!1});let{child:Y,processTree:H}=n$($,Z,{cwd:J,env:{...this.options.environment,PATH:this.options.environment.PATH??process.env.PATH??"",HOME:this.options.environment.HOME??process.env.HOME??"",USER:this.options.environment.USER??process.env.USER??"",SHELL:this.options.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1",BLADE_SESSION_ID:this.options.sessionId},stdio:["ignore","pipe","pipe"]}),W,Q=new Promise((V)=>{W=V}),O={processTree:H,settled:Q};return this.activeCommands.add(O),new Promise((V,z)=>{let B="",G="",K=!1,E=!1,q,w=()=>{return q??=H.terminate(),q};Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(A)=>{B=YJ(B,A)}),Y.stderr?.on("data",(A)=>{G=YJ(G,A)});let F=()=>{clearTimeout(b),X?.removeEventListener("abort",D),this.disposeController.signal.removeEventListener("abort",D),this.activeCommands.delete(O),W()},D=()=>{w()},b=setTimeout(()=>{K=!0,w()},U);if(X?.addEventListener("abort",D,{once:!0}),this.disposeController.signal.addEventListener("abort",D,{once:!0}),X?.aborted||this.disposeController.signal.aborted)D();Y.once("error",(A)=>{if(E)return;E=!0,F(),z(A)}),Y.once("close",async(A)=>{if(E)return;if(E=!0,K||X?.aborted||this.disposeController.signal.aborted)await w();F(),V({stdout:B,stderr:G,exitCode:A??1,timedOut:K})})})}}import{Mutex as zW}from"async-mutex";import{nanoid as HJ}from"nanoid";var BW=20,_W=OJ+VJ;function WJ($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}function QJ($){return $?Buffer.byteLength(JSON.stringify($)):0}class I1{inbox;transitionMutex=new zW;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new I1(await zJ.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let J=this.inbox.count()>0,U=await this.enqueueDurably($,"next_turn",Z);if(!U.accepted||!U.messageId)return{accepted:!1,queued:U.queued,reason:"queue_full"};let X=this.createTurn();if(!J){let Y=this.inbox.list().find((H)=>H.id===U.messageId);if(!Y)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${U.messageId}`);this.claimed.set(Y.id,Y)}return{accepted:!0,handle:X,messageId:U.messageId,queued:U.queued,mode:J?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let U={id:J.messageId??HJ(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{},...J.outputSchema?{outputSchema:J.outputSchema}:{}};if(!await this.inbox.enqueue(U,(Y)=>{if(Y.length>=BW)return!1;let H=Y.reduce((Q,O)=>Q+WJ(O.content),0),W=Y.reduce((Q,O)=>Q+QJ(O.outputSchema),0);return H+W+WJ($)+QJ(J.outputSchema)<=_W}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:U.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:HJ(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var A0=l("Agent"),BJ=new Map;async function qW($){let Z=BJ.get($);if(!Z)Z=(async()=>{try{let J=await a0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)A0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)A0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){A0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),BJ.set($,Z);await Z}class b${config;options;approvalStore=new T1;baseRegistry=new F$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new KW;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new KJ(EJ().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:O0.resolve(Z.workspaceRoot??N()),config:FJ($),catalog:J}}this.lspResources=K1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new S0(this.workspaceRoot,this.sessionId),this.attachmentCollector=new w1({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){let Z=$.workspaceRoot??N(),J=$.taskWorktree,U=$.taskIsolation,X=$.modelId,Y=$.permissionMode,H=$.reasoningEffort,W=$.serviceTier,Q=$.responseVerbosity,O=$.communicationStyle,V=$.communicationStyleDigest,z=$.projectInstructionsDigest,B=X!==void 0,G=O!==void 0;try{await M2();let K=await
|
|
1021
|
+
\`\`\``,UJ.info(`[AutoVerify] injected type diagnostics (${Y.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??U0(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await P0.getInstance().getStatus(this.options.projectRoot)).state==="trusted"}runOwnedCommand($,Z,J,U,X){if(this.disposed||X?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:1,timedOut:!1});let{child:Y,processTree:H}=n$($,Z,{cwd:J,env:{...this.options.environment,PATH:this.options.environment.PATH??process.env.PATH??"",HOME:this.options.environment.HOME??process.env.HOME??"",USER:this.options.environment.USER??process.env.USER??"",SHELL:this.options.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1",BLADE_SESSION_ID:this.options.sessionId},stdio:["ignore","pipe","pipe"]}),W,Q=new Promise((V)=>{W=V}),O={processTree:H,settled:Q};return this.activeCommands.add(O),new Promise((V,z)=>{let B="",G="",K=!1,E=!1,q,w=()=>{return q??=H.terminate(),q};Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(A)=>{B=YJ(B,A)}),Y.stderr?.on("data",(A)=>{G=YJ(G,A)});let F=()=>{clearTimeout(b),X?.removeEventListener("abort",D),this.disposeController.signal.removeEventListener("abort",D),this.activeCommands.delete(O),W()},D=()=>{w()},b=setTimeout(()=>{K=!0,w()},U);if(X?.addEventListener("abort",D,{once:!0}),this.disposeController.signal.addEventListener("abort",D,{once:!0}),X?.aborted||this.disposeController.signal.aborted)D();Y.once("error",(A)=>{if(E)return;E=!0,F(),z(A)}),Y.once("close",async(A)=>{if(E)return;if(E=!0,K||X?.aborted||this.disposeController.signal.aborted)await w();F(),V({stdout:B,stderr:G,exitCode:A??1,timedOut:K})})})}}import{Mutex as zW}from"async-mutex";import{nanoid as HJ}from"nanoid";var BW=20,_W=OJ+VJ;function WJ($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}function QJ($){return $?Buffer.byteLength(JSON.stringify($)):0}class I1{inbox;transitionMutex=new zW;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new I1(await zJ.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let J=this.inbox.count()>0,U=await this.enqueueDurably($,"next_turn",Z);if(!U.accepted||!U.messageId)return{accepted:!1,queued:U.queued,reason:"queue_full"};let X=this.createTurn();if(!J){let Y=this.inbox.list().find((H)=>H.id===U.messageId);if(!Y)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${U.messageId}`);this.claimed.set(Y.id,Y)}return{accepted:!0,handle:X,messageId:U.messageId,queued:U.queued,mode:J?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let U={id:J.messageId??HJ(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{},...J.outputSchema?{outputSchema:J.outputSchema}:{}};if(!await this.inbox.enqueue(U,(Y)=>{if(Y.length>=BW)return!1;let H=Y.reduce((Q,O)=>Q+WJ(O.content),0),W=Y.reduce((Q,O)=>Q+QJ(O.outputSchema),0);return H+W+WJ($)+QJ(J.outputSchema)<=_W}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:U.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:HJ(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var A0=l("Agent"),BJ=new Map;async function qW($){let Z=BJ.get($);if(!Z)Z=(async()=>{try{let J=await a0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)A0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)A0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){A0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),BJ.set($,Z);await Z}class b${config;options;approvalStore=new T1;baseRegistry=new F$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new KW;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new KJ(EJ().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:O0.resolve(Z.workspaceRoot??N()),config:FJ($),catalog:J}}this.lspResources=K1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new S0(this.workspaceRoot,this.sessionId),this.attachmentCollector=new w1({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){let Z=$.workspaceRoot??N(),J=$.taskWorktree,U=$.taskIsolation,X=$.modelId,Y=$.permissionMode,H=$.reasoningEffort,W=$.serviceTier,Q=$.responseVerbosity,O=$.communicationStyle,V=$.communicationStyleDigest,z=$.projectInstructionsDigest,B=X!==void 0,G=O!==void 0;try{await M2();let K=await n.findSessionMetadata($.sessionId,Z);if(K?.archivedAt)throw new fJ($.sessionId,K.archivedBySessionId??$.sessionId);if(Y??=K?.permissionMode,H??=K?.reasoningEffort??"off",W??=K?.serviceTier??"auto",Q??=K?.responseVerbosity??"auto",O??=K?.communicationStyle??"auto",!G||O===K?.communicationStyle)V??=K?.communicationStyleDigest;if(z??=K?.projectInstructionsDigest,!$.subagentInfo&&(!J||!U||!X)){let C=await(J?Promise.resolve(void 0):n.findSessionTaskWorktree($.sessionId,Z));J??=C,U??=K?.taskIsolation,X??=K?.selectedModelId??K?.taskModelId}if(J){if(O0.resolve(J.workspaceRoot)!==O0.resolve(Z))throw Error("Task worktree workspace does not match runtime workspace");await a0.restoreSession(J)}let E=G0();if(!E)throw Error("配置未初始化,请确保应用已正确启动");e$.configure(E.maxConcurrentTasks,E.maxQueuedTasks);let q=X0.getInstance(),w=$.modelResources?.projectRoot??$.lspResources?.projectRoot??$.agentResources?.projectRoot??J?.originalWorkspaceRoot??Z,F=$.modelResources?DJ($.modelResources):await wJ(w,E),D=F.config.models,b=$.lspResources?K1($.lspResources):await o4(w,F.config.lspServers);if(D.length===0)throw Error(`没有可用的模型配置
|
|
1022
1022
|
|
|
1023
1023
|
`+`请先使用以下命令添加模型:
|
|
1024
1024
|
`+` /model add
|
|
1025
1025
|
|
|
1026
1026
|
`+`或运行初始化向导:
|
|
1027
|
-
`+" /init");if(!B&&X&&X!=="inherit"&&!D.some((C)=>C.id===X))X=void 0;let A=await W2({workspaceRoot:w,storeServers:E.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),L={...F.config,permissionMode:Y??F.config.permissionMode??"default",lspServers:structuredClone(b.servers),permissions:await q.loadWorkspacePermissions(w,F.config.permissions),hooks:await q.loadWorkspaceHooks(w,F.config.hooks??{})};q.validateConfig(L,F.catalog);let T=new b$(L,{...$,modelResources:F,lspResources:b,mcpServers:A,...X?{modelId:X}:{},permissionMode:L.permissionMode,reasoningEffort:H,serviceTier:W,responseVerbosity:Q,communicationStyle:O,...V?{communicationStyleDigest:V}:{},...z?{projectInstructionsDigest:z}:{},...J?{taskWorktree:J}:{},...U?{taskIsolation:U}:{}});return await T.initialize(),T}catch(K){if(!$.subagentInfo&&!(K instanceof x2)){let E=J?await a0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await b$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",E??void 0).catch((q)=>{if(q.code!=="ENOENT")A0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,q)})}throw K}}static async hasPendingInbox($,Z){try{return(await GW(_J($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return S0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??N()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return K1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=e$.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",U=await r.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return _0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:U.taskStatus,...U.taskStartedAt?{taskStartedAt:U.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,updatedAt:U.lastMessageTime}),U}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=e$.getStats();_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return s2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return s2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??bJ}getProjectRuleCatalog(){return this.agentResources?.projectRules??LJ.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,U){let X=new Set;try{let Q=this.baseRegistry.get($)?.build(Z);for(let O of Q?.getAffectedPaths()??[])if(O)X.add(O)}catch{}let Y=(Q)=>{if(typeof Q==="string"&&Q.trim())X.add(Q)};if(["Read","Edit","Write"].includes($))Y(Z.file_path);else if($==="NotebookEdit")Y(Z.notebook_path);else if(["Grep","Glob"].includes($))Y(Z.path);else if($==="Bash")Y(Z.cwd);let H=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(H?.affected_paths))for(let Q of H.affected_paths)Y(Q);if(Array.isArray(H?.changes)){for(let Q of H.changes)if(Q&&typeof Q==="object")Y(Q.path)}let W=[...X].map((Q)=>O0.isAbsolute(Q)?O0.resolve(Q):O0.resolve(this.workspaceRoot,Q)).flatMap((Q)=>{let O=O0.relative(this.workspaceRoot,Q);if(O===""||!O.startsWith("..")&&!O0.isAbsolute(O))return[O0.resolve(this.projectRoot,O)];let V=O0.relative(this.projectRoot,Q);return V===""||!V.startsWith("..")&&!O0.isAbsolute(V)?[Q]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,U)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await a0.getChangeSummary(this.sessionId):void 0;return b$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,U,X){let Y=new Date().toISOString(),H=J==="failed"&&U!==void 0?o2(U):void 0,W=H?.message??(typeof U==="string"?U.slice(0,500):void 0),Q=await r.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:W??null,taskFailure:H??null,...X!==void 0?{taskDiffStat:X}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:Y,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:Y,taskOwnerPid:null}});return _0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:Q.taskStatus,...W?{taskStatusReason:W}:{},...H?{taskFailure:H}:{},...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...Q.taskCompletedAt?{taskCompletedAt:Q.taskCompletedAt}:{},...Q.taskDiffStat?{taskDiffStat:Q.taskDiffStat}:{},...Q.taskQueuePosition?{taskQueuePosition:Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{taskQueueDepth:Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:Q.taskConcurrencyLimit}:{},updatedAt:Q.lastMessageTime}),Q}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),r.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),r.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return Z0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return g0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return g0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return g0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=Z0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},U=Z.getAgent($.agentId,J);if(!U)throw Error(`Subagent not found in this session: ${$.agentId}`);let X=this.subagentRegistry?.getSubagent(U.subagentType),Y=U.configSnapshot?{...U.configSnapshot}:X;if(!Y)throw Error(`Subagent configuration is unavailable: ${U.subagentType}`);let H=Z.resumeAgent({agentId:U.id,prompt:$.prompt,config:Y,owner:J,permissionMode:Y.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:$.onCompleted});if(!H)throw Error(`Subagent cannot be resumed: ${U.id}`);let W=Z.getAgent(H.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:W}}async beginTurn($="goal"){let Z=this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),U=await J.prepareInputTurn($,Z);if(!U.accepted)return U;try{return await this.saveTurnStart(U.handle,U.mode==="direct"?"user":"pending",J.pendingMessages().map((X)=>X.id)),U}catch(X){throw await J.finishTurn(U.handle).catch(()=>{return}),X}}async enqueueSteering($,Z){return this.getActiveTurnMailbox().enqueue($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},U=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let Y=await this.getActiveTurnMailbox().claimedMessageIds($);await U.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},Y),await this.getActiveTurnMailbox().acknowledge(Y)}else await U.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs});let X=await this.getActiveTurnMailbox().finishTurn($,Z);if(!X)return;try{return await this.saveTurnStart(X,"pending",this.getActiveTurnMailbox().pendingMessages().map((Y)=>Y.id)),X}catch(Y){throw await this.getActiveTurnMailbox().finishTurn(X).catch(()=>{return}),Y}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;try{return await this.saveTurnStart(Z,"pending",$.pendingMessages().map((J)=>J.id)),Z}catch(J){throw await $.finishTurn(Z).catch(()=>{return}),J}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await I1.create(this.workspaceRoot,this.sessionId)}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=EW(12),U=this.hasTurnOwner(),X=Z.signal??new AbortController().signal,Y=async(B)=>{let G=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:U}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:U}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:U,delivery:B.delivery,queued:B.queued};_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,G),await Z.onEvent?.(B)},H=await AJ($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:X,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await Y({...B,auxiliary:U})}}),W=NJ(H),O=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...U?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),V=U?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,z={executionId:J,messageId:O,record:H,modelContent:W,auxiliary:U,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}};return await Y({type:"completed",executionId:J,messageId:O,record:H,auxiliary:U,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}}),z})}async initialize(){if(this.initialized)return;this.sessionLease=await h2.acquire(this.sessionId,this.workspaceRoot);try{if(await new S$(this.workspaceRoot,this.sessionId).reapOrphans(),await e.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),!U0(this.sessionId))await RZ(this.workspaceRoot);await Z0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await qW(this.workspaceRoot);let $=b0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)A0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=qJ(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new b5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new e6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await I1.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let U=await this.getExecutionEngine().getContextManager().persistentStore.recoverInterruptedTurn(this.sessionId);if(U?.outcome==="completed")await this.reloadPendingInbox();if(U)A0.warn(`[SessionRuntime ${this.sessionId}] recovered ${U.outcome} turn ${U.turnId}`);this.initialized=!0,A0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,U=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,X=$.reasoningEffort??this.selectedReasoningEffort,Y=$.serviceTier??this.selectedServiceTier,H=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(s2(W,this.getCommunicationStyleCatalog()),U&&(U!==this.currentModelId||X!==this.selectedReasoningEffort||Y!==this.selectedServiceTier||H!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(U),U!==this.currentModelId?"切换模型":X!==this.selectedReasoningEffort?"切换推理强度":Y!==this.selectedServiceTier?"切换服务等级":"切换输出详略",X,Y,H);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=X,this.selectedServiceTier=Y,this.selectedResponseVerbosity=H,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new F$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=$.toolWhitelist?new Set($.toolWhitelist):null,U=$.toolBlacklist?new Set($.toolBlacklist):null;for(let Q of this.baseRegistry.getBuiltinTools()){if(U?.has(Q.name))continue;if(!J||J.has(Q.name))Z.register(Q)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),J,U));let X=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((Q)=>!U?.has(Q)&&(!J||J.has(Q))))for(let Q of g0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:O,...V}=Q;Z.queueMcpTaskChange({revision:0,...V})}this.executorCatalogs.set(Z,{allowed:J,blocked:U});let H={...this.config.permissions,...$.permissions},W=$.permissionMode??this.config.permissionMode??"default";return new f1(Z,{permissionConfig:H,permissionMode:W,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:W,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...W==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(K,E)=>{try{await E()}catch(q){$??=q,A0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${K} during cleanup`,q)}},J=this.chatService,U=this.sessionMcpRegistry,X=this.mcpCatalogListener,Y=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,Q=this.mcpLogListener,O=this.mcpInstructionsListener,V=this.mcpTaskListener,z=this.sessionLease,B=this.autoVerifyRuntime,G=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new F$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,await Z("kill the session background processes",()=>e.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>E0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>B?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>b0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>a0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>g0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(U&&X)U.off("catalogChanged",X);if(U&&Y)U.off("contentCatalogChanged",Y);if(U&&H)U.off("resourceUpdated",H);if(U&&W)U.off("connectionLifecycleChanged",W);if(U&&Q)U.off("log",Q);if(U&&O)U.off("instructionsChanged",O);if(V)g0.getInstance().off("taskChanged",V);await U?.disconnectAll()}),await Z("release the session lease",()=>z?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((U)=>U.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[]){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{}})}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(e.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(Z0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,U,X){let Y=M0($,this.config,J,this.modelResources.catalog,U,X);A0.debug(`${Z} ${Y.displayName} (${$.model})`);let H=Y.model.contextWindow,W=await C2(Y.chat),Q=this.initialized?this.chatService:void 0,O=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new M1(W,O,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=Y.reasoning,this.currentServiceTier=Y.serviceTier,this.currentResponseVerbosity=Y.responseVerbosity;let V=Q;try{await V?.dispose?.()}catch(z){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,z)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await v$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){A0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await r.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof TJ||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await r.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await S2({sessionId:this.sessionId,configDir:O0.join(jJ.homedir(),".blade"),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=x0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new E1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(O)=>{this.applyMcpCatalog(O,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let U=(O)=>{this.applyMcpContentCatalog(O)},X=(O)=>{this.applyMcpResourceUpdated(O)},Y=(O)=>{this.applyMcpConnectionChange(O)},H=(O)=>{this.applyMcpLog(O)},W=(O)=>{this.applyMcpInstructions(O)},Q=(O)=>{if(O.owner.sessionId!==this.sessionId||O0.resolve(O.owner.projectPath)!==O0.resolve(this.workspaceRoot))return;this.applyMcpTask(O);let{owner:V,result:z,...B}=O;_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=U,this.mcpResourceUpdatedListener=X,this.mcpConnectionListener=Y,this.mcpLogListener=H,this.mcpInstructionsListener=W,this.mcpTaskListener=Q,Z.on("contentCatalogChanged",U),Z.on("resourceUpdated",X),Z.on("connectionLifecycleChanged",Y),Z.on("log",H),Z.on("instructionsChanged",W),g0.getInstance().on("taskChanged",Q);for(let[O,V]of Object.entries($))try{let z=V.type==="stdio"?{...this.sessionEnvironment,...V.env}:void 0;await Z.registerServer(O,V.type==="stdio"?{...V,...z&&Object.keys(z).length>0?{env:z}:{}}:V)}catch(z){A0.warn(`Warning: MCP server "${O}" connection failed:`,z)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(A1(Z)),this.baseRegistry.registerAll(N6(Z))}catch($){A0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((U)=>!J?.has(U.name)&&(!Z||Z.has(U.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,U]of this.executorCatalogs){let X=this.filterMcpTools($.tools,U.allowed,U.blocked),Y=(Q)=>!U.blocked?.has(Q)&&(!U.allowed||U.allowed.has(Q)),H={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(Y),removed:$.removed.filter(Y),updated:$.updated.filter(Y)},W=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(X,Z&&W?H:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,U]of this.executorCatalogs)if(Z.some((Y)=>!U.blocked?.has(Y)&&(!U.allowed||U.allowed.has(Y))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...U}=$;for(let[X,Y]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W))))X.queueMcpTaskChange(U)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),U=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return GJ(U,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await Y0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=R2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function $4(){let $=await X0.getInstance().reload();B0().config.actions.setConfig($),await x0.getInstance().disconnectAll(),MJ(),await Y0(N())}import vO from"fuse.js";import Q$ from"node:path";import{Mutex as FW}from"async-mutex";var O$=new FW;async function RJ($){await $.reapplyEnabledSettings(),l$($.getWorkspaceRoot()),await c$($.getWorkspaceRoot()),await Z4(await Y0($.getWorkspaceRoot()))}async function wW($){l$($.getWorkspaceRoot());let Z=await $.refresh();return await c$($.getWorkspaceRoot()),await Z4(await Y0($.getWorkspaceRoot())),Z}async function J4($){let Z=await Y0($),J=Array.from(new Set([Z.plugins,...t2.getInitializedInstances()])),U;for(let X of J){let Y=await wW(X);if(X===Z.plugins)U=Y}return U??{plugins:[],errors:[]}}async function DW($,Z){let J=Q$.resolve($),U=d$();await Promise.all([U.removePluginSetting(Z,{scope:"global",immediate:!0}),U.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),U.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function bW($){return Q$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function SJ($,Z){if(bW(Z)&&!(await P0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function e2($,Z,J,U="local"){return O$.runExclusive(async()=>{let X=Q$.resolve($),Y=await Y0(X),H=Y.plugins.get(Z);if(!H)throw Error(`Plugin not found: ${Z}`);if(H.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await d$().save({enabledPlugins:{[Z]:J}},{scope:U,projectDir:X,immediate:!0});let W=U==="global"?Array.from(new Set([Y.plugins,...t2.getInitializedInstances()])):[Y.plugins];for(let V of W)await RJ(V);let Q=Y.plugins.get(Z);if(!Q)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let O=await X0.getInstance().loadWorkspacePluginSettingsResolution(X);return{name:Z,requestedEnabled:J,effectiveEnabled:Q.status==="active",scope:U,source:Q.source,status:Q.status,effectiveScope:O.settings[Z]?.effectiveScope??"default"}})}async function $5($){return O$.runExclusive(async()=>{let Z=await Y0($);l$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await c$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function U4($,Z,J="global"){return O$.runExclusive(async()=>{let U=Q$.resolve($),X={...Z,...CJ(Z)};await d$().save({pluginSourcePolicy:X},{scope:J,projectDir:U,immediate:!0});let Y=await Y0(U),H=J==="global"?Array.from(new Set([Y.plugins,...t2.getInitializedInstances()])):[Y.plugins];for(let W of H)await RJ(W);return X0.getInstance().loadWorkspacePluginSourcePolicy(U)})}async function X4($,Z,J={}){return O$.runExclusive(async()=>{let U=Q$.resolve($);await SJ(U,Z);let X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await m0().install(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await J4(U);return{result:Y,discovery:H}})}async function Y4($,Z,J={}){return O$.runExclusive(async()=>{let U=Q$.resolve($),X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await m0().update(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await J4(U);return{result:Y,discovery:H}})}async function H4($,Z,J=!1){return O$.runExclusive(async()=>{let U=Q$.resolve($),Y=(await Y0(U)).plugins.getAll().filter((Q)=>Q.manifest.name!==Z&&Q.manifest.dependencies?.[Z]!==void 0).map((Q)=>Q.manifest.name).sort();if(Y.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${Y.join(", ")}`}};let H=await m0().uninstall(Z,J);if(!H.success)return{result:H};await DW(U,Z);let W=await J4(U);return{result:H,discovery:W}})}async function W4($,Z,J){return O$.runExclusive(async()=>{let U=Q$.resolve($);await SJ(U,Z);let X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U);return m0().addMarketplace(Z,{workspaceRoot:U,ref:J,policy:X})})}async function Q4($,Z){return O$.runExclusive(async()=>{let J=Q$.resolve($),U=await X0.getInstance().loadWorkspacePluginSourcePolicy(J);return m0().refreshMarketplace(Z,U)})}async function O4($,Z=!1){return O$.runExclusive(()=>m0().removeMarketplace($,Z))}import V7 from"node:fs/promises";import z7 from"node:path";async function Z5($,Z,J={}){let U=Date.now(),X=J.timeoutMs??20000,Y="unknown";try{let H=M0($,Z,"off");Y=H.model.api;let Q=await new PJ({...H.chat,temperature:0,maxOutputTokens:8,timeout:X,streamIdleTimeout:X,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(X));if(!Boolean(Q.content||Q.reasoningContent||Q.finishReason||Q.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:"ok",message:"Provider responded successfully."}}catch(H){let W=o2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:W.code,message:W.message}}}import LW from"node:os";import kJ from"node:path";function v($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
1027
|
+
`+" /init");if(!B&&X&&X!=="inherit"&&!D.some((C)=>C.id===X))X=void 0;let A=await W2({workspaceRoot:w,storeServers:E.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),L={...F.config,permissionMode:Y??F.config.permissionMode??"default",lspServers:structuredClone(b.servers),permissions:await q.loadWorkspacePermissions(w,F.config.permissions),hooks:await q.loadWorkspaceHooks(w,F.config.hooks??{})};q.validateConfig(L,F.catalog);let T=new b$(L,{...$,modelResources:F,lspResources:b,mcpServers:A,...X?{modelId:X}:{},permissionMode:L.permissionMode,reasoningEffort:H,serviceTier:W,responseVerbosity:Q,communicationStyle:O,...V?{communicationStyleDigest:V}:{},...z?{projectInstructionsDigest:z}:{},...J?{taskWorktree:J}:{},...U?{taskIsolation:U}:{}});return await T.initialize(),T}catch(K){if(!$.subagentInfo&&!(K instanceof x2)){let E=J?await a0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await b$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",E??void 0).catch((q)=>{if(q.code!=="ENOENT")A0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,q)})}throw K}}static async hasPendingInbox($,Z){try{return(await GW(_J($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return S0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??N()}get projectRoot(){return this.options.modelResources?.projectRoot??this.options.lspResources?.projectRoot??this.options.agentResources?.projectRoot??this.options.taskWorktree?.originalWorkspaceRoot??this.workspaceRoot}getConfig(){return this.config}getAvailableModels(){return this.config.models.map(($)=>structuredClone($))}getModelById($){let Z=this.config.models.find((J)=>J.id===$);return Z?structuredClone(Z):void 0}getAgentResources(){if(!this.agentResources)throw Error("Session agent resources are unavailable before initialization");return this.agentResources}getModelResources(){return this.modelResources}getLspResources(){return K1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=e$.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",U=await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,{taskStatus:$.state,taskStatusReason:null,taskFailure:null,taskQueuePosition:J?$.queuePosition??1:null,taskQueueDepth:J?$.queueDepth:null,taskConcurrencyLimit:$.maxConcurrent,...J?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskStartedAt:Z,taskCompletedAt:null,taskOwnerPid:process.pid}});return _0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:U.taskStatus,...U.taskStartedAt?{taskStartedAt:U.taskStartedAt}:{},...$.queuePosition?{taskQueuePosition:$.queuePosition}:{},taskQueueDepth:$.queueDepth,taskConcurrencyLimit:$.maxConcurrent,taskInFlight:$.inFlight,updatedAt:U.lastMessageTime}),U}publishTaskAdmissionCapacity($){if(!this.isTaskSession())return;let Z=e$.getStats();_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"task.status",{taskStatus:$,taskQueueDepth:Z.queued,taskConcurrencyLimit:Z.maxConcurrent,taskInFlight:Z.inFlight,updatedAt:new Date().toISOString()})}getChatService(){if(!this.chatService)throw Error("Session runtime is not initialized");return this.chatService}getExecutionEngine(){if(!this.executionEngine)throw Error("Session runtime is not initialized");return this.executionEngine}async loadModelContext(){if(!this.initialized)throw Error("Session runtime is not initialized");return n.loadSessionModelContext(this.sessionId,this.workspaceRoot)}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getReasoningConfiguration(){if(!this.currentReasoning)throw Error("Session runtime is not initialized");return{...this.currentReasoning,supported:[...this.currentReasoning.supported]}}resolveReasoningConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,$,this.modelResources.catalog).reasoning}getServiceTierConfiguration(){if(!this.currentServiceTier)throw Error("Session runtime is not initialized");return{...this.currentServiceTier,supported:[...this.currentServiceTier.supported]}}resolveServiceTierConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,$).serviceTier}getResponseVerbosityConfiguration(){if(!this.currentResponseVerbosity)throw Error("Session runtime is not initialized");return{...this.currentResponseVerbosity,supported:[...this.currentResponseVerbosity.supported]}}resolveResponseVerbosityConfiguration($,Z=this.currentModelId){return M0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return s2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return s2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??bJ}getProjectRuleCatalog(){return this.agentResources?.projectRules??LJ.empty(this.projectRoot)}getStaticProjectRules(){return this.getProjectRuleCatalog().staticRules(this.projectRoot)}hydrateProjectRules($){return this.getProjectRuleCatalog().hydrate($)}resolveContextualProjectRules($,Z,J,U){let X=new Set;try{let Q=this.baseRegistry.get($)?.build(Z);for(let O of Q?.getAffectedPaths()??[])if(O)X.add(O)}catch{}let Y=(Q)=>{if(typeof Q==="string"&&Q.trim())X.add(Q)};if(["Read","Edit","Write"].includes($))Y(Z.file_path);else if($==="NotebookEdit")Y(Z.notebook_path);else if(["Grep","Glob"].includes($))Y(Z.path);else if($==="Bash")Y(Z.cwd);let H=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;if(Array.isArray(H?.affected_paths))for(let Q of H.affected_paths)Y(Q);if(Array.isArray(H?.changes)){for(let Q of H.changes)if(Q&&typeof Q==="object")Y(Q.path)}let W=[...X].map((Q)=>O0.isAbsolute(Q)?O0.resolve(Q):O0.resolve(this.workspaceRoot,Q)).flatMap((Q)=>{let O=O0.relative(this.workspaceRoot,Q);if(O===""||!O.startsWith("..")&&!O0.isAbsolute(O))return[O0.resolve(this.projectRoot,O)];let V=O0.relative(this.projectRoot,Q);return V===""||!V.startsWith("..")&&!O0.isAbsolute(V)?[Q]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,W,U)}getCurrentModelMaxContextTokens(){if(this.currentModelMaxContextTokens===void 0)throw Error("Session runtime is not initialized");return this.currentModelMaxContextTokens}getGoal(){return this.goalStore.get()}async setTaskStatus($,Z){if(this.options.subagentInfo)return;let J=this.options.taskWorktree&&!["queued","running"].includes($)?await a0.getChangeSummary(this.sessionId):void 0;return b$.persistTaskStatus(this.sessionId,this.workspaceRoot,$,Z,J??void 0)}static async persistTaskStatus($,Z,J,U,X){let Y=new Date().toISOString(),H=J==="failed"&&U!==void 0?o2(U):void 0,W=H?.message??(typeof U==="string"?U.slice(0,500):void 0),Q=await n.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:W??null,taskFailure:H??null,...X!==void 0?{taskDiffStat:X}:J==="running"?{taskDiffStat:null}:{},...J!=="queued"?{taskQueuePosition:null,taskQueueDepth:null}:{},...J==="running"?{taskStartedAt:Y,taskCompletedAt:null,taskOwnerPid:process.pid}:J==="queued"?{taskStartedAt:null,taskCompletedAt:null,taskOwnerPid:null}:{taskCompletedAt:Y,taskOwnerPid:null}});return _0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:Q.taskStatus,...W?{taskStatusReason:W}:{},...H?{taskFailure:H}:{},...Q.taskStartedAt?{taskStartedAt:Q.taskStartedAt}:{},...Q.taskCompletedAt?{taskCompletedAt:Q.taskCompletedAt}:{},...Q.taskDiffStat?{taskDiffStat:Q.taskDiffStat}:{},...Q.taskQueuePosition?{taskQueuePosition:Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{taskQueueDepth:Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:Q.taskConcurrencyLimit}:{},updatedAt:Q.lastMessageTime}),Q}createGoal($){return this.goalStore.create($)}editGoal($){return this.goalStore.edit($)}pauseGoal($){return this.goalStore.pause($)}resumeGoal(){return this.goalStore.resume()}clearGoal(){return this.goalStore.clear()}recordGoalCompletionVerification($){return this.goalStore.recordCompletionVerification($)}invalidateGoalCompletionVerification($){return this.goalStore.invalidateCompletionVerification($)}finalizeVerifiedGoalCompletion(){return this.goalStore.finalizeVerifiedCompletion()}recordGoalProgress($){return this.goalStore.recordProgress($)}beginGoalContinuation(){return this.goalStore.tryBeginContinuation()}async pauseActiveGoal($){return this.goalStore.pauseIfActive($)}async listRewindCheckpoints(){return this.assertRewindIdle(),n.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),n.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return Z0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})}getMcpContentCatalog(){return this.sessionMcpRegistry?.getContentCatalogSnapshot()??{revision:0,resources:[],resourceTemplates:[],prompts:[]}}async refreshMcpContentCatalogs($){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.refreshContentCatalogs($)}async getMcpPrompt($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.getPrompt($,Z,J)}async completeMcpArgument($,Z,J){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");return this.sessionMcpRegistry.complete($,Z,J)}listMcpTasks($){return g0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return g0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return g0.getInstance().cancel($,{sessionId:this.sessionId,projectPath:this.workspaceRoot},Z)}getMcpLogs($,Z={}){return this.sessionMcpRegistry?.getLogSnapshot($,Z)??{revision:0,entries:[]}}getMcpInstructions(){return this.sessionMcpRegistry?.getInstructionsSnapshot()??{revision:0,instructions:[]}}async setMcpLoggingLevel($,Z){if(!this.sessionMcpRegistry)throw Error("This Session has no MCP servers");await this.sessionMcpRegistry.setServerLoggingLevel($,Z)}resumeSubagent($){this.assertSubagentControlIdle();let Z=Z0.getInstance(),J={sessionId:this.sessionId,projectPath:this.workspaceRoot},U=Z.getAgent($.agentId,J);if(!U)throw Error(`Subagent not found in this session: ${$.agentId}`);let X=this.subagentRegistry?.getSubagent(U.subagentType),Y=U.configSnapshot?{...U.configSnapshot}:X;if(!Y)throw Error(`Subagent configuration is unavailable: ${U.subagentType}`);let H=Z.resumeAgent({agentId:U.id,prompt:$.prompt,config:Y,owner:J,permissionMode:Y.permissionMode,reasoningEffort:this.selectedReasoningEffort,serviceTier:this.selectedServiceTier,responseVerbosity:this.selectedResponseVerbosity,communicationStyle:this.selectedCommunicationStyle,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,onEvent:$.onEvent,onCompleted:$.onCompleted});if(!H)throw Error(`Subagent cannot be resumed: ${U.id}`);let W=Z.getAgent(H.agentId,J);if(!W)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:W}}async beginTurn($="goal"){let Z=this.getActiveTurnMailbox().beginTurn();try{return await this.saveTurnStart(Z,$),Z}catch(J){throw await this.getActiveTurnMailbox().finishTurn(Z).catch(()=>{return}),J}}async prepareInputTurn($,Z){let J=this.getActiveTurnMailbox(),U=await J.prepareInputTurn($,Z);if(!U.accepted)return U;try{return await this.saveTurnStart(U.handle,U.mode==="direct"?"user":"pending",J.pendingMessages().map((X)=>X.id)),U}catch(X){throw await J.finishTurn(U.handle).catch(()=>{return}),X}}async enqueueSteering($,Z){return this.getActiveTurnMailbox().enqueue($,Z)}async drainSteering($){return this.getActiveTurnMailbox().drain($)}async drainSteeringOrSeal($){return this.getActiveTurnMailbox().drainOrSeal($)}async getClaimedTurnMessageIds($){return this.getActiveTurnMailbox().claimedMessageIds($)}async discardPendingInput(){let $=this.getActiveTurnMailbox(),Z=$.pendingMessages().map((J)=>J.id);if(Z.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,Z),await $.acknowledge(Z)}async finishTurn($,Z={}){let J=Z.outcome??{status:"aborted",cause:"interrupted",turnsCount:0,toolCallsCount:0,durationMs:0},U=this.getExecutionEngine().getContextManager().persistentStore;if(J.status==="completed"){let Y=await this.getActiveTurnMailbox().claimedMessageIds($);await U.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs},Y),await this.getActiveTurnMailbox().acknowledge(Y)}else await U.saveTurnAbort(this.sessionId,{turnId:$.id,cause:J.cause,abortedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs});let X=await this.getActiveTurnMailbox().finishTurn($,Z);if(!X)return;try{return await this.saveTurnStart(X,"pending",this.getActiveTurnMailbox().pendingMessages().map((Y)=>Y.id)),X}catch(Y){throw await this.getActiveTurnMailbox().finishTurn(X).catch(()=>{return}),Y}}async beginPendingTurn(){let $=this.getActiveTurnMailbox(),Z=await $.beginPendingTurn();if(!Z)return;try{return await this.saveTurnStart(Z,"pending",$.pendingMessages().map((J)=>J.id)),Z}catch(J){throw await $.finishTurn(Z).catch(()=>{return}),J}}hasActiveTurn(){return this.activeTurnMailbox?.isActive()??!1}hasTurnOwner(){return this.activeTurnMailbox?.hasTurnOwner()??!1}getPendingSteeringCount(){return this.activeTurnMailbox?.pendingCount()??0}getPendingSteeringMessages(){return this.activeTurnMailbox?.pendingMessages()??[]}getRecoveredSteeringCount(){return this.activeTurnMailbox?.recoveredCount()??0}async reloadPendingInbox(){if(this.hasTurnOwner())throw Error("Cannot reload the pending inbox during an active turn");this.activeTurnMailbox=await I1.create(this.workspaceRoot,this.sessionId)}async executeUserShellCommand($,Z={}){if(!this.initialized||!this.executionEngine)throw Error("Session runtime is not initialized");return this.userShellMutex.runExclusive(async()=>{let J=EW(12),U=this.hasTurnOwner(),X=Z.signal??new AbortController().signal,Y=async(B)=>{let G=B.type==="started"?{executionId:B.executionId,command:B.command,auxiliary:U}:B.type==="output"?{executionId:B.executionId,stream:B.stream,chunk:B.chunk,streamedBytes:B.streamedBytes,streamTruncated:B.streamTruncated,auxiliary:U}:{executionId:B.executionId,messageId:B.messageId,record:B.record,auxiliary:U,delivery:B.delivery,queued:B.queued};_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${B.type}`,G),await Z.onEvent?.(B)},H=await AJ($,{executionId:J,cwd:this.workspaceRoot,env:{...process.env,...this.sessionEnvironment,BLADE_CLI:"1",BLADE_USER_SHELL:"1"},signal:X,timeoutMs:Z.timeoutMs,executor:this.options.userShellExecutor,onEvent:async(B)=>{if(B.type!=="completed")await Y({...B,auxiliary:U})}}),W=NJ(H),O=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",W,null,{...U?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),V=U?await this.getActiveTurnMailbox().enqueue(W,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,z={executionId:J,messageId:O,record:H,modelContent:W,auxiliary:U,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}};return await Y({type:"completed",executionId:J,messageId:O,record:H,auxiliary:U,...V?.delivery?{delivery:V.delivery}:{},...V?{queued:V.queued}:{}}),z})}async initialize(){if(this.initialized)return;this.sessionLease=await h2.acquire(this.sessionId,this.workspaceRoot);try{if(await new S$(this.workspaceRoot,this.sessionId).reapOrphans(),await e.getInstance().reapOrphanedSession(this.sessionId,this.workspaceRoot),!U0(this.sessionId))await RZ(this.workspaceRoot);await Z0.getInstance().reconcileOrphanedSessions({sessionId:this.sessionId,projectPath:this.workspaceRoot}),await qW(this.workspaceRoot);let $=b0.getInstance();if($.loadConfig(this.config.disableAllHooks?{...this.config.hooks,enabled:!1}:this.config.hooks??{},this.projectRoot),$.bindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot],this.modelResources),await this.loadAgentResources(),this.projectRoot!==this.workspaceRoot)$.inheritProjectConfig(this.projectRoot,this.workspaceRoot);$.bindSessionConfig(this.sessionId,[this.projectRoot,this.workspaceRoot],this.config.disableAllHooks?{...this.agentResources?.hooks??$.getConfig(this.projectRoot),enabled:!1}:this.agentResources?.hooks??$.getConfig(this.projectRoot));let Z=await $.executeSessionStartHooks({projectDir:this.workspaceRoot,sessionId:this.sessionId,permissionMode:this.config.permissionMode??"default",isResume:this.options.sessionStart?.isResume??!1,resumeSessionId:this.options.sessionStart?.resumeSessionId});if(!Z.proceed)throw Error(Z.warning||"SessionStart hook blocked initialization");if(Z.warning)A0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=qJ(Z.env??{});if(this.sessionEnvironment=Object.freeze({...this.sessionEnvironment,...J}),this.config.env=this.sessionEnvironment,$.bindSessionEnvironment(this.sessionId,[this.projectRoot,this.workspaceRoot],this.sessionEnvironment),Object.keys(this.lspResources.servers).length>0)this.lspManager=new b5({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new e6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await I1.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.applyModelConfig(this.resolveModelConfig(this.selectedModelId),"使用模型:",this.selectedReasoningEffort,this.selectedServiceTier,this.selectedResponseVerbosity),await this.getExecutionEngine().getContextManager().persistentStore.initSession(this.sessionId,this.options.subagentInfo);let U=await this.getExecutionEngine().getContextManager().persistentStore.recoverInterruptedTurn(this.sessionId);if(U?.outcome==="completed")await this.reloadPendingInbox();if(U)A0.warn(`[SessionRuntime ${this.sessionId}] recovered ${U.outcome} turn ${U.turnId}`);this.initialized=!0,A0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to clean up after initialization error`,Z)}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId==="inherit",J=$.modelId&&!Z?$.modelId:void 0,U=Z?this.getDefaultModel()?.id:J??this.selectedModelId??this.getDefaultModel()?.id,X=$.reasoningEffort??this.selectedReasoningEffort,Y=$.serviceTier??this.selectedServiceTier,H=$.responseVerbosity??this.selectedResponseVerbosity,W=$.communicationStyle??this.selectedCommunicationStyle;if(s2(W,this.getCommunicationStyleCatalog()),U&&(U!==this.currentModelId||X!==this.selectedReasoningEffort||Y!==this.selectedServiceTier||H!==this.selectedResponseVerbosity))await this.applyModelConfig(this.resolveModelConfig(U),U!==this.currentModelId?"切换模型":X!==this.selectedReasoningEffort?"切换推理强度":Y!==this.selectedServiceTier?"切换服务等级":"切换输出详略",X,Y,H);if(Z)this.selectedModelId=void 0;else if(J)this.selectedModelId=J;this.selectedReasoningEffort=X,this.selectedServiceTier=Y,this.selectedResponseVerbosity=H,this.selectedCommunicationStyle=W}createToolExecutor($={}){let Z=new F$;Z.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=$.toolWhitelist?new Set($.toolWhitelist):null,U=$.toolBlacklist?new Set($.toolBlacklist):null;for(let Q of this.baseRegistry.getBuiltinTools()){if(U?.has(Q.name))continue;if(!J||J.has(Q.name))Z.register(Q)}Z.replaceMcpTools(this.filterMcpTools(this.baseRegistry.getMcpTools(),J,U));let X=this.getMcpInstructions();if(Z.queueMcpInstructionsChange({revision:X.revision,reason:"snapshot",replace:!0,instructions:X.instructions,removed:[]}),["TaskOutput","ListMcpTasks","CancelMcpTask"].some((Q)=>!U?.has(Q)&&(!J||J.has(Q))))for(let Q of g0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:O,...V}=Q;Z.queueMcpTaskChange({revision:0,...V})}this.executorCatalogs.set(Z,{allowed:J,blocked:U});let H={...this.config.permissions,...$.permissions},W=$.permissionMode??this.config.permissionMode??"default";return new f1(Z,{permissionConfig:H,permissionMode:W,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:W,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...W==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(K,E)=>{try{await E()}catch(q){$??=q,A0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${K} during cleanup`,q)}},J=this.chatService,U=this.sessionMcpRegistry,X=this.mcpCatalogListener,Y=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,W=this.mcpConnectionListener,Q=this.mcpLogListener,O=this.mcpInstructionsListener,V=this.mcpTaskListener,z=this.sessionLease,B=this.autoVerifyRuntime,G=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new F$,this.sessionMcpRegistry=void 0,this.mcpCatalogListener=void 0,this.mcpContentCatalogListener=void 0,this.mcpResourceUpdatedListener=void 0,this.mcpConnectionListener=void 0,this.mcpLogListener=void 0,this.mcpInstructionsListener=void 0,this.mcpTaskListener=void 0,this.mcpCatalogBarrier=async()=>{return},this.executorCatalogs.clear(),this.sessionLease=void 0,this.autoVerifyRuntime=void 0,this.lspManager=void 0,await Z("kill the session background processes",()=>e.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>E0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>B?.dispose()),await Z("stop the session LSP servers",()=>G?.dispose()),await Z("release the session hook model resources",()=>b0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>a0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>g0.getInstance().cancelSession({sessionId:this.sessionId,projectPath:this.workspaceRoot})),await Z("disconnect the session MCP servers",async()=>{if(U&&X)U.off("catalogChanged",X);if(U&&Y)U.off("contentCatalogChanged",Y);if(U&&H)U.off("resourceUpdated",H);if(U&&W)U.off("connectionLifecycleChanged",W);if(U&&Q)U.off("log",Q);if(U&&O)U.off("instructionsChanged",O);if(V)g0.getInstance().off("taskChanged",V);await U?.disconnectAll()}),await Z("release the session lease",()=>z?.release()),this.currentModelId=void 0,this.currentReasoning=void 0,this.currentServiceTier=void 0,this.initialized=!1,$!==void 0)throw $}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?this.config.models.find((U)=>U.id===Z):this.getDefaultModel();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}getDefaultModel(){return this.config.models.find(($)=>$.id===this.config.currentModelId)??this.config.models[0]}getActiveTurnMailbox(){if(!this.activeTurnMailbox)throw Error("Session runtime is not initialized");return this.activeTurnMailbox}async saveTurnStart($,Z,J=[]){await this.getExecutionEngine().getContextManager().persistentStore.saveTurnStart(this.sessionId,{turnId:$.id,kind:Z,startedAt:new Date().toISOString(),...J.length>0?{inputMessageIds:J}:{}})}assertRewindIdle(){if(this.hasTurnOwner())throw Error("Cannot rewind while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot rewind while durable input is pending");if(e.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(Z0.getInstance().listForSession({sessionId:this.sessionId,projectPath:this.workspaceRoot}).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background agent is running")}assertSubagentControlIdle(){if(this.hasTurnOwner())throw Error("Cannot resume a subagent while the session has an active turn");if(this.getPendingSteeringCount()>0)throw Error("Cannot resume a subagent while durable input is pending")}async applyModelConfig($,Z,J,U,X){let Y=M0($,this.config,J,this.modelResources.catalog,U,X);A0.debug(`${Z} ${Y.displayName} (${$.model})`);let H=Y.model.contextWindow,W=await C2(Y.chat),Q=this.initialized?this.chatService:void 0,O=this.executionEngine?.getContextManager();this.chatService=W,this.executionEngine=new M1(W,O,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=Y.reasoning,this.currentServiceTier=Y.serviceTier,this.currentResponseVerbosity=Y.responseVerbosity;let V=Q;try{await V?.dispose?.()}catch(z){A0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,z)}}async validateSystemPromptConfig(){let $=this.getStaticProjectRules();if(this.options.projectInstructionsDigest&&$.provenanceSha256!==this.options.projectInstructionsDigest)throw Error("Project instruction provenance mismatch");if(!this.options.subagentInfo&&$.files.length>0&&!this.options.projectInstructionsDigest)await this.persistSystemPromptProvenance({projectInstructionsDigest:$.provenanceSha256}),this.options.projectInstructionsDigest=$.provenanceSha256;let Z=this.resolveCommunicationStyleConfiguration(this.selectedCommunicationStyle);if(Z.source!=="built-in"&&this.options.communicationStyleDigest&&Z.contentSha256!==this.options.communicationStyleDigest)throw Error(`Communication style provenance mismatch: ${this.selectedCommunicationStyle}`);if(Z.source!=="built-in"&&Z.contentSha256&&!this.options.communicationStyleDigest)await this.persistSystemPromptProvenance({communicationStyleDigest:Z.contentSha256}),this.options.communicationStyleDigest=Z.contentSha256;try{await v$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList()??"",communicationStyle:this.selectedCommunicationStyle,communicationStyleCatalog:this.getCommunicationStyleCatalog(),projectRuleCatalog:this.getProjectRuleCatalog(),projectInstructionSourcePath:this.projectRoot})}catch(J){A0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await n.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof TJ||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await n.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await S2({sessionId:this.sessionId,configDir:O0.join(jJ.homedir(),".blade"),workspaceRoot:this.workspaceRoot,resourceRoot:this.projectRoot,agentResources:this.agentResources,modelResources:this.modelResources,lspManager:this.lspManager,lspResources:this.lspResources,getReasoningEffort:()=>this.selectedReasoningEffort,getServiceTier:()=>this.selectedServiceTier,getResponseVerbosity:()=>this.selectedResponseVerbosity,getCommunicationStyle:()=>this.selectedCommunicationStyle})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers??{};if(Object.keys($).length===0)return;let Z=x0.createIsolated({roots:U0(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!U0(this.sessionId),artifactWriter:new E1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!U0(this.sessionId)}),exposeLogDetails:!U0(this.sessionId),exposeInstructions:!U0(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(O)=>{this.applyMcpCatalog(O,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let U=(O)=>{this.applyMcpContentCatalog(O)},X=(O)=>{this.applyMcpResourceUpdated(O)},Y=(O)=>{this.applyMcpConnectionChange(O)},H=(O)=>{this.applyMcpLog(O)},W=(O)=>{this.applyMcpInstructions(O)},Q=(O)=>{if(O.owner.sessionId!==this.sessionId||O0.resolve(O.owner.projectPath)!==O0.resolve(this.workspaceRoot))return;this.applyMcpTask(O);let{owner:V,result:z,...B}=O;_0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",B)};this.mcpContentCatalogListener=U,this.mcpResourceUpdatedListener=X,this.mcpConnectionListener=Y,this.mcpLogListener=H,this.mcpInstructionsListener=W,this.mcpTaskListener=Q,Z.on("contentCatalogChanged",U),Z.on("resourceUpdated",X),Z.on("connectionLifecycleChanged",Y),Z.on("log",H),Z.on("instructionsChanged",W),g0.getInstance().on("taskChanged",Q);for(let[O,V]of Object.entries($))try{let z=V.type==="stdio"?{...this.sessionEnvironment,...V.env}:void 0;await Z.registerServer(O,V.type==="stdio"?{...V,...z&&Object.keys(z).length>0?{env:z}:{}}:V)}catch(z){A0.warn(`Warning: MCP server "${O}" connection failed:`,z)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(A1(Z)),this.baseRegistry.registerAll(N6(Z))}catch($){A0.warn("Failed to register MCP tools:",$)}}filterMcpTools($,Z,J){return $.filter((U)=>!J?.has(U.name)&&(!Z||Z.has(U.name)))}applyMcpCatalog($,Z){this.baseRegistry.replaceMcpTools($.tools);for(let[J,U]of this.executorCatalogs){let X=this.filterMcpTools($.tools,U.allowed,U.blocked),Y=(Q)=>!U.blocked?.has(Q)&&(!U.allowed||U.allowed.has(Q)),H={revision:$.revision,serverName:$.serverName,reason:$.reason,added:$.added.filter(Y),removed:$.removed.filter(Y),updated:$.updated.filter(Y)},W=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(X,Z&&W?H:void 0)}}applyMcpContentCatalog($){if(!this.initialized)return;let Z=$.kind==="resources"?["ListMcpResources","ReadMcpResource"]:$.kind==="resourceTemplates"?["ListMcpResourceTemplates","CompleteMcpArgument"]:["ListMcpPrompts","CompleteMcpArgument","GetMcpPrompt"];for(let[J,U]of this.executorCatalogs)if(Z.some((Y)=>!U.blocked?.has(Y)&&(!U.allowed||U.allowed.has(Y))))J.queueMcpContentChange($)}applyMcpResourceUpdated($){if(!this.initialized)return;for(let[Z,J]of this.executorCatalogs)if(!J.blocked?.has("ReadMcpResource")&&(!J.allowed||J.allowed.has("ReadMcpResource")))Z.queueMcpResourceUpdated($)}applyMcpConnectionChange($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpConnectionChange($)}applyMcpLog($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpLog($)}applyMcpInstructions($){if(!this.initialized)return;for(let Z of this.executorCatalogs.keys())Z.queueMcpInstructionsChange({revision:$.revision,reason:$.reason,replace:!1,instructions:$.action==="added"&&$.instruction?[{serverName:$.serverName,...$.instruction}]:[],removed:$.action==="removed"?[$.serverName]:[]})}applyMcpTask($){if(!this.initialized)return;let{owner:Z,result:J,...U}=$;for(let[X,Y]of this.executorCatalogs)if(["TaskOutput","ListMcpTasks","CancelMcpTask"].some((W)=>!Y.blocked?.has(W)&&(!Y.allowed||Y.allowed.has(W))))X.queueMcpTaskChange(U)}handleMcpSampling=async($,Z)=>{let J=this.getChatService(),U=await J.chat($.messages,void 0,Z,{maxOutputTokens:$.maxTokens,...$.temperature!==void 0?{temperature:$.temperature}:{}});return GJ(U,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await Y0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=R2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function $4(){let $=await X0.getInstance().reload();B0().config.actions.setConfig($),await x0.getInstance().disconnectAll(),MJ(),await Y0(N())}import vO from"fuse.js";import Q$ from"node:path";import{Mutex as FW}from"async-mutex";var O$=new FW;async function RJ($){await $.reapplyEnabledSettings(),l$($.getWorkspaceRoot()),await c$($.getWorkspaceRoot()),await Z4(await Y0($.getWorkspaceRoot()))}async function wW($){l$($.getWorkspaceRoot());let Z=await $.refresh();return await c$($.getWorkspaceRoot()),await Z4(await Y0($.getWorkspaceRoot())),Z}async function J4($){let Z=await Y0($),J=Array.from(new Set([Z.plugins,...t2.getInitializedInstances()])),U;for(let X of J){let Y=await wW(X);if(X===Z.plugins)U=Y}return U??{plugins:[],errors:[]}}async function DW($,Z){let J=Q$.resolve($),U=d$();await Promise.all([U.removePluginSetting(Z,{scope:"global",immediate:!0}),U.removePluginSetting(Z,{scope:"project",projectDir:J,immediate:!0}),U.removePluginSetting(Z,{scope:"local",projectDir:J,immediate:!0})])}function bW($){return Q$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function SJ($,Z){if(bW(Z)&&!(await P0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function e2($,Z,J,U="local"){return O$.runExclusive(async()=>{let X=Q$.resolve($),Y=await Y0(X),H=Y.plugins.get(Z);if(!H)throw Error(`Plugin not found: ${Z}`);if(H.source==="cli")throw Error(`Plugin "${Z}" was loaded with --plugin-dir and is invocation-scoped`);await d$().save({enabledPlugins:{[Z]:J}},{scope:U,projectDir:X,immediate:!0});let W=U==="global"?Array.from(new Set([Y.plugins,...t2.getInitializedInstances()])):[Y.plugins];for(let V of W)await RJ(V);let Q=Y.plugins.get(Z);if(!Q)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let O=await X0.getInstance().loadWorkspacePluginSettingsResolution(X);return{name:Z,requestedEnabled:J,effectiveEnabled:Q.status==="active",scope:U,source:Q.source,status:Q.status,effectiveScope:O.settings[Z]?.effectiveScope??"default"}})}async function $5($){return O$.runExclusive(async()=>{let Z=await Y0($);l$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await c$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function U4($,Z,J="global"){return O$.runExclusive(async()=>{let U=Q$.resolve($),X={...Z,...CJ(Z)};await d$().save({pluginSourcePolicy:X},{scope:J,projectDir:U,immediate:!0});let Y=await Y0(U),H=J==="global"?Array.from(new Set([Y.plugins,...t2.getInitializedInstances()])):[Y.plugins];for(let W of H)await RJ(W);return X0.getInstance().loadWorkspacePluginSourcePolicy(U)})}async function X4($,Z,J={}){return O$.runExclusive(async()=>{let U=Q$.resolve($);await SJ(U,Z);let X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await m0().install(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await J4(U);return{result:Y,discovery:H}})}async function Y4($,Z,J={}){return O$.runExclusive(async()=>{let U=Q$.resolve($),X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await m0().update(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await J4(U);return{result:Y,discovery:H}})}async function H4($,Z,J=!1){return O$.runExclusive(async()=>{let U=Q$.resolve($),Y=(await Y0(U)).plugins.getAll().filter((Q)=>Q.manifest.name!==Z&&Q.manifest.dependencies?.[Z]!==void 0).map((Q)=>Q.manifest.name).sort();if(Y.length>0)return{result:{success:!1,pluginName:Z,code:"PLUGIN_REQUIRED",error:`Plugin "${Z}" is required by: ${Y.join(", ")}`}};let H=await m0().uninstall(Z,J);if(!H.success)return{result:H};await DW(U,Z);let W=await J4(U);return{result:H,discovery:W}})}async function W4($,Z,J){return O$.runExclusive(async()=>{let U=Q$.resolve($);await SJ(U,Z);let X=await X0.getInstance().loadWorkspacePluginSourcePolicy(U);return m0().addMarketplace(Z,{workspaceRoot:U,ref:J,policy:X})})}async function Q4($,Z){return O$.runExclusive(async()=>{let J=Q$.resolve($),U=await X0.getInstance().loadWorkspacePluginSourcePolicy(J);return m0().refreshMarketplace(Z,U)})}async function O4($,Z=!1){return O$.runExclusive(()=>m0().removeMarketplace($,Z))}import V7 from"node:fs/promises";import z7 from"node:path";async function Z5($,Z,J={}){let U=Date.now(),X=J.timeoutMs??20000,Y="unknown";try{let H=M0($,Z,"off");Y=H.model.api;let Q=await new PJ({...H.chat,temperature:0,maxOutputTokens:8,timeout:X,streamIdleTimeout:X,maxRetries:0,fallbackModels:[]}).chat([{role:"user",content:"Reply with OK."}],void 0,AbortSignal.timeout(X));if(!Boolean(Q.content||Q.reasoningContent||Q.finishReason||Q.usage))throw Error("Provider returned an empty response");return{ok:!0,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:"ok",message:"Provider responded successfully."}}catch(H){let W=o2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:W.code,message:W.message}}}import LW from"node:os";import kJ from"node:path";function v($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
1028
1028
|
|
|
1029
1029
|
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>k().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var IJ={name:"agents",description:"Manage agent configurations",fullDescription:"Create, edit, or delete custom subagents. Subagents are specialized agents that Claude can delegate tasks to.",usage:"/agents [list|create|help]",category:"System",examples:["/agents","/agents list","/agents help"],async handler($,Z){let J=$[0],U=v(Z),X=Z.workspaceRoot||Z.cwd||N();await Y0(X);let Y=N$(X);if(!J)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(J==="list"){let W=Y.getAllNames().map((G)=>Y.getSubagent(G)).filter((G)=>G!==void 0);if(W.length===0){let G=`**Agents 管理**
|
|
1030
1030
|
|
|
@@ -1071,7 +1071,7 @@ ${O}
|
|
|
1071
1071
|
`+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
|
|
1072
1072
|
`+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"**提示:** 创建文件后,重启 Blade 使配置生效";return U.sendMessage(W),{success:!0,message:"Help displayed"}}if(J==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let H=`未知子命令: \`${J}\`
|
|
1073
1073
|
|
|
1074
|
-
`+"使用 `/agents help` 查看可用命令";return U.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function vJ($,Z){let J=(await
|
|
1074
|
+
`+"使用 `/agents help` 查看可用命令";return U.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function vJ($,Z){let J=(await n.listSessions({includeSubagents:!1,archived:Z})).filter((U)=>U.sessionId===$);if(J.length===0)return{success:!1,error:`${Z?"Archived session":"Session"} not found: ${$}`};if(J.length>1)return{success:!1,error:`Multiple workspaces contain session ${$}`};return{projectPath:J[0].projectPath}}var yJ={name:"archive",description:"Move an inactive session tree out of the active catalog",fullDescription:"归档一个已停止的会话及其 fork/subagent 后代。Transcript、任务证据和 worktree 元数据都会保留,可通过 /unarchive 恢复。",usage:"/archive [sessionId]",category:"Session",examples:["/archive","/archive web-abc123"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /archive [sessionId]"};try{if($.length===0){if(!Z.lifecycle||!Z.sessionId)return{success:!1,error:"Current surface cannot archive its active session; provide a session ID"};let Y=await Z.lifecycle.archiveCurrent();return{success:!0,message:"session_archived",content:`Archived session \`${Y.sessionId}\`. Restore it with \`/unarchive ${Y.sessionId}\`.`,data:{session:Y}}}let J=$[0],U=await vJ(J,!1);if("success"in U)return U;let X=await n.archiveSession(J,U.projectPath);return{success:!0,message:`Archived session ${J}`,content:`Archived session \`${J}\` and its inactive descendants. Restore it with \`/unarchive ${J}\`.`,data:{session:X}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to archive session"}}}},xJ={name:"unarchive",description:"Restore an archived session tree to the active catalog",fullDescription:"恢复一个归档根会话及其继承归档状态的 fork/subagent 后代。单独归档的后代保持归档。",usage:"/unarchive <sessionId>",category:"Session",examples:["/unarchive web-abc123"],async handler($){if($.length!==1)return{success:!1,error:"Usage: /unarchive <sessionId>"};try{let Z=$[0],J=await vJ(Z,!0);if("success"in J)return J;let U=await n.unarchiveSession(Z,J.projectPath);return{success:!0,message:`Restored session ${Z}`,content:`Restored session \`${Z}\` to the active catalog.`,data:{session:U}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to restore session"}}}};import AW from"node:path";var NW={name:"branch",description:"Fork the current session into an independent branch",fullDescription:"将当前会话历史分支到一个独立会话",usage:"/branch",async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to branch"};let J=AW.resolve(Z.workspaceRoot??Z.cwd),U=await n.forkSession(Z.sessionId,{sourceProjectPath:J,targetProjectPath:J});return{success:!0,message:"session_forked",content:Z.acp?`Created session branch ${U.sessionId}. Load it with ACP session/load to continue independently.`:void 0,data:{action:"restore_forked_session",sessionId:U.sessionId,parentSessionId:U.parentSessionId,messages:U.messages,visibleMessages:n.toUISafeMessages(U.messages)}}}},hJ=NW;async function TW($,Z){let J=v(Z);try{let U=G0(),X=w$();if(!U||!X)return{success:!1,error:"配置未初始化"};let Y=B0().session,H=Z.messages??Y.messages,W=Z.sessionId??Y.sessionId;if(!H||H.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let Q=Z.messages?[...Z.messages]:H.map((K)=>({role:K.role,content:K.content})),O=J5.countTokens(Q,X.model),V=M0(X,U,"off"),z=V.model.contextWindow,B=(O/z*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
|
|
1075
1075
|
• 消息数量: ${Q.length}
|
|
1076
1076
|
• Token 数量: ${O.toLocaleString()}
|
|
1077
1077
|
• Token 限制: ${z.toLocaleString()}
|
|
@@ -1094,8 +1094,8 @@ ${O}
|
|
|
1094
1094
|
|
|
1095
1095
|
由于压缩过程出现错误,已使用简单截断策略。
|
|
1096
1096
|
错误信息: ${G.error}`),{success:!1,message:"compact_fallback",error:G.error,data:{compactedMessages:G.compactedMessages,boundaryMessage:G.boundaryMessage,summaryMessage:G.summaryMessage,preTokens:G.preTokens,postTokens:G.postTokens}}}catch(U){let X=U instanceof Error?U.message:String(U);return J.sendMessage(`[FAIL] **压缩失败**: ${X}`),{success:!1,error:X}}}var fW={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:TW},dJ=fW;function jW($){return`Reasoning effort: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1097
|
-
Supported: auto, ${$.supported.join(", ")}`}var MW={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!gJ(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let U=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:jW(U),data:{reasoningEffort:U.selection,effectiveReasoningEffort:U.effective,supportedReasoningEfforts:U.supported}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Failed to update reasoning effort"}}}},mJ=MW;import{mkdir as CW,open as RW,unlink as SW}from"node:fs/promises";import pJ from"node:os";import X1 from"node:path";function PW($,Z,J){let U=Z?.trim()||J;if(U.includes("\x00"))throw Error("Session export path contains a null byte");if(U==="~")return X1.join(pJ.homedir(),J);if(U.startsWith(`~${X1.sep}`)||U.startsWith("~/"))return X1.resolve(pJ.homedir(),U.slice(2));return X1.resolve($,U)}async function iJ($,Z,J){if(!X1.isAbsolute($))throw Error("Session export cwd must be absolute");let U=PW($,J,Z.filename);await CW(X1.dirname(U),{recursive:!0,mode:448});let X,Y=!1;try{return X=await RW(U,"wx",384),Y=!0,await X.writeFile(Z.markdown,"utf8"),await X.sync(),U}catch(H){if(await X?.close().catch(()=>{return}),X=void 0,Y)await SW(U).catch(()=>{return});if(H.code==="EEXIST")throw Error(`Session export already exists: ${U}`);throw H}finally{await X?.close().catch(()=>{return})}}function kW($){let Z=!1,J=[];for(let U of $){if(U==="--reasoning"){Z=!0;continue}if(U.startsWith("--"))throw Error(`Unknown export option: ${U}`);J.push(U)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var IW={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:U,outputPath:X}=kW($),Y=await
|
|
1098
|
-
SHA-256 ${Y.contentSha256}`,data:{action:"session_exported",filePath:H,filename:Y.filename,contentSha256:Y.contentSha256,contentBytes:Y.contentBytes,redactionCount:Y.redactionCount}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Session export failed"}}}},lJ=IW;function vW($){return $.filter((Z)=>Z.relationType!=="subagent")}var yW={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await
|
|
1097
|
+
Supported: auto, ${$.supported.join(", ")}`}var MW={name:"effort",description:"查看或设置当前 Session 的推理强度",fullDescription:"推理强度由当前 Session 持有并持久化。auto 会按模型能力在 high 附近解析;显式不支持的级别会被拒绝。",usage:"/effort [auto|off|minimal|low|medium|high|xhigh|max]",category:"Session",examples:["/effort","/effort low","/effort auto","/effort off"],async handler($,Z){if(!Z.reasoning)return{success:!1,error:"This surface has no active Session reasoning boundary"};if($.length>1)return{success:!1,error:"Usage: /effort [auto|off|minimal|low|medium|high|xhigh|max]"};let J=$[0]?.toLowerCase();if(J!==void 0&&!gJ(J))return{success:!1,error:`Invalid reasoning effort: ${J}`};try{let U=J?await Z.reasoning.set(J):await Z.reasoning.get();return{success:!0,message:jW(U),data:{reasoningEffort:U.selection,effectiveReasoningEffort:U.effective,supportedReasoningEfforts:U.supported}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Failed to update reasoning effort"}}}},mJ=MW;import{mkdir as CW,open as RW,unlink as SW}from"node:fs/promises";import pJ from"node:os";import X1 from"node:path";function PW($,Z,J){let U=Z?.trim()||J;if(U.includes("\x00"))throw Error("Session export path contains a null byte");if(U==="~")return X1.join(pJ.homedir(),J);if(U.startsWith(`~${X1.sep}`)||U.startsWith("~/"))return X1.resolve(pJ.homedir(),U.slice(2));return X1.resolve($,U)}async function iJ($,Z,J){if(!X1.isAbsolute($))throw Error("Session export cwd must be absolute");let U=PW($,J,Z.filename);await CW(X1.dirname(U),{recursive:!0,mode:448});let X,Y=!1;try{return X=await RW(U,"wx",384),Y=!0,await X.writeFile(Z.markdown,"utf8"),await X.sync(),U}catch(H){if(await X?.close().catch(()=>{return}),X=void 0,Y)await SW(U).catch(()=>{return});if(H.code==="EEXIST")throw Error(`Session export already exists: ${U}`);throw H}finally{await X?.close().catch(()=>{return})}}function kW($){let Z=!1,J=[];for(let U of $){if(U==="--reasoning"){Z=!0;continue}if(U.startsWith("--"))throw Error(`Unknown export option: ${U}`);J.push(U)}if(J.length>1)throw Error("Usage: /export [path] [--reasoning]");return{includeReasoning:Z,...J[0]?{outputPath:J[0]}:{}}}var IW={name:"export",description:"Export the current durable conversation as safe Markdown",fullDescription:"将当前完整 durable history 导出为 Markdown。工具活动经过凭证、二进制、宿主路径和体积清理;reasoning 仅在显式 --reasoning 时包含。",usage:"/export [path] [--reasoning]",category:"Session",examples:["/export","/export reports/conversation.md","/export --reasoning"],async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to export"};let J=Z.workspaceRoot??Z.cwd;try{let{includeReasoning:U,outputPath:X}=kW($),Y=await n.exportSessionMarkdown(Z.sessionId,J,{includeReasoning:U});if(Z.surface==="acp"){if(X)return{success:!1,error:"ACP export does not write host paths; omit the path to receive Markdown"};if(Buffer.byteLength(Y.markdown,"utf8")>cJ)return{success:!1,error:"Session export exceeds the ACP inline limit; use the Web export endpoint"};return{success:!0,message:"Session export ready",content:Y.markdown,data:{action:"session_exported",filename:Y.filename,contentSha256:Y.contentSha256,contentBytes:Y.contentBytes}}}let H=await iJ(J,Y,X);return{success:!0,message:`Saved conversation to ${H}
|
|
1098
|
+
SHA-256 ${Y.contentSha256}`,data:{action:"session_exported",filePath:H,filename:Y.filename,contentSha256:Y.contentSha256,contentBytes:Y.contentBytes,redactionCount:Y.redactionCount}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Session export failed"}}}},lJ=IW;function vW($){return $.filter((Z)=>Z.relationType!=="subagent")}var yW={name:"fork",description:"Fork a conversation into an independent session branch",fullDescription:"从任意工作区的历史会话创建独立分支。可以指定唯一 sessionId 直接 fork,或不带参数打开会话选择器。",usage:"/fork [sessionId]",category:"Session",examples:["/fork - 打开会话选择器","/fork parent-session - 直接 fork 指定会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /fork [sessionId]"};try{let J=await n.listSessions({includeSubagents:!1}),U=vW(J);if($.length===0){if(U.length===0)return{success:!1,error:"No forkable sessions found"};return{success:!0,data:{action:"select_session",intent:"fork",sessions:U}}}let X=$[0],Y=J.filter((W)=>W.sessionId===X);if(Y.length>0&&Y.every((W)=>W.relationType==="subagent"))return{success:!1,error:`Cannot fork subagent session: ${X}`};let H=U.filter((W)=>W.sessionId===X);if(H.length===0)return{success:!1,error:`Session not found: ${X}`};if(H.length>1)return{success:!1,error:`Multiple workspaces contain session ${X}; use /fork to select one`};return{success:!0,data:{action:"activate_session",intent:"fork",session:H[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},nJ=yW;function oJ($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let U=Math.floor(J/60);if(U<24)return`${U}h ago`;return`${Math.floor(U/24)}d ago`}async function xW($){let Z=x0.getInstance(),J=I$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
|
|
1099
1099
|
|
|
1100
1100
|
[WARN] 暂无配置的 MCP 服务器
|
|
1101
1101
|
|
|
@@ -1205,8 +1205,8 @@ ${W}
|
|
|
1205
1205
|
`+`/memory list — 列出所有记忆文件
|
|
1206
1206
|
`+`/memory show [topic] — 查看记忆内容(默认 MEMORY)
|
|
1207
1207
|
`+`/memory edit [topic] — 用编辑器打开记忆文件(默认 MEMORY)
|
|
1208
|
-
`+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},Z7=JQ;async function UQ($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var XQ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:UQ},U5=XQ;var YQ={name:"resume",description:"Resume a conversation",fullDescription:"恢复任意工作区的历史会话。可以指定唯一 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /resume [sessionId]"};try{let J=await
|
|
1209
|
-
`)),{success:!0}}let U=WQ($),X=await Z.rewind.execute(U),Y=
|
|
1208
|
+
`+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},Z7=JQ;async function UQ($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var XQ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:UQ},U5=XQ;var YQ={name:"resume",description:"Resume a conversation",fullDescription:"恢复任意工作区的历史会话。可以指定唯一 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /resume [sessionId]"};try{let J=await n.listSessions({includeSubagents:!1});if($.length===0){if(J.length===0)return{success:!1,error:"No resumable sessions found"};return{success:!0,data:{action:"select_session",intent:"resume",sessions:J}}}let U=$[0],X=J.filter((Y)=>Y.sessionId===U);if(X.length===0)return{success:!1,error:`Session not found: ${U}`};if(X.length>1)return{success:!1,error:`Multiple workspaces contain session ${U}; use /resume to select one`};return{success:!0,data:{action:"activate_session",intent:"resume",session:X[0]}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to list sessions"}}}},J7=YQ;import z4 from"node:path";async function HQ($,Z){let J=v(Z),U=Z.sessionId??B0().session?.sessionId;if(!U)return J.sendMessage("No active session is available for file rewind."),{success:!1,error:"No active session"};if($.length===0)return{success:!1,error:"Usage: /rewind file <file_path>"};let X=z4.resolve(Z.workspaceRoot??Z.cwd),Y=z4.resolve(Z.cwd,$.join(" "));if(!await V0.isWithinWorkspaceResolved(Y,X)){let O=`Target path is outside the current workspace: ${Y}`;return J.sendMessage(O),{success:!1,error:O}}let H=new c0({sessionId:U,workspaceRoot:X});await H.initialize();let W=await H.rewindLatest(Y);E0.getInstance().clearFileRecord(W.filePath);let Q=z4.relative(X,Y)||".";return J.sendMessage(`Rewound \`${Q}\` to the state before the latest Blade edit (v${W.version}).`),{success:!0}}function WQ($){let Z=new Set($.filter((Y)=>Y.startsWith("--"))),J=$.filter((Y)=>!Y.startsWith("--")),U=new Set(["--code","--code-only","--conversation"]),X=[...Z].find((Y)=>!U.has(Y));if(X)throw Error(`Unknown rewind option: ${X}`);if(J.length!==1)throw Error("Usage: /rewind <checkpointId> [--code|--code-only|--conversation]");if(Z.has("--code")&&Z.has("--code-only"))throw Error("--code and --code-only cannot be combined");return{targetMessageId:J[0],mode:Z.has("--code-only")?"code":Z.has("--code")?"both":"conversation"}}var QQ={name:"rewind",description:"Rewind the conversation and optionally restore code",fullDescription:"List durable user-turn checkpoints or rewind to one. Use --code to restore both conversation and code. Legacy single-file rewind remains available through /rewind file <path>.",usage:"/rewind [checkpointId] [--code|--code-only] | /rewind file <file_path>",aliases:["undo","checkpoint"],async handler($,Z){let J=v(Z);try{if($[0]==="file"||$[0]==="--file")return await HQ($.slice(1),Z);if(!Z.rewind)return{success:!1,error:"This surface does not own a session runtime for rewind"};if($.length===0){let W=await Z.rewind.listCheckpoints();if(W.length===0)return J.sendMessage("Nothing to rewind to yet."),{success:!0};let Q=W.map((O)=>{let V=O.fileCount===0?"":`, ${O.fileCount} file${O.fileCount===1?"":"s"}`;return`- \`${O.messageId}\` ${O.preview}${V}`});return J.sendMessage(["**Rewind checkpoints**","",...Q,"","Use `/rewind <checkpointId>` for conversation only or add `--code` to restore code too."].join(`
|
|
1209
|
+
`)),{success:!0}}let U=WQ($),X=await Z.rewind.execute(U),Y=n.toUISafeMessages(X.messages),H=X.restoredFiles.length===0?"":` Restored ${X.restoredFiles.length} file${X.restoredFiles.length===1?"":"s"}.`;return J.sendMessage(`Rewound ${X.removedTurns} turn${X.removedTurns===1?"":"s"} to before: ${X.checkpoint.preview}.${H}`),{success:!0,data:{action:"rewind_session",sessionId:Z.sessionId,messages:X.messages,visibleMessages:Y,checkpoint:X.checkpoint,mode:X.mode,restoredFiles:X.restoredFiles}}}catch(U){let X=U instanceof Error?U.message:String(U);return J.sendMessage(`Rewind failed: ${X}`),{success:!1,error:X}}}},U7=QQ;function OQ($){return`Service tier: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1210
1210
|
Supported: auto, ${$.supported.join(", ")}`}function VQ($){let Z=$.toLowerCase();if(Z==="on")return"fast";if(Z==="off")return"standard";return X7(Z)?Z:void 0}var zQ={name:"speed",aliases:["fast"],description:"查看或设置当前 Session 的 provider 服务等级",fullDescription:"auto 使用 provider 默认值;standard 强制基线;fast 使用 priority tier;flex 使用低成本弹性 tier。显式不支持的等级会被拒绝。",usage:"/speed [auto|standard|fast|flex]",category:"Session",examples:["/speed","/speed fast","/fast on","/fast off"],async handler($,Z){if(!Z.serviceTier)return{success:!1,error:"This surface has no active Session service-tier boundary"};if($.length>1)return{success:!1,error:"Usage: /speed [auto|standard|fast|flex]"};let J=$[0]?VQ($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid service tier: ${$[0].toLowerCase()}`};try{let U=J?await Z.serviceTier.set(J):await Z.serviceTier.get();return{success:!0,message:OQ(U),data:{serviceTier:U.selection,effectiveServiceTier:U.effective,supportedServiceTiers:U.supported}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Failed to update service tier"}}}},Y7=zQ;function BQ($){return`Communication style: ${$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`}
|
|
1211
1211
|
Supported: ${$.supported.map((J)=>J.id).join(", ")}`}function _Q($){let Z=$.toLowerCase();return H7(Z)?Z:void 0}var GQ={name:"style",aliases:["personality"],description:"查看或设置当前 Session 的沟通风格",fullDescription:"内置或 namespaced custom style 只改变沟通语气和解释框架。",usage:"/style [auto|pragmatic|friendly|explanatory|<namespaced-id>]",category:"Session",examples:["/style","/style pragmatic","/style project:review:strict","/personality friendly"],async handler($,Z){if(!Z.communicationStyle)return{success:!1,error:"This surface has no active Session communication-style boundary"};if($.length>1)return{success:!1,error:"Usage: /style [auto|pragmatic|friendly|explanatory|<namespaced-id>]"};let J=$[0]?_Q($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid communication style: ${$[0].toLowerCase()}`};try{let U=J?await Z.communicationStyle.set(J):await Z.communicationStyle.get();return{success:!0,message:BQ(U),data:{communicationStyle:U.selection,effectiveCommunicationStyle:U.effective}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Failed to update communication style"}}}},W7=GQ;function KQ($){let Z=$.selection===$.effective?$.selection:`${$.selection} (${$.effective})`,J=$.supported.length>0?`auto, ${$.supported.join(", ")}`:"auto";return`Response verbosity: ${Z}
|
|
1212
1212
|
Supported: ${J}`}function EQ($){let Z=$.toLowerCase();return Q7(Z)?Z:void 0}var qQ={name:"verbosity",aliases:["detail"],description:"查看或设置当前 Session 的响应详略",fullDescription:"auto 使用模型默认值;low、medium、high 控制支持模型的原生响应详略。显式不支持的选择会被拒绝。",usage:"/verbosity [auto|low|medium|high]",category:"Session",examples:["/verbosity","/verbosity low","/detail high"],async handler($,Z){if(!Z.responseVerbosity)return{success:!1,error:"This surface has no active Session response-verbosity boundary"};if($.length>1)return{success:!1,error:"Usage: /verbosity [auto|low|medium|high]"};let J=$[0]?EQ($[0]):void 0;if($[0]&&!J)return{success:!1,error:`Invalid response verbosity: ${$[0].toLowerCase()}`};try{let U=J?await Z.responseVerbosity.set(J):await Z.responseVerbosity.get();return{success:!0,message:KQ(U),data:{responseVerbosity:U.selection,effectiveResponseVerbosity:U.effective,supportedResponseVerbosities:U.supported}}}catch(U){return{success:!1,error:U instanceof Error?U.message:"Failed to update response verbosity"}}}},O7=qQ;var FQ={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=v(Z),U=`**可用的 Slash Commands:**
|
|
@@ -1570,7 +1570,7 @@ ${J}
|
|
|
1570
1570
|
`)),{success:!0,message:"Schedules listed",content:Q.join(`
|
|
1571
1571
|
`)}}case"create":{let W=DO(Y);if("error"in W)return U.sendMessage(`创建失败:${W.error}`),{success:!1,error:W.error};let Q={prompt:W.prompt,projectPath:H,trigger:W.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let O=await $.create(Q),V=O.nextRunAt?new Date(O.nextRunAt).toLocaleString():"(无)";return U.sendMessage(`[OK] 已创建定时任务 \`${O.id}\`
|
|
1572
1572
|
${b4(O.trigger)} · 下次运行: ${V}`),{success:!0,message:`Schedule ${O.id} created`}}catch(O){let V=O instanceof Error?O.message:String(O);return U.sendMessage(`创建失败:${V}`),{success:!1,error:V}}}case"remove":case"rm":{let W=Y[0];if(!W)return U.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let Q=await $.remove(W);return U.sendMessage(Q?`[OK] 已删除 \`${W}\``:`未找到 \`${W}\``),{success:Q,message:Q?"Removed":"Not found"}}case"enable":case"disable":{let W=Y[0];if(!W)return U.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let Q=await $.setEnabled(W,X==="enable");return U.sendMessage(Q?`[OK] 已${X==="enable"?"启用":"停用"} \`${W}\``:`未找到 \`${W}\``),{success:Boolean(Q),message:Q?"Updated":"Not found"}}case"run":{let W=Y[0];if(!W)return U.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await bO(W),U.sendMessage(`[OK] 已触发 \`${W}\``),{success:!0,message:"Schedule triggered"}}catch(Q){let O=Q instanceof Error?Q.message:String(Q);return U.sendMessage(`运行失败:${O}`),{success:!1,error:O}}}default:return U.sendMessage(`未知子命令: ${X}
|
|
1573
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var x7=LO();import*as Q1 from"node:fs/promises";import*as O1 from"node:path";async function m7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??r1(X??N());if(!Y){let B=await AO($,X??N(),J,U);if(B)return B}let W;try{W=(await Q1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>O1.join(H,G))}catch{return[]}let O=(await Promise.all(W.map(async(B)=>{try{let G=await Q1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),V=[],z=U?$:$.toLowerCase();for(let B of O){if(V.length>=J)break;let G=O1.basename(B,".jsonl"),K=await NO(B,z,U,G);if(V.push(...K),V.length>=J){V.length=J;break}}return V}async function AO($,Z,J,U){try{let{syncAll:X}=await import("./chunk-
|
|
1573
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var x7=LO();import*as Q1 from"node:fs/promises";import*as O1 from"node:path";async function m7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??r1(X??N());if(!Y){let B=await AO($,X??N(),J,U);if(B)return B}let W;try{W=(await Q1.readdir(H)).filter((G)=>G.endsWith(".jsonl")&&!G.startsWith("agent_")).map((G)=>O1.join(H,G))}catch{return[]}let O=(await Promise.all(W.map(async(B)=>{try{let G=await Q1.stat(B);return{path:B,mtime:G.mtimeMs}}catch{return null}}))).filter((B)=>B!==null).sort((B,G)=>G.mtime-B.mtime).map((B)=>B.path),V=[],z=U?$:$.toLowerCase();for(let B of O){if(V.length>=J)break;let G=O1.basename(B,".jsonl"),K=await NO(B,z,U,G);if(V.push(...K),V.length>=J){V.length=J;break}}return V}async function AO($,Z,J,U){try{let{syncAll:X}=await import("./chunk-pdkj959x.js"),Y=await d7();if(!Y)return null;let{SessionService:H}=await import("./chunk-1p45ytbg.js");await X(Y,H.projectionDeriverForSearch());let W=O1.resolve(Z),Q=g7(Y,$,W,J*4),O=U?$:$.toLowerCase(),V=[];for(let z of Q){if(z.role!=="user"&&z.role!=="assistant")continue;let B=L4(z.text,O,U,z.session_id,z.role,z.timestamp??void 0,0);if(B)V.push(B);if(V.length>=J)break}return V}catch{return null}}async function NO($,Z,J,U){try{let X=await Q1.readFile($,"utf8"),H=X.split(`
|
|
1574
1574
|
`).flatMap((z,B)=>{if(!z.trim())return[];try{return[{event:JSON.parse(z),index:B}]}catch{return[]}});if(!H.some(({event:z})=>z.type==="session_created"))return TO(H,Z,J,U);let Q=new Map(H.flatMap(({event:z,index:B})=>typeof z.id==="string"?[[z.id,B+1]]:[])),O=h7(u7(X,$)),V=new Map;for(let z of O){if(z.type==="message_created"&&(z.data.role==="user"||z.data.role==="assistant"))V.set(z.data.messageId,{role:z.data.role,content:[],timestamp:z.timestamp,lineNumber:Q.get(z.id)??0});if(z.type==="part_created"&&z.data.partType==="text"){let B=V.get(z.data.messageId),G=z.data.payload.text;if(B&&typeof G==="string")B.content.push(G)}}return[...V.values()].flatMap((z)=>{let B=L4(z.content.join(" "),Z,J,U,z.role,z.timestamp,z.lineNumber);return B?[B]:[]})}catch{return[]}}function TO($,Z,J,U){return $.flatMap(({event:X,index:Y})=>{if(X.type!=="message")return[];let H=X.message;if(H?.role!=="user"&&H?.role!=="assistant"||!H.content)return[];let W=typeof H.content==="string"?H.content:Array.isArray(H.content)?H.content.filter((O)=>typeof O==="object"&&O!==null&&O.type==="text"&&typeof O.text==="string").map((O)=>O.text).join(" "):"",Q=L4(W,Z,J,U,H.role,typeof X.timestamp==="string"?X.timestamp:void 0,Y+1);return Q?[Q]:[]})}function L4($,Z,J,U,X,Y,H){if(!$)return;let W=J?$:$.toLowerCase();if(!W.includes(Z))return;let Q=W.indexOf(Z),O=Math.max(0,Q-80),V=Math.min($.length,Q+Z.length+80);return{sessionId:U,role:X,content:(O>0?"...":"")+$.slice(O,V).replace(/\n/g," ")+(V<$.length?"...":""),timestamp:Y,lineNumber:H}}function p7($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1575
1575
|
`];for(let J of $){let U=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",X=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${X} \`${J.sessionId.slice(0,8)}\` (${U})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
|
|
1576
1576
|
`)}var fO={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=v(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let U=$.join(" ");J.sendMessage(`正在搜索: "${U}" ...`);try{let X=await m7(U,{maxResults:15,projectPath:Z.cwd}),Y=p7(X);return J.sendMessage(Y),{success:!0,message:`found ${X.length} results`,data:{matches:X.length}}}catch(X){let Y=X instanceof Error?X.message:"未知错误";return J.sendMessage(`搜索失败: ${Y}`),{success:!1,error:Y}}}},i7=fO;var jO={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await I0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),l$(Z.workspaceRoot??Z.cwd),await c$(Z.workspaceRoot??Z.cwd),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let U=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return k().addAssistantMessage(U),{success:!1,error:U}}}},c7=jO;import MO from"node:path";function V5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function l7($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function n7($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function CO($,Z){let J=v(Z),U=$[0],X=e.getInstance(),Y=Z0.getInstance(),H=Z.sessionId??"",W=Z.sessionId?{sessionId:Z.sessionId,projectPath:MO.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(U==="resume"){let G=$[1],K=$.slice(2).join(" ").trim();if(!G||!K)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let E=await Z.subagents.resume(G,K),q=`Resumed \`${G}\` as \`${E.session.id}\` (depth ${E.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:G,subagent:E.session}}}if(U==="clean"){let G=Y.cleanupExpiredSessionsForParent(W??H,0);return J.sendMessage(`已清理 ${G} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${G} agent sessions`}}let Q=[`**后台任务列表**
|
|
@@ -1605,4 +1605,4 @@ ${b4(O.trigger)} · 下次运行: ${V}`),{success:!0,message:`Schedule ${O.id} c
|
|
|
1605
1605
|
|
|
1606
1606
|
**When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,U)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function hO($,Z){return I0({cwd:Z}).getUserInvocableSkills().find((X)=>X.name===$)}async function uO($){await o7({cwd:$})}async function dO($){let Z=y0.getInstance($),J=Z.getLastDiscoveryResult();if(Z.isInitialized()&&J)return J;return await Z.initialize($)}async function Xj($,Z){try{let{command:J,args:U}=yO($),X=xO(J);if(X)return await X.handler(U,Z);let Y=Z.workspaceRoot||Z.cwd||N();await Y0(Y);let H=y0.getInstance(Y);if(!H.isInitialized())await dO(Y);if(H.hasCommand(J)){let V=H.getCommand(J);if(V){let z=await H.executeCommand(J,{args:U,workspaceRoot:Y,signal:Z.signal});if(z)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:z,config:V.config}}}}let Q=Z$(Y).findCommand(J);if(Q){let V=await H.executePluginCommand(Q.namespacedName,{args:U,workspaceRoot:Y,signal:Z.signal});if(V)return{success:!0,message:`执行插件命令: /${Q.namespacedName}`,data:{action:"invoke_plugin_command",commandName:Q.namespacedName,pluginName:Q.pluginName,processedContent:V,config:Q.config}}}await uO(Y);let O=hO(J,Y);if(O)return await t7(O).handler(U,Z);return{success:!1,error:`未知命令: /${J}
|
|
1607
1607
|
使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function Yj($=N()){let Z=Object.values(u1),U=y0.getInstance($).getAllCommands().map((Q)=>({name:Q.name,description:Q.config.description||Q.content.slice(0,50),usage:Q.config.argumentHint?`/${Q.name} ${Q.config.argumentHint}`:`/${Q.name}`,category:"custom",handler:async()=>({success:!0})})),Y=Z$($).getAllCommands().map((Q)=>({name:Q.namespacedName,description:Q.config.description||Q.content.slice(0,50),usage:Q.config.argumentHint?`/${Q.namespacedName} ${Q.config.argumentHint}`:`/${Q.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),W=I0({cwd:$}).getUserInvocableSkills().map(t7);return[...Z,...U,...Y,...W]}function Hj($,Z=N()){let J=($.startsWith("/")?$.slice(1):$).trim(),U=Object.values(u1).map((K)=>({name:K.name,description:K.description,aliases:K.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),X=y0.getInstance(Z),Y=X.getAllCommands().map((K)=>({name:K.name,description:K.config.description||K.content.slice(0,50),aliases:[],label:X.getCommandLabel(K),argumentHint:K.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),W=Z$(Z).getAllCommands().map((K)=>({name:K.namespacedName,description:K.config.description||K.content.slice(0,50),aliases:[K.originalName],label:`(plugin: ${K.pluginName})`,argumentHint:K.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),O=I0({cwd:Z}).getUserInvocableSkills().map((K)=>({name:K.name,description:K.description,aliases:[],label:"(skill)",argumentHint:K.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),V=[...U,...Y,...W,...O];if(!J)return V.map((K)=>({command:`/${K.name}`,description:K.label?`${K.description} ${K.label}`:K.description,argumentHint:K.argumentHint,matchScore:50}));return new vO(V,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(J).map((K)=>{let E=K.score??1,q=Math.round((1-E)*100),w=K.item;return{command:`/${w.name}`,description:w.label?`${w.description} ${w.label}`:w.description,argumentHint:w.argumentHint,matchScore:q}}).filter((K)=>(K.matchScore||0)>=40)}
|
|
1608
|
-
export{nz as
|
|
1608
|
+
export{nz as u,B$ as v,h as w,S0 as x,x$ as y,XX as z,e as A,xE as B,L0 as C,a0 as D,U9 as E,e$ as F,b$ as G,u6 as H,d6 as I,j9 as J,M9 as K,k9 as L,j0 as M,e2 as N,$5 as O,U4 as P,X4 as Q,Y4 as R,H4 as S,W4 as T,Q4 as U,O4 as V,Z5 as W,B4 as X,KT as Y,$4 as Z,Uj as _,dO as $,Xj as aa,Yj as ba,Hj as ca};
|