blade-code 0.10.18 → 0.10.20
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-nddkzabm.js → chunk-0y0wbjyf.js} +1 -1
- package/dist/chunk-4544fy5s.js +1 -0
- package/dist/{chunk-jsey85bn.js → chunk-619rxqh6.js} +1 -1
- package/dist/{chunk-xyzhpd3j.js → chunk-7pkscxbb.js} +1 -1
- package/dist/{chunk-2rkdyx6m.js → chunk-7wx9vt15.js} +1 -1
- package/dist/{chunk-ae66ffh3.js → chunk-83jkb44s.js} +2 -2
- package/dist/{chunk-dc094tzc.js → chunk-8mp5qg8q.js} +1 -1
- package/dist/{chunk-4g5wvaa9.js → chunk-a5ncqsat.js} +1 -1
- package/dist/{chunk-88n14h5d.js → chunk-axe8621t.js} +1 -1
- package/dist/{chunk-cx0yycfr.js → chunk-bffw1t7e.js} +1 -1
- package/dist/{chunk-9xpq3a19.js → chunk-bv7e8221.js} +1 -1
- package/dist/{chunk-pq1p9jz6.js → chunk-e37k44j1.js} +1 -1
- package/dist/{chunk-1gqmy8aq.js → chunk-eakfkjk4.js} +1 -1
- package/dist/{chunk-s7cp67vw.js → chunk-ehgfwwqk.js} +1 -1
- package/dist/{chunk-j0wssvjp.js → chunk-eq5kb8m9.js} +1 -1
- package/dist/{chunk-qnnyasc0.js → chunk-f6a1grte.js} +1 -1
- package/dist/{chunk-hatwwhm2.js → chunk-fbnetqrz.js} +1 -1
- package/dist/{chunk-0ke6fsmy.js → chunk-h1b6wehr.js} +1 -1
- package/dist/{chunk-yn2fvjfm.js → chunk-h41b8965.js} +1 -1
- package/dist/chunk-htarfekt.js +200 -0
- package/dist/{chunk-wbxv9wcn.js → chunk-j9vqys2g.js} +1 -1
- package/dist/{chunk-1re8nwdc.js → chunk-kf56q9zs.js} +1 -1
- package/dist/{chunk-19z401aq.js → chunk-n00q74bt.js} +1 -1
- package/dist/{chunk-c6t2nt3v.js → chunk-nqd6t5t7.js} +1 -1
- package/dist/{chunk-eb6d2sqj.js → chunk-q6ev6t06.js} +1 -1
- package/dist/{chunk-nbx7kcwy.js → chunk-w6azkwgq.js} +1 -1
- package/dist/{chunk-awnrm721.js → chunk-wmttq8eq.js} +1 -1
- package/dist/{chunk-n8egkfa0.js → chunk-xfr5z6pz.js} +1 -1
- package/dist/{chunk-h7pregxp.js → chunk-xpt6cdn8.js} +1 -1
- package/dist/{chunk-a43d70k9.js → chunk-z2fn2yg8.js} +1 -1
- package/dist/{chunk-jba4g4y1.js → chunk-zqf8043h.js} +6 -6
- package/dist/{chunk-xn02evty.js → chunk-zvdervx9.js} +1 -1
- package/dist/{chunk-agsvdf45.js → chunk-zzkdr84r.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-h18y4067.js +0 -200
- package/dist/chunk-nke2117v.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{ca as j,da as x0,ia as KJ,ja as O8,ka as P0}from"./chunk-
|
|
1
|
+
import{ca as j,da as x0,ia as KJ,ja as O8,ka as P0}from"./chunk-eakfkjk4.js";import{Ea as J7,la as $7,na as Z7,oa as r6}from"./chunk-qt114yth.js";import{Fa as _$,Ga as o1,Ha as eZ,Ia as E1,Ja as Z8,Ka as J8,La as U8,Oa as V2,Qa as $6,Ra as E2,Sa as _2,Va as r0,Ya as Q0,cb as M2,db as YJ,eb as M9,gb as G8,ob as M8}from"./chunk-htarfekt.js";import{pb as g8,qb as p8,rb as J2}from"./chunk-095x2ykj.js";import{$b as l9,Jb as A2,Kb as V0,Lb as p0,Mb as p2,Nb as c$,Ob as p9,Pb as i9,Sb as VJ,Wb as f8,_b as c9,bc as c,xb as X0,yb as m9,zb as g9}from"./chunk-q6ev6t06.js";import{cc as Y7,fc as H7,nc as z7,tc as Q7}from"./chunk-8rzwyknk.js";import{Ec as g4,Fc as d4}from"./chunk-k3nkcaap.js";import{$c as M$,Rc as O2,Sc as z0,Tc as P,Wc as W0,Xc as X2,Yc as n$,Zc as F$,_c as B6,ad as T8,fd as p$}from"./chunk-bffw1t7e.js";import{gd as k$}from"./chunk-6pa6c2n0.js";import{hd as Y$}from"./chunk-yz2bsntj.js";import{nd as t9,od as Y2}from"./chunk-xet98pc1.js";import{qd as A0,rd as j$}from"./chunk-kbpc97n3.js";import{sd as zJ}from"./chunk-5chec8rs.js";import{ud as y9,vd as x9,wd as h9}from"./chunk-f6a1grte.js";import{Ad as L$,Bd as r8,Dd as C0,Ed as q7,Fd as S0,Gd as h0,Hd as r2,Id as N2,Jd as $$,Kd as u$,Ld as d$,Md as d9,Nd as M6,Pd as $0,Qd as H2,Rd as r9,xd as W2,yd as B2}from"./chunk-0y0wbjyf.js";import{Td as a$,Vd as q$,Wd as s1}from"./chunk-r1jxbx1h.js";import{$d as p4,Xd as TJ,Zd as u9,_d as L2}from"./chunk-6sb7cg95.js";import{be as g6,de as K0}from"./chunk-j9vqys2g.js";import{ee as u0}from"./chunk-q3c07kb4.js";import{ie as g}from"./chunk-6207mbmr.js";import{Be as C4,De as P9,Fe as oZ,Ge as tZ,Ne as K4,Oe as a9,Pe as v9,Qe as F8,Re as q8,Se as w8,Te as D8,Ue as b8,Ve as L8,We as e,le as f4,qe as M4,se as x6,xe as GJ}from"./chunk-e37k44j1.js";import{af as I1,bf as B4,cf as _,df as a8,ef as S,ff as m}from"./chunk-96h588rd.js";import{hf as T9,if as f9}from"./chunk-3qhqbj09.js";import{kf as u1,mf as A}from"./chunk-prgh321y.js";import{qf as I9,rf as k9}from"./chunk-jpwfq49n.js";import{sf as MJ,vf as NJ}from"./chunk-yqfqj7mh.js";import{zf as PJ}from"./chunk-fbnetqrz.js";import{Ef as f0}from"./chunk-1n60pgsq.js";import{Hf as X7,Jf as P$,Lf as S9,Mf as W4,Of as O0}from"./chunk-yvf4nmds.js";import{Qf as t0}from"./chunk-6g5k5de1.js";import{randomUUID as T7}from"crypto";import{mkdir as S1,realpath as m2}from"node:fs/promises";import D7 from"node:os";import W$ from"node:path";import{Mutex as b7}from"async-mutex";var o6=new b7,B$,u2;function L7(){return import("@anthropic-ai/sandbox-runtime")}async function X1(){if(B$)return B$;if(!u2)u2=L7();return B$=await u2,B$}var A7={isSupportedPlatform:async()=>(await X1()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await X1()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await X1()).getDefaultWritePaths(),initialize:async($)=>(await X1()).SandboxManager.initialize($),updateConfig:($)=>{if(!B$)throw Error("Sandbox runtime is not initialized");B$.SandboxManager.updateConfig($)},wrapWithSandboxArgv:async($,Z,J,U,X)=>(await X1()).SandboxManager.wrapWithSandboxArgv($,Z,J,U,X),cleanupAfterCommand:()=>B$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await B$?.SandboxManager.reset()}};function d2($){return{network:{allowedDomains:$,deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0}}class T$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class m$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class t6{backend;constructor($){this.backend=$}async prepare($){let Z=W$.resolve($.workspaceRoot),J=W$.resolve($.cwd);if(!X0.isWithinWorkspace(J,Z))throw new m$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let U,X;try{[U,X]=await Promise.all([m2(Z),m2(J)])}catch(Y){throw new m$(`Workspace sandbox path cannot be resolved: ${Y instanceof Error?Y.message:String(Y)}`)}if(!X0.isWithinWorkspace(X,U))throw new m$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:X,workspaceRoot:U})}}class e6{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??A7,this.tempRoot=$.tempRoot??W$.join(O0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=W$.join(Z,"tmp"),U=W$.join(Z,"cache"),X=W$.join(U,"npm"),Y=W$.join(U,"bun");await Promise.all([S1(J,{recursive:!0}),S1(X,{recursive:!0}),S1(Y,{recursive:!0})]);let z=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((F)=>!F.startsWith("/dev/")),Q=$.access==="workspace-read-only",W=Q?[D7.homedir(),O0(),process.env.BLADE_REAL_API_CREDENTIALS_FILE].filter((F)=>typeof F==="string"&&F.trim().length>0).map((F)=>W$.resolve(F)).filter((F,w,q)=>q.indexOf(F)===w):[],B=process.platform==="win32"?"bash":"/bin/bash",V,E,O=()=>{if(!E)return;let F=E;E=void 0;try{this.runtime.updateConfig(d2(["*"]))}finally{F()}},G=async()=>{let F=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,B,{network:Q?{allowedDomains:[],deniedDomains:[],strictAllowlist:!0}:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:W,allowRead:Q?[$.workspaceRoot]:[],allowWrite:Q?[Z]:[$.workspaceRoot,Z],denyWrite:Q?[$.workspaceRoot,...z]:z},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(F===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=F}};try{if(Q)E=await o6.acquire(),this.runtime.updateConfig(d2([])),V=await G();else V=await o6.runExclusive(G)}catch(F){if(O(),F instanceof Error&&F.name==="AbortError")throw F;throw new T$(`Workspace sandbox failed to prepare the command: ${F instanceof Error?F.message:String(F)}`)}let K=!1;return{executable:V.argv[0]??B,args:V.argv.slice(1),env:{...V.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:U,npm_config_cache:X,BUN_INSTALL_CACHE_DIR:Y},sandboxed:!0,inheritProcessEnv:!Q,cleanup:()=>{if(K)return;K=!0;try{this.runtime.cleanupAfterCommand()}finally{O()}}}}async dispose(){this.initialization=void 0,await this.runtime.reset()}async ensureInitialized(){if(!this.initialization)this.initialization=this.initializeRuntime().catch(($)=>{throw this.initialization=void 0,$});return this.initialization}async initializeRuntime(){if(!await this.runtime.isSupportedPlatform())throw new T$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new T$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize(d2(["*"]))}catch(Z){throw new T$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await S1(this.tempRoot,{recursive:!0}),m2(this.tempRoot)}}function P1($,Z){let J=Z.toLowerCase();return $===71&&J.includes("sandbox-exec")||J.includes("sandbox_apply: operation not permitted")||J.includes("bwrap: creating new namespace failed")||J.includes("failed to create new user namespace")||J.includes("srt-win sandbox failed")}var N7=new e6,j7={prepare:($)=>N7.prepare($)},g2=new t6(j7);class t{static instance=null;processes=new Map;static getInstance(){if(!t.instance)t.instance=new t;return t.instance}startBackgroundProcess($){let Z=`bash_${T7()}`,J={};for(let[Q,W]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(W!==void 0)J[Q]=W;let U=$.sandboxedCommand?.executable??"bash",X=$.sandboxedCommand?.args??["-c",$.command],{child:Y,processTree:H}=u0(U,X,{cwd:$.cwd||A(),env:J,stdio:["pipe","pipe","pipe"]}),z={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:Y,processTree:H,pid:Y.pid,status:"running",startTime:Date.now(),pendingStdout:new p2,pendingStderr:new p2,sandboxed:Boolean($.sandboxedCommand)};return Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(Q)=>{z.pendingStdout.append(Q)}),Y.stderr?.on("data",(Q)=>{z.pendingStderr.append(Q)}),Y.on("close",(Q,W)=>{$.sandboxedCommand?.cleanup();let B=z.sandboxed&&P1(Q,z.pendingStderr.peek().content);if(z.status=z.status==="killed"?"killed":B?"error":"exited",z.exitCode=Q,z.signal=W,B)z.errorMessage="Workspace sandbox failed to start; command was not executed";z.endTime=Date.now(),z.process=void 0}),Y.on("error",(Q)=>{$.sandboxedCommand?.cleanup(),z.status="error",z.errorMessage=Q.message,z.endTime=Date.now(),z.process=void 0,z.pendingStderr.append(`
|
|
2
2
|
[error] ${Q.message}`)}),this.processes.set(Z,z),z}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;let U=J.pendingStdout.consume(),X=J.pendingStderr.consume();return{id:J.id,command:J.command,status:J.status,stdout:U.content,stderr:X.content,stdoutOmittedBytes:U.omittedBytes,stderrOmittedBytes:X.omittedBytes,exitCode:J.exitCode,signal:J.signal,pid:J.pid,startedAt:J.startTime,endedAt:J.endTime,errorMessage:J.errorMessage,sandboxed:J.sandboxed}}getProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$)}async writeInput($,Z,J,U=!1){let X=this.getProcess($,Z);if(!X)return;let Y=X.process?.stdin;if(X.status!=="running"||!Y||Y.destroyed||Y.writableEnded)return{success:!1,status:X.status,bytesWritten:0,stdinClosed:!Y||Y.destroyed||Y.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((H,z)=>{let Q=(B)=>{Y.off("error",Q),z(B)},W=(B)=>{if(Y.off("error",Q),B)z(B);else H()};if(Y.once("error",Q),U)Y.end(J,W);else Y.write(J,W)}),{success:!0,status:X.status,bytesWritten:Buffer.byteLength(J),stdinClosed:U}}catch(H){return{success:!1,status:X.status,bytesWritten:0,stdinClosed:Y.destroyed||Y.writableEnded,errorMessage:H instanceof Error?H.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getProcess($,Z);if(!J)return;return this.terminateProcess(J)}async killSession($){let Z=this.listForSession($);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}async terminateProcess($){if($.status!=="running"||!$.process)return{success:!1,alreadyExited:!0,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};$.status="killed",$.endTime=Date.now();let Z=await $.processTree?.terminate();if(!Z?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:Z?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return{success:!0,alreadyExited:Z.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}}import{stat as qH}from"node:fs/promises";import{Mutex as wH}from"async-mutex";import{nanoid as DH}from"nanoid";import*as n9 from"os";import*as U0 from"path";import*as k0 from"fs/promises";class f${async readTextFile($){return k0.readFile($,"utf-8")}async writeTextFile($,Z){await k0.writeFile($,Z,"utf-8")}async exists($){try{return await k0.access($),!0}catch{return!1}}async readBinaryFile($){return k0.readFile($)}async stat($){try{let Z=await k0.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await k0.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var f7=new f$;function V$(){return f7}var D0=g("Agent");class Y1{connection;sessionId;capabilities;fallback;constructor($,Z,J,U=new f$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=U}async readTextFile($){if(!this.capabilities.readTextFile)return D0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return D0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw D0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return D0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{D0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw D0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return D0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),D0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((H)=>J.includes(H)))return D0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=M7(J);return D0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return D0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return D0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return D0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}}function M7($){if($.includes("permission")||$.includes("access denied"))return"permission";if($.includes("timeout")||$.includes("timed out"))return"timeout";if($.includes("binary")||$.includes("encoding"))return"binary";if($.includes("too large")||$.includes("size"))return"size";if($.includes("connection")||$.includes("network"))return"network";return"unknown"}var d0=g("Agent");class i2{async execute($,Z){return new Promise((J)=>{let U=process.platform==="win32"?"cmd.exe":"/bin/bash",X=process.platform==="win32"?["/c",$]:["-c",$],{child:Y,processTree:H}=u0(U,X,{cwd:Z?.cwd||A(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),z,Q=()=>{return z??=H.terminate(),z},W="",B="",V=!1,E=Z?.timeout?setTimeout(()=>{V=!0,Q()},Z.timeout):null,O=null,G=()=>{if(E)clearTimeout(E);if(O&&Z?.signal)Z.signal.removeEventListener("abort",O),O=null};if(Z?.signal){if(O=()=>{V=!0,Q()},Z.signal.addEventListener("abort",O),Z.signal.aborted)O()}Y.stdout?.on("data",(K)=>{let F=K.toString();W+=F,Z?.onOutput?.(F)}),Y.stderr?.on("data",(K)=>{let F=K.toString();B+=F,Z?.onOutput?.(F)}),Y.on("close",async(K)=>{if(G(),V)await Q();J({success:K===0&&!V,stdout:W,stderr:B,exitCode:K,error:V?"Command was terminated":void 0})}),Y.on("error",(K)=>{G(),J({success:!1,stdout:W,stderr:B,exitCode:null,error:K.message})})})}isAvailable(){return!0}}class $4{connection;sessionId;fallback;constructor($,Z,J=new i2){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{d0.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([W,B])=>({name:W,value:B})):void 0}),U=0,X=null;if(Z?.onOutput)X=setInterval(async()=>{try{let B=(await J.currentOutput()).output||"";if(B.length>U){let V=B.slice(U);U=B.length,Z.onOutput?.(V)}}catch{}},100);let Y=(W=!1)=>{if(X)clearInterval(X),X=null;(W?J.kill().then(()=>d0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},H=[];if(H.push(J.waitForExit().then((W)=>({type:"completed",exitCode:W.exitCode??null}))),Z?.timeout)H.push(new Promise((W)=>{setTimeout(()=>W({type:"timeout"}),Z.timeout)}));if(Z?.signal)H.push(new Promise((W)=>{if(Z.signal.aborted)W({type:"aborted"});else Z.signal.addEventListener("abort",()=>W({type:"aborted"}),{once:!0})}));let z=await Promise.race(H),Q="";try{if(Q=(await J.currentOutput()).output||"",Z?.onOutput&&Q.length>U)Z.onOutput(Q.slice(U))}catch{}switch(z.type){case"completed":return Y(!1),{success:z.exitCode===0,stdout:Q,stderr:"",exitCode:z.exitCode};case"timeout":return d0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),Y(!0),{success:!1,stdout:Q,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return d0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),Y(!0),{success:!1,stdout:Q,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){if(Z?.allowLocalFallback===!1)return{success:!1,stdout:"",stderr:"",exitCode:null,error:J instanceof Error?`ACP terminal unavailable: ${J.message}`:"ACP terminal unavailable"};return d0.warn("[AcpTerminal] ACP terminal failed, using fallback:",J),this.fallback.execute($,Z)}}isAvailable(){return!0}}class y{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new y}static initializeSession($,Z,J,U){let X=J?.fs?new Y1($,Z,J.fs):new f$;if(J?.fs)d0.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let Y=new $4($,Z);d0.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),y.sessions.set(Z,{fileSystemService:X,terminalService:Y,connection:$,clientCapabilities:J||null,cwd:U}),y.currentSessionId=Z,d0.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:U})}static destroySession($){if(y.sessions.delete($),y.currentSessionId===$){let Z=Array.from(y.sessions.keys());y.currentSessionId=Z[0]||null}d0.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return y.sessions.get($)||null}static setCurrentSession($){if(y.sessions.has($))y.currentSessionId=$}static getCurrentSessionId(){return y.currentSessionId}initialize($,Z,J,U){y.initializeSession($,Z,J,U||A())}reset(){if(y.currentSessionId)y.destroySession(y.currentSessionId)}isAcpMode(){return y.currentSessionId!==null}getFileSystemService($){let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.fileSystemService}return new f$}getTerminalService($){let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.terminalService}return new i2}getConnection(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.connection}return null}getSessionId(){return y.currentSessionId}getClientCapabilities(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,U,X){let Y=y.currentSessionId;if(!Y)return;let H=y.sessions.get(Y);if(!H)return;try{await H.connection.sessionUpdate({sessionId:Y,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:U||[],kind:X||"other"}})}catch(z){d0.warn("[AcpServiceContext] Failed to send tool update:",z)}}}function E$($){return y.getInstance().getFileSystemService($)}function Z4($){return y.getInstance().getTerminalService($)}function a($){return $?y.getSessionServices($)!==null:y.getInstance().isAcpMode()}import*as m0 from"node:fs/promises";import*as V4 from"node:path";import{Mutex as C7}from"async-mutex";import{nanoid as R7}from"nanoid";import S7 from"write-file-atomic";var J4=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],U4=["pending","pass","fail","partial"];var X4=1048576,c2=1e5,E4=4000,P7=_.Object({attempt:_.Integer({minimum:1}),status:m(U4),requestedAt:_.String({format:"date-time"}),completedAt:_.Optional(_.String({format:"date-time"})),verifierSessionId:_.Optional(_.String({minLength:1})),summary:_.Optional(_.String({maxLength:E4})),evidenceSha256:_.Optional(_.String({pattern:"^[a-f0-9]{64}$"}))}),Y4=_.Object({version:_.Literal(1),sessionId:_.String({minLength:1}),goalId:_.String({minLength:1}),objective:_.String({minLength:1,maxLength:c2}),status:m(J4),tokenBudget:_.Optional(_.Integer({minimum:1})),tokensUsed:_.Integer({minimum:0}),timeUsedSeconds:_.Integer({minimum:0}),continuationCount:_.Integer({minimum:0}),statusReason:_.Optional(_.String()),completionVerification:_.Optional(P7),createdAt:_.String({format:"date-time"}),updatedAt:_.String({format:"date-time"})});function H4($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function z4($){let Z=$.trim();if(!Z)throw Error("Goal objective must not be empty");if(Z.length>c2)throw Error(`Goal objective exceeds ${c2} characters`);return Z}function I7($){if($===void 0)return;if(!Number.isInteger($)||$<=0)throw Error("Goal token budget must be a positive integer");return $}function Q4($){let Z=$?.trim();if(!Z)return;return Z.slice(0,E4)}class T0{workspaceRoot;sessionId;static mutexes=new Map;static listeners=new Set;filePath;mutex;constructor($,Z){this.workspaceRoot=$;this.sessionId=Z;this.filePath=W4($,Z);let J=T0.mutexes.get(this.filePath);if(!J)J=new C7,T0.mutexes.set(this.filePath,J);this.mutex=J}static subscribe($){return this.listeners.add($),()=>this.listeners.delete($)}static async hasActiveGoal($,Z){let J=(await new T0($,Z).get())?.status;return J==="active"||J==="verifying"}async get(){return this.mutex.runExclusive(()=>this.readUnlocked())}async create($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(Z&&Z.status!=="complete")throw Error(`Session already has an unfinished goal (${Z.status}); clear or complete it first`);let J=new Date().toISOString(),U=I7($.tokenBudget),X={version:1,sessionId:this.sessionId,goalId:R7(12),objective:z4($.objective),status:"active",...U===void 0?{}:{tokenBudget:U},tokensUsed:0,timeUsedSeconds:0,continuationCount:0,createdAt:J,updatedAt:J};return await this.persistUnlocked(X),this.emit(X),X})}async edit($){return this.updateExisting((Z)=>{if(!["active","verifying","paused","blocked"].includes(Z.status))throw Error(`Cannot edit goal while status is ${Z.status}`);return{...Z,objective:z4($),completionVerification:void 0,status:Z.status==="verifying"?"active":Z.status,statusReason:Z.status==="verifying"?void 0:Z.statusReason,updatedAt:new Date().toISOString()}})}async pause($="paused by user"){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying"&&Z.status!=="blocked")throw Error(`Cannot pause goal while status is ${Z.status}`);return{...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()}})}async pauseIfActive($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J={...Z,status:"paused",statusReason:$,updatedAt:new Date().toISOString()};return await this.persistUnlocked(J),this.emit(J),J})}async resume(){return this.updateExisting(($)=>{if($.status!=="paused"&&$.status!=="blocked")throw Error(`Cannot resume goal while status is ${$.status}`);let Z=$.completionVerification?.status==="pending"||$.completionVerification?.status==="pass";return{...$,status:Z?"verifying":"active",statusReason:void 0,updatedAt:new Date().toISOString()}})}async requestCompletion(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot request goal completion while status is ${$.status}`);if($.status==="verifying"&&($.completionVerification?.status==="pending"||$.completionVerification?.status==="pass"))return $;let Z=new Date().toISOString();return{...$,status:"verifying",statusReason:"awaiting independent completion verification",completionVerification:{attempt:($.completionVerification?.attempt??0)+1,status:"pending",requestedAt:Z},updatedAt:Z}})}async recordCompletionVerification($){let Z=$.verifierSessionId?.trim();if(!Z)throw Error("Goal verification requires a verifier Session identity");if(!/^[a-f0-9]{64}$/.test($.evidenceSha256??""))throw Error("Goal verification requires a SHA-256 evidence digest");return this.updateExisting((J)=>{if(J.status!=="verifying"||!J.completionVerification)throw Error(`Cannot record goal verification while status is ${J.status}`);let U=new Date().toISOString();return{...J,statusReason:$.verdict==="pass"?"independent completion verification passed":`independent completion verification returned ${$.verdict}`,completionVerification:{...J.completionVerification,status:$.verdict,completedAt:U,verifierSessionId:Z,...Q4($.summary)?{summary:Q4($.summary)}:{},evidenceSha256:$.evidenceSha256},updatedAt:U}})}async invalidateCompletionVerification($){return this.updateExisting((Z)=>{if(Z.status!=="verifying"||!Z.completionVerification)return Z;let J=$.trim()||"goal completion evidence became stale";return{...Z,statusReason:J,completionVerification:{attempt:Z.completionVerification.attempt,status:"pending",requestedAt:Z.completionVerification.requestedAt},updatedAt:new Date().toISOString()}})}async finalizeVerifiedCompletion(){return this.updateExisting(($)=>{if($.status!=="verifying"||$.completionVerification?.status!=="pass"||!$.completionVerification.verifierSessionId||!$.completionVerification.evidenceSha256)throw Error("Goal completion requires a persisted independent PASS verdict");return{...$,status:"complete",statusReason:void 0,updatedAt:new Date().toISOString()}})}async block($){return this.updateExisting((Z)=>{if(Z.status!=="active"&&Z.status!=="verifying")throw Error(`Cannot block goal while status is ${Z.status}`);let J=$.trim();if(!J)throw Error("Blocked goal requires a reason");return{...Z,status:"blocked",statusReason:J,completionVerification:void 0,updatedAt:new Date().toISOString()}})}async recordProgress($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z||Z.status!=="active"&&Z.status!=="verifying")return Z;let J=Math.max(0,Math.round($.tokens)),U=Math.max(0,Math.round($.elapsedMs/1000)),X=Z.tokensUsed+J,Y=Z.tokenBudget!==void 0&&X>=Z.tokenBudget,H={...Z,tokensUsed:X,timeUsedSeconds:Z.timeUsedSeconds+U,status:Y?"budget_limited":Z.status,statusReason:Y?"token budget exhausted":Z.statusReason,updatedAt:new Date().toISOString()};return await this.persistUnlocked(H),this.emit(H),H})}async beginContinuation(){return this.updateExisting(($)=>{if($.status!=="active"&&$.status!=="verifying")throw Error(`Cannot continue goal while status is ${$.status}`);return{...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()}})}async tryBeginContinuation(){return this.mutex.runExclusive(async()=>{let $=await this.readUnlocked();if(!$||$.status!=="active"&&$.status!=="verifying")return null;let Z={...$,continuationCount:$.continuationCount+1,updatedAt:new Date().toISOString()};return await this.persistUnlocked(Z),this.emit(Z),Z})}async clear(){return this.mutex.runExclusive(async()=>{try{await m0.unlink(this.filePath)}catch($){if(H4($,"ENOENT"))return!1;throw $}return this.emit(null),!0})}async updateExisting($){return this.mutex.runExclusive(async()=>{let Z=await this.readUnlocked();if(!Z)throw Error("Session has no goal");let J=B4(Y4,$(Z));return await this.persistUnlocked(J),this.emit(J),J})}async readUnlocked(){try{if((await m0.stat(this.filePath)).size>X4)throw Error(`Goal state exceeds ${X4} bytes`);await m0.chmod(this.filePath,384);let Z=I1(Y4,JSON.parse(await m0.readFile(this.filePath,"utf8")));if(!Z.success||Z.data.sessionId!==this.sessionId)throw Error(`Invalid goal state: ${this.filePath}`);return Z.data}catch($){if(H4($,"ENOENT"))return null;if($ instanceof SyntaxError)throw Error(`Invalid goal state JSON: ${this.filePath}`,{cause:$});throw $}}async persistUnlocked($){await m0.mkdir(V4.dirname(this.filePath),{recursive:!0,mode:448}),await S7(this.filePath,`${JSON.stringify($)}
|
|
3
3
|
`,{encoding:"utf8",mode:384,fsync:!0})}emit($){let Z={workspaceRoot:this.workspaceRoot,sessionId:this.sessionId,goal:$?{...$}:null};for(let J of T0.listeners)try{J(Z)}catch{}}}import{createHash as k7}from"node:crypto";import{promises as k1,realpathSync as v7}from"node:fs";import l from"node:path";import{fileURLToPath as y7,pathToFileURL as e0}from"node:url";var _4=g("Service"),O4=65536;class l2{name;onCrash;child;processTree;connection;closePromise;crashCleanup;capabilities;initialized=!1;stopping=!1;notificationHandlers=new Map;requestHandlers=new Map;constructor($,Z){this.name=$;this.onCrash=Z}get serverCapabilities(){return this.capabilities}get isInitialized(){return this.initialized}async start($){if(await this.crashCleanup,this.crashCleanup=void 0,this.connection)return;let Z=await import("vscode-jsonrpc/node.js"),{child:J,processTree:U}=u0($.command,[...$.args],{cwd:$.cwd,env:{...$.environment,PATH:$.environment.PATH??process.env.PATH??"",HOME:$.environment.HOME??process.env.HOME??"",USER:$.environment.USER??process.env.USER??"",SHELL:$.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},{releaseOnExit:!1});this.child=J,this.processTree=U;try{if(await new Promise((H,z)=>{let Q=()=>{J.removeListener("spawn",W),J.removeListener("error",B)},W=()=>{Q(),H()},B=(V)=>{Q(),z(V)};J.once("spawn",W),J.once("error",B)}),!J.stdout||!J.stdin)throw Error("LSP server stdio is unavailable");let X="";J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(H)=>{if(X.length<O4)X+=H.slice(0,O4-X.length)}),J.stdin.on("error",(H)=>{if(!this.stopping)_4.debug(`[LSP ${this.name}] stdin closed: ${H.message}`)}),this.closePromise=new Promise((H)=>{J.once("close",(z,Q)=>{this.initialized=!1;let W=!this.stopping;if(!this.stopping){let B=X.trim()?`: ${X.trim().slice(0,512)}`:Q?` (${Q})`:"";this.onCrash(Error(`LSP server "${this.name}" exited with code ${z}${B}`))}if(this.child===J){let B=this.processTree;try{this.connection?.dispose()}catch{}if(this.connection=void 0,this.child=void 0,this.closePromise=void 0,W&&B)this.crashCleanup=B.terminate().then(()=>{return}),this.processTree=void 0}H()})});let Y=Z.createMessageConnection(new Z.StreamMessageReader(J.stdout),new Z.StreamMessageWriter(J.stdin));this.connection=Y,Y.onError(([H])=>{if(!this.stopping)_4.warn(`[LSP ${this.name}] connection error: ${H.message}`)}),Y.onClose(()=>{this.initialized=!1});for(let[H,z]of this.notificationHandlers)for(let Q of z)Y.onNotification(H,Q);for(let[H,z]of this.requestHandlers)Y.onRequest(H,z);Y.listen()}catch(X){throw await this.disposeTransport(),X}}async initialize($,Z,J){let U=await this.request("initialize",$,Z,J,!1);return this.capabilities=U.capabilities,await this.notify("initialized",{}),this.initialized=!0,U}async request($,Z,J,U,X=!0){let Y=this.connection;if(!Y)throw Error(`LSP server "${this.name}" is not started`);if(X&&!this.initialized)throw Error(`LSP server "${this.name}" is not initialized`);let z=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;return this.awaitRequest(Y.sendRequest($,Z,z.token),z,J,U,$)}async notify($,Z){if(!this.connection)throw Error(`LSP server "${this.name}" is not started`);await this.connection.sendNotification($,Z)}onNotification($,Z){let J=this.notificationHandlers.get($)??[];J.push(Z),this.notificationHandlers.set($,J),this.connection?.onNotification($,Z)}onRequest($,Z){this.requestHandlers.set($,Z),this.connection?.onRequest($,Z)}async stop($){if(!this.child&&!this.connection){await this.crashCleanup,this.crashCleanup=void 0;return}this.stopping=!0;let Z=this.connection;try{if(Z&&this.initialized){let U=new(await import("vscode-jsonrpc/node.js")).CancellationTokenSource;await this.awaitRequest(Z.sendRequest("shutdown",U.token),U,$,void 0,"shutdown").catch(()=>{return}),await Z.sendNotification("exit").catch(()=>{return})}await Promise.race([this.closePromise??Promise.resolve(),new Promise((J)=>setTimeout(J,Math.min($,500)))])}finally{await this.disposeTransport(),this.stopping=!1,this.initialized=!1,this.capabilities=void 0}}awaitRequest($,Z,J,U,X){return new Promise((Y,H)=>{let z=!1,Q=(V)=>{if(z)return;z=!0,clearTimeout(B),U?.removeEventListener("abort",W),V()},W=()=>{Z.cancel(),Q(()=>H(Error(`LSP request "${X}" was aborted`)))},B=setTimeout(()=>{Z.cancel(),Q(()=>H(Error(`LSP request "${X}" timed out after ${J}ms`)))},J);if(U?.addEventListener("abort",W,{once:!0}),U?.aborted)W();$.then((V)=>Q(()=>Y(V)),(V)=>Q(()=>H(V)))})}async disposeTransport(){let $=this.connection,Z=this.processTree;this.connection=void 0,this.processTree=void 0,this.child=void 0,this.closePromise=void 0;try{$?.dispose()}catch{}await Z?.terminate(),await this.crashCleanup,this.crashCleanup=void 0}}var x7=g("Service"),h7=10485760,u7=10,G4=30,d7=-32801;class n2{options;workspaceRoot;servers=new Map;diagnostics=new Map;delivered=new Map;waiters=new Map;disposeController=new AbortController;diagnosticSequence=0;disposed=!1;constructor($){this.options=$;let Z=l.resolve($.workspaceRoot);try{this.workspaceRoot=v7.native(Z)}catch{this.workspaceRoot=Z}for(let[J,U]of Object.entries($.servers)){if(U.enabled===!1)continue;let X={name:J,config:structuredClone(U),state:"stopped",restartCount:0,openedFiles:new Map,client:new l2(J,(Y)=>{X.state="error",X.lastError=Y.message,X.openedFiles.clear()})};X.client.onNotification("textDocument/publishDiagnostics",(Y)=>{this.captureDiagnostics(J,Y)}),X.client.onRequest("workspace/configuration",(Y)=>this.resolveWorkspaceConfiguration(U.settings,Y)),X.client.onRequest("workspace/workspaceFolders",()=>[{uri:e0(this.workspaceRoot).href,name:l.basename(this.workspaceRoot)}]),X.client.onRequest("window/workDoneProgress/create",()=>null),this.servers.set(J,X)}}get available(){return this.servers.size>0&&!this.isRemoteSession()&&!this.disposed}get workspacePath(){return this.workspaceRoot}getStatus(){return[...this.servers.values()].map(($)=>({name:$.name,state:$.state,restartCount:$.restartCount,extensions:Object.keys($.config.extensionToLanguage).sort(),...$.lastError?{lastError:$.lastError}:{}})).sort(($,Z)=>$.name.localeCompare(Z.name))}async afterToolUse($,Z,J,U){if(!this.available||this.disposed)return;let X;if(J.success&&($==="Write"||$==="Edit")&&typeof Z.file_path==="string")X=await this.syncAfterWrite(Z.file_path,U.signal);else if(J.success&&$==="ApplyPatch"){let Y=Array.isArray(J.metadata?.changes)?J.metadata.changes:[];for(let H of Y){if(!H||typeof H!=="object"||!("path"in H)||typeof H.path!=="string")continue;if("newContent"in H&&H.newContent===null)await this.syncAfterDelete(H.path);else X=await this.syncAfterWrite(H.path,U.signal)??X}}this.attachPendingDiagnostics(J,X)}async query($,Z){if(!this.available)throw Error(this.isRemoteSession()?"LSP is unavailable for ACP-owned remote files":"No LSP servers are configured for this Session");let J=await this.resolveFile($.filePath);if($.operation==="diagnostics")return{operation:$.operation,filePath:J,result:this.getCurrentDiagnostics(J)};let U=await this.ensureFileOpen(J,void 0,Z);if(!U)throw Error(`No LSP server handles ${l.extname(J)||"this file"}`);let X={line:Math.max(0,($.line??1)-1),character:Math.max(0,($.character??1)-1)},Y={uri:e0(J).href},H={goToDefinition:{method:"textDocument/definition",params:{textDocument:Y,position:X}},findReferences:{method:"textDocument/references",params:{textDocument:Y,position:X,context:{includeDeclaration:!0}}},hover:{method:"textDocument/hover",params:{textDocument:Y,position:X}},documentSymbol:{method:"textDocument/documentSymbol",params:{textDocument:Y}},workspaceSymbol:{method:"workspace/symbol",params:{query:$.query??""}},goToImplementation:{method:"textDocument/implementation",params:{textDocument:Y,position:X}},prepareCallHierarchy:{method:"textDocument/prepareCallHierarchy",params:{textDocument:Y,position:X}}},z;if($.operation==="incomingCalls"||$.operation==="outgoingCalls"){let W=(await this.requestWithRetry(U,"textDocument/prepareCallHierarchy",{textDocument:Y,position:X},Z))?.[0];z=W?await this.requestWithRetry(U,$.operation==="incomingCalls"?"callHierarchy/incomingCalls":"callHierarchy/outgoingCalls",{item:W},Z):[]}else{let Q=H[$.operation];z=await this.requestWithRetry(U,Q.method,Q.params,Z)}return{operation:$.operation,filePath:J,serverName:U.name,result:z}}async dispose(){if(this.disposed)return;this.disposed=!0,this.disposeController.abort();for(let $ of this.waiters.values())for(let Z of $)clearTimeout(Z.timer),Z.resolve();this.waiters.clear(),await Promise.allSettled([...this.servers.values()].map(async($)=>{$.state="stopping",await $.client.stop($.config.shutdownTimeout??2000),$.state="stopped",$.openedFiles.clear()})),this.diagnostics.clear(),this.delivered.clear()}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}selectServer($){let Z=l.extname($).toLowerCase();return[...this.servers.values()].filter((J)=>(Z in J.config.extensionToLanguage)).sort((J,U)=>(U.config.priority??0)-(J.config.priority??0)||J.name.localeCompare(U.name))[0]}async ensureFileOpen($,Z,J){let U=this.selectServer($);if(!U)return;await this.ensureStarted(U,J);let X=e0($).href;if(U.openedFiles.has(X))return U;let Y=Z??await this.readBoundedFile($);return await U.client.notify("textDocument/didOpen",{textDocument:{uri:X,languageId:U.config.extensionToLanguage[l.extname($).toLowerCase()],version:1,text:Y}}),U.openedFiles.set(X,1),U}async syncAfterWrite($,Z){try{let J=await this.resolveFile($),U=await this.readBoundedFile(J),X=await this.ensureFileOpen(J,U,Z);if(!X)return;let Y=e0(J).href,H=this.diagnostics.get(Y)?.sequence??0;this.delivered.delete(Y);let z=X.openedFiles.get(Y)??0;if(z>0){let Q=z+1;await X.client.notify("textDocument/didChange",{textDocument:{uri:Y,version:Q},contentChanges:[{text:U}]}),X.openedFiles.set(Y,Q)}return await X.client.notify("textDocument/didSave",{textDocument:{uri:Y},text:U}),await this.waitForDiagnostics(Y,H,X.config.diagnosticWaitTimeout??750,Z),J}catch(J){if(!Z?.aborted&&!this.disposeController.signal.aborted)x7.debug(`[LSP] post-edit sync skipped: ${J instanceof Error?J.message:String(J)}`);return}}async syncAfterDelete($){let Z=await this.resolveMissingFile($).catch(()=>{return});if(!Z)return;if(!this.isInsideWorkspace(Z))return;let J=e0(Z).href;for(let U of this.servers.values()){if(!U.openedFiles.has(J))continue;await U.client.notify("textDocument/didClose",{textDocument:{uri:J}}).catch(()=>{return}),U.openedFiles.delete(J)}this.diagnostics.delete(J),this.delivered.delete(J)}async ensureStarted($,Z){if($.state==="running")return;if($.startPromise)return $.startPromise;if($.state==="error"){if($.restartCount>=($.config.maxRestarts??3))throw Error(`LSP server "${$.name}" exceeded its restart limit`);$.restartCount++}let J=this.startServer($,Z).finally(()=>{$.startPromise=void 0});return $.startPromise=J,J}async startServer($,Z){$.state="starting";try{await $.client.start({command:$.config.command,args:$.config.args??[],cwd:this.workspaceRoot,environment:{...this.options.environment,...$.config.env,BLADE_SESSION_ID:this.options.sessionId}});let J=e0(this.workspaceRoot).href,U={processId:process.pid,rootPath:this.workspaceRoot,rootUri:J,workspaceFolders:[{uri:J,name:l.basename(this.workspaceRoot)}],initializationOptions:$.config.initializationOptions??{},capabilities:{workspace:{configuration:!0,workspaceFolders:!0,symbol:{dynamicRegistration:!1}},textDocument:{synchronization:{dynamicRegistration:!1,willSave:!1,willSaveWaitUntil:!1,didSave:!0},publishDiagnostics:{relatedInformation:!0,versionSupport:!1},hover:{dynamicRegistration:!1,contentFormat:["markdown","plaintext"]},definition:{dynamicRegistration:!1,linkSupport:!0},references:{dynamicRegistration:!1},implementation:{dynamicRegistration:!1,linkSupport:!0},documentSymbol:{dynamicRegistration:!1,hierarchicalDocumentSymbolSupport:!0},callHierarchy:{dynamicRegistration:!1}},general:{positionEncodings:["utf-16"]}}};if(await $.client.initialize(U,$.config.startupTimeout??1e4,Z),$.config.settings!==void 0)await $.client.notify("workspace/didChangeConfiguration",{settings:$.config.settings});$.state="running",$.lastError=void 0}catch(J){throw $.state="error",$.lastError=J instanceof Error?J.message:String(J),await $.client.stop($.config.shutdownTimeout??2000).catch(()=>{return}),J}}async requestWithRetry($,Z,J,U){let X;for(let Y=0;Y<4;Y++)try{return await $.client.request(Z,J,$.config.requestTimeout??1e4,U)}catch(H){if(X=H,H.code!==d7||Y===3)break;await new Promise((z)=>setTimeout(z,100*2**Y))}throw X}captureDiagnostics($,Z){if(this.disposed||!Z||typeof Z!=="object"||!("uri"in Z)||!("diagnostics"in Z))return;let J=Z;if(!Array.isArray(J.diagnostics))return;let U;try{U=J.uri.startsWith("file:")?y7(J.uri):l.resolve(J.uri)}catch{return}if(!this.isInsideWorkspace(U))return;let X=e0(l.resolve(U)).href,Y={sequence:++this.diagnosticSequence,serverName:$,filePath:l.resolve(U),diagnostics:J.diagnostics.filter((Q)=>Q&&typeof Q.message==="string"&&Q.range!==void 0).slice(0,100).map((Q)=>structuredClone(Q))};this.diagnostics.set(X,Y);let H=this.waiters.get(X)??[],z=[];for(let Q of H)if(Y.sequence>Q.afterSequence)clearTimeout(Q.timer),Q.resolve();else z.push(Q);if(z.length>0)this.waiters.set(X,z);else this.waiters.delete(X)}waitForDiagnostics($,Z,J,U){if(J===0||(this.diagnostics.get($)?.sequence??0)>Z)return Promise.resolve();return new Promise((X)=>{let Y=!1,H,z=()=>{if(Y)return;Y=!0,clearTimeout(H.timer),U?.removeEventListener("abort",z);let B=(this.waiters.get($)??[]).filter((V)=>V!==H);if(B.length>0)this.waiters.set($,B);else this.waiters.delete($);X()},Q=setTimeout(z,J);H={afterSequence:Z,resolve:z,timer:Q};let W=this.waiters.get($)??[];if(W.push(H),this.waiters.set($,W),U?.addEventListener("abort",z,{once:!0}),U?.aborted)z()})}attachPendingDiagnostics($,Z){let J=[...this.diagnostics.values()].sort((z,Q)=>{if(Z){if(z.filePath===Z&&Q.filePath!==Z)return-1;if(Q.filePath===Z&&z.filePath!==Z)return 1}return Q.sequence-z.sequence}),U=[],X=[],Y=0;for(let z of J){let Q=e0(z.filePath).href,W=this.delivered.get(Q)??new Set,B=z.diagnostics.sort((E,O)=>(E.severity??4)-(O.severity??4)).filter((E)=>!W.has(this.diagnosticKey(E))).slice(0,Math.min(u7,G4-Y));if(B.length===0)continue;let V=l.relative(this.workspaceRoot,z.filePath);U.push(`${V}:`);for(let E of B){let O=E.range.start.line+1,G=E.range.start.character+1,K=["Error","Warning","Info","Hint"][(E.severity??1)-1],F=E.message.replace(/\s+/g," ").slice(0,500);U.push(` ${K??"Error"} ${O}:${G} ${F}`+(E.code!==void 0?` [${String(E.code)}]`:"")),W.add(this.diagnosticKey(E)),X.push({file:V,line:O,character:G,severity:K??"Error",message:F,server:z.serverName}),Y++}if(this.delivered.set(Q,W),Y>=G4)break}if(U.length===0)return;let H=typeof $.llmContent==="string"?$.llmContent:JSON.stringify($.llmContent);$.llmContent=`${H}
|
|
4
4
|
|
|
@@ -650,14 +650,14 @@ ${B.additionalContext}`};if(B.warning)console.warn(`[ToolExecutor] PostToolUseFa
|
|
|
650
650
|
`+` /model add
|
|
651
651
|
|
|
652
652
|
`+`或运行初始化向导:
|
|
653
|
-
`+" /init");let J=W0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");e.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 L0(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=W0(),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 L0($.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 B1({cwd:A(),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,z=(Q)=>{if(!Y||!X)return;X.release(),X=void 0;try{U.publishTaskAdmissionCapacity(Q)}catch(W){x.warn("[Agent] Failed to publish task admission capacity:",W)}};try{if(U.isTaskSession?.()===!0){Y=J?.taskAdmission===void 0;let B=J?.taskAdmission??l$.admit({key:`${U.workspaceRoot}\x00${U.sessionId}`,...U.getTaskAdmissionLimits(),signal:Z.signal,onUpdate:(V)=>{U.setTaskAdmission(V).catch((E)=>{x.warn("[Agent] Failed to persist task admission update:",E)})}});try{X=await B.ready}catch(V){if(V instanceof D1||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 V}if(Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,z("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),W=Z.signal?.aborted?"cancelled":Q.success?"completed":"failed";return await U.setTaskStatus(W,W==="failed"&&Q.error?Q.error:void 0),H=!0,z(W),Q}catch(Q){let W=Z.signal?.aborted?"cancelled":"failed";try{await U.setTaskStatus(W,Q)}catch(B){x.warn("[Agent] Failed to persist terminal task status:",B)}throw H=!0,z(W),Q}finally{if(!H)await U.setTaskStatus("interrupted","Task stream closed before completion").catch((Q)=>{x.warn("[Agent] Failed to persist interrupted task status:",Q)}),z("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?f8(J.outputSchema).schema:void 0,H=J?.preparedInputTurn;if(Z&&this.sessionRuntime&&!U&&!X){if(!H){let E=Y?await this.sessionRuntime.prepareInputTurn($,{outputSchema:Y}):await this.sessionRuntime.prepareInputTurn($);if(!E.accepted)throw Error(E.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");H=E}}let z=$,Q=null;if(X){if(Q=await this.sessionRuntime.beginGoalContinuation(),!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};z=w5(Q)}else if(!U&&H?.mode!=="pending")try{z=await this.processAtMentionsForContent($)}catch(E){if(this.sessionRuntime&&H)await this.sessionRuntime.finishTurn(H.handle,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});throw E}else if(!Z||!this.sessionRuntime)z=await this.processAtMentionsForContent($);if(Z){let E=z,O=Z,G=U,K=X,F=K?void 0:Y,w=Q,q,b;if(this.sessionRuntime)if(K)b=await this.sessionRuntime.beginTurn("goal");else if(G)b=await this.sessionRuntime.beginPendingTurn();else{let R=H;if(b=R.handle,R.mode==="pending")G=!0,E="";else q=R.messageId}let D=0;if(G&&this.sessionRuntime&&!b)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let L=()=>this.sessionRuntime.getPendingSteeringMessages().map((R)=>({...R,persisted:O.messages.some((T)=>{let f=T.metadata;return f!==null&&typeof f==="object"&&!Array.isArray(f)&&f.inboxMessageId===R.id})})),N=()=>{let R=this.sessionRuntime.getPendingSteeringMessages().flatMap((f)=>f.outputSchema?[f.outputSchema]:[]);if(R.length<=1)return R[0];let T=JSON.stringify(R[0]);if(R.some((f)=>JSON.stringify(f)!==T))throw Error("Queued inputs contain conflicting structured output schemas");return R[0]};if(G&&this.sessionRuntime)F=N();let C=async(R)=>Promise.all(R.map(async(T)=>({...T,content:await this.processAtMentionsForContent(T.content)})));try{if(G&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:L()};if(K&&w)yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w};while(!0){let R=b,T=w??await this.sessionRuntime?.getGoal()??null,f={...J,pendingInputOnly:G,goalContinuationOnly:void 0,preparedInputTurn:void 0,inputMessageId:G?void 0:q,transientInput:K?"goal_continuation":void 0,outputSchema:K?void 0:F,...this.sessionRuntime?{goalLifecycle:{snapshot:T,getSnapshot:()=>this.sessionRuntime.getGoal(),recordVerification:(I)=>this.sessionRuntime.recordGoalCompletionVerification(I),invalidateVerification:(I)=>this.sessionRuntime.invalidateGoalCompletionVerification(I),finalizeCompletion:()=>this.sessionRuntime.finalizeVerifiedGoalCompletion()}}:{},signal:O.signal,turnSteering:this.sessionRuntime&&R?{drain:async()=>C(await this.sessionRuntime.drainSteering(R)),drainOrSeal:async()=>{let I=await this.sessionRuntime.drainSteeringOrSeal(R);return{...I,messages:await C(I.messages)}}}:void 0},M;if(O.permissionMode==="plan")M=yield*this.runPlanLoop(E,O,f);else M=yield*this.runLoop(E,O,f);if(M.success&&M.metadata?.targetMode&&O.permissionMode==="plan"){let I=M.metadata.targetMode,o=M.metadata.planContent;if(x.debug(`Plan 模式已批准,切换到 ${I} 模式并重新执行`),this.sessionRuntime&&O.sessionId)await c.setSessionPermissionMode(O.sessionId,this.sessionRuntime.workspaceRoot,I);await O.onPermissionModeChange?.(I),O={...O,permissionMode:I};let w0=E;if(o){let H0=`
|
|
653
|
+
`+" /init");let J=W0();if(!J)throw Error("配置未初始化,请确保应用已正确启动");e.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 L0(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=W0(),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 L0($.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 B1({cwd:A(),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,z=(Q)=>{if(!Y||!X)return;X.release(),X=void 0;try{U.publishTaskAdmissionCapacity(Q)}catch(W){x.warn("[Agent] Failed to publish task admission capacity:",W)}};try{if(U.isTaskSession?.()===!0){Y=J?.taskAdmission===void 0;let B=J?.taskAdmission??l$.admit({key:`${U.workspaceRoot}\x00${U.sessionId}`,...U.getTaskAdmissionLimits(),signal:Z.signal,onUpdate:(V)=>{U.setTaskAdmission(V).catch((E)=>{x.warn("[Agent] Failed to persist task admission update:",E)})}});try{X=await B.ready}catch(V){if(V instanceof D1||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 V}if(Z.signal?.aborted)return await U.setTaskStatus("cancelled","Task admission was cancelled"),H=!0,z("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),W=Z.signal?.aborted?"cancelled":Q.success?"completed":"failed";return await U.setTaskStatus(W,W==="failed"&&Q.error?Q.error:void 0),H=!0,z(W),Q}catch(Q){let W=Z.signal?.aborted?"cancelled":"failed";try{await U.setTaskStatus(W,Q)}catch(B){x.warn("[Agent] Failed to persist terminal task status:",B)}throw H=!0,z(W),Q}finally{if(!H)await U.setTaskStatus("interrupted","Task stream closed before completion").catch((Q)=>{x.warn("[Agent] Failed to persist interrupted task status:",Q)}),z("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?f8(J.outputSchema).schema:void 0,H=J?.preparedInputTurn;if(Z&&this.sessionRuntime&&!U&&!X){if(!H){let E=Y?await this.sessionRuntime.prepareInputTurn($,{outputSchema:Y}):await this.sessionRuntime.prepareInputTurn($);if(!E.accepted)throw Error(E.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");H=E}}let z=$,Q=null;if(X){if(Q=await this.sessionRuntime.beginGoalContinuation(),!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};z=w5(Q)}else if(!U&&H?.mode!=="pending")try{z=await this.processAtMentionsForContent($)}catch(E){if(this.sessionRuntime&&H)await this.sessionRuntime.finishTurn(H.handle,{outcome:{status:"aborted",cause:"failed",turnsCount:0,toolCallsCount:0,durationMs:0}}).catch(()=>{return});throw E}else if(!Z||!this.sessionRuntime)z=await this.processAtMentionsForContent($);if(Z){let E=z,O=Z,G=U,K=X,F=K?void 0:Y,w=Q,q,b;if(this.sessionRuntime)if(K)b=await this.sessionRuntime.beginTurn("goal");else if(G)b=await this.sessionRuntime.beginPendingTurn();else{let R=H;if(b=R.handle,R.mode==="pending")G=!0,E="";else q=R.messageId}let D=0;if(G&&this.sessionRuntime&&!b)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let L=()=>this.sessionRuntime.getPendingSteeringMessages().map((R)=>({...R,persisted:O.messages.some((T)=>{let f=T.metadata;return f!==null&&typeof f==="object"&&!Array.isArray(f)&&f.inboxMessageId===R.id})})),N=()=>{let R=this.sessionRuntime.getPendingSteeringMessages().flatMap((f)=>f.outputSchema?[f.outputSchema]:[]);if(R.length<=1)return R[0];let T=JSON.stringify(R[0]);if(R.some((f)=>JSON.stringify(f)!==T))throw Error("Queued inputs contain conflicting structured output schemas");return R[0]};if(G&&this.sessionRuntime)F=N();let C=async(R)=>Promise.all(R.map(async(T)=>({...T,content:await this.processAtMentionsForContent(T.content)})));try{if(G&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:L()};if(K&&w)yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w};while(!0){let R=b,T=w??await this.sessionRuntime?.getGoal()??null,f={...J,pendingInputOnly:G,goalContinuationOnly:void 0,preparedInputTurn:void 0,inputMessageId:G?void 0:q,transientInput:K?"goal_continuation":void 0,outputSchema:K?void 0:F,...this.sessionRuntime?{goalLifecycle:{snapshot:T,getSnapshot:()=>this.sessionRuntime.getGoal(),recordVerification:(I)=>this.sessionRuntime.recordGoalCompletionVerification(I),invalidateVerification:(I)=>this.sessionRuntime.invalidateGoalCompletionVerification(I),finalizeCompletion:()=>this.sessionRuntime.finalizeVerifiedGoalCompletion()}}:{},signal:O.signal,turnSteering:this.sessionRuntime&&R?{drain:async()=>C(await this.sessionRuntime.drainSteering(R)),drainOrSeal:async()=>{let I=await this.sessionRuntime.drainSteeringOrSeal(R);return{...I,messages:await C(I.messages)}}}:void 0,turnFinalization:this.sessionRuntime&&R?{turnId:R.id,getInputMessageIds:()=>this.sessionRuntime.getClaimedTurnMessageIds(R)}:void 0},M;if(O.permissionMode==="plan")M=yield*this.runPlanLoop(E,O,f);else M=yield*this.runLoop(E,O,f);if(M.success&&M.metadata?.targetMode&&O.permissionMode==="plan"){let I=M.metadata.targetMode,o=M.metadata.planContent;if(x.debug(`Plan 模式已批准,切换到 ${I} 模式并重新执行`),this.sessionRuntime&&O.sessionId)await c.setSessionPermissionMode(O.sessionId,this.sessionRuntime.workspaceRoot,I);await O.onPermissionModeChange?.(I),O={...O,permissionMode:I};let w0=E;if(o){let H0=`
|
|
654
654
|
|
|
655
655
|
<approved-plan>
|
|
656
656
|
${o}
|
|
657
657
|
</approved-plan>
|
|
658
658
|
|
|
659
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof E==="string")w0=E+H0;else w0=[...E,{type:"text",text:H0}]}M=yield*this.runLoop(w0,O,{...f,inputMessageId:void 0})}if(!this.sessionRuntime||!R)return M;
|
|
660
|
-
`),B={id:this.generateTaskId(),type:"simple",prompt:W};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-
|
|
659
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof E==="string")w0=E+H0;else w0=[...E,{type:"text",text:H0}]}M=yield*this.runLoop(w0,O,{...f,inputMessageId:void 0})}if(!this.sessionRuntime||!R)return M;let h=await this.sessionRuntime.recordGoalProgress({tokens:M.metadata?.tokensUsed??0,elapsedMs:M.metadata?.duration??0});if(h)yield{kind:"goal_updated",goal:h};if(!M.success||O.signal?.aborted){if(h=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":M.error?.message??"goal paused after turn failure"),h)yield{kind:"goal_updated",goal:h}}let p=M.success&&!O.signal?.aborted&&D<20;if(b=await this.sessionRuntime.finishTurn(R,{continuePending:p,outcome:M.success&&!O.signal?.aborted?{status:"completed",turnsCount:M.metadata?.turnsCount??0,toolCallsCount:M.metadata?.toolCallsCount??0,durationMs:M.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:M.metadata?.turnsCount??0,toolCallsCount:M.metadata?.toolCallsCount??0,durationMs:M.metadata?.duration??0}}),b){D++,G=!0,K=!1,w=null,E="",q=void 0,F=N(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:L()};continue}if(!M.success||O.signal?.aborted)return M;if(h=await this.sessionRuntime.getGoal(),!h||h.status!=="active"&&h.status!=="verifying")return M;if(w=await this.sessionRuntime.beginGoalContinuation(),!w)return M;b=await this.sessionRuntime.beginTurn("goal"),G=!1,K=!0,E=w5(w),q=void 0,F=void 0,yield{kind:"goal_continuation_started",goal:w,continuation:w.continuationCount},yield{kind:"goal_updated",goal:w}}}finally{if(this.sessionRuntime&&b)await this.sessionRuntime.finishTurn(b)}}let W=typeof z==="string"?z:z.filter((E)=>E.type==="text").map((E)=>E.text).join(`
|
|
660
|
+
`),B={id:this.generateTaskId(),type:"simple",prompt:W};return{success:!0,finalMessage:(await this.executeTask(B)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:U}=await import("./chunk-axe8621t.js");return U(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){x.debug("Processing Plan mode message...");let{prompt:U}=await C$({projectPath:Z.workspaceRoot||A(),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((z)=>z===H?{type:"text",text:Q1(H.text)}:z)}else X=[{type:"text",text:Q1("")},...$]}return yield*this.executeLoop(X,Z,J,U)}async*runLoop($,Z,J){x.debug("Processing enhanced chat message...");let U=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||A());return yield*this.executeLoop($,Z,J,U)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await C$({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 M8(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=$,x.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);x.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);x.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){x.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){x.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await C$({projectPath:this.sessionRuntime?.workspaceRoot??A(),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("系统提示配置验证成功"),x.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((U)=>U.loaded).map((U)=>U.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await z2({sessionId:"default",configDir:R8.join(C8.homedir(),".blade"),workspaceRoot:A(),resourceRoot:A(),agentResources:this.agentResources});x.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;x.debug(`Builtin tools registered: ${Z} tools`),x.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw x.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await d1({workspaceRoot:A(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){x.debug("No MCP servers configured");return}let Z=P0.createIsolated({artifactWriter:new z1(`legacy-${TX()}`)});this.legacyMcpRegistry=Z;for(let[Y,H]of Object.entries($))try{x.debug(`Connecting to MCP server: ${Y}`),await Z.registerServer(Y,H),x.debug(`MCP server "${Y}" connected`)}catch(z){x.warn(`Warning: MCP server "${Y}" connection failed:`,z)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let U=Z.getCatalogSnapshot();J.replaceMcpTools(U.tools),J.registerAll(O1(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)x.debug(`Registered ${U.tools.length} MCP tools`),x.debug(`[MCP Tools] ${U.tools.map((Y)=>Y.name).join(", ")}`)}catch($){x.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await $0(A());if(this.agentResources=H2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)x.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else x.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;x.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 x.debug(`Filtered tools: ${J.map((U)=>U.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)x.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(`
|
|
661
661
|
`);try{let U=await this.attachmentCollector.collect(J);if(U.length===0)return $;x.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 x.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+=`
|
|
662
662
|
|
|
663
663
|
<system-reminder>
|
|
@@ -903,7 +903,7 @@ ${W}
|
|
|
903
903
|
`+` /model add
|
|
904
904
|
|
|
905
905
|
`+`或运行初始化向导:
|
|
906
|
-
`+" /init");if(!E&&X&&X!=="inherit"&&!b.some((R)=>R.id===X))X=void 0;let L=await d1({workspaceRoot:w,storeServers:K.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),N={...q.config,permissionMode:Y??q.config.permissionMode??"default",lspServers:structuredClone(D.servers),permissions:await F.loadWorkspacePermissions(w,q.config.permissions),hooks:await F.loadWorkspaceHooks(w,q.config.hooks??{})};F.validateConfig(N,q.catalog);let C=new w$(N,{...$,modelResources:q,lspResources:D,mcpServers:L,...X?{modelId:X}:{},permissionMode:N.permissionMode,reasoningEffort:H,serviceTier:z,responseVerbosity:Q,communicationStyle:W,...B?{communicationStyleDigest:B}:{},...V?{projectInstructionsDigest:V}:{},...J?{taskWorktree:J}:{},...U?{taskIsolation:U}:{}});return await C.initialize(),C}catch(G){if(!$.subagentInfo&&!(G instanceof m9)){let K=J?await n0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await w$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",K??void 0).catch((F)=>{if(F.code!=="ENOENT")q0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,F)})}throw G}}static async hasPendingInbox($,Z){try{return(await qH(S9($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return T0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??A()}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 H1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=l$.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",U=await c.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 Q0.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=l$.getStats();Q0.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 A0(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 A0(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 A0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return L2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return L2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??u9}getProjectRuleCatalog(){return this.agentResources?.projectRules??d9.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 W of Q?.getAffectedPaths()??[])if(W)X.add(W)}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 z=[...X].map((Q)=>U0.isAbsolute(Q)?U0.resolve(Q):U0.resolve(this.workspaceRoot,Q)).flatMap((Q)=>{let W=U0.relative(this.workspaceRoot,Q);if(W===""||!W.startsWith("..")&&!U0.isAbsolute(W))return[U0.resolve(this.projectRoot,W)];let B=U0.relative(this.projectRoot,Q);return B===""||!B.startsWith("..")&&!U0.isAbsolute(B)?[Q]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,z,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 n0.getChangeSummary(this.sessionId):void 0;return w$.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?A2(U):void 0,z=H?.message??(typeof U==="string"?U.slice(0,500):void 0),Q=await c.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:z??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 Q0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:Q.taskStatus,...z?{taskStatusReason:z}:{},...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(),c.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),c.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return s.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 x0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return x0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return x0.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=s.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 z=Z.getAgent(H.agentId,J);if(!z)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:z}}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 acknowledgeTurn($){let Z=this.getActiveTurnMailbox(),J=await Z.claimedMessageIds($);if(J.length===0)return;await this.getExecutionEngine().getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,J),await Z.acknowledge(J)}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")await U.saveTurnCompletion(this.sessionId,{turnId:$.id,completedAt:new Date().toISOString(),turnsCount:J.turnsCount,toolCallsCount:J.toolCallsCount,durationMs:J.durationMs});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 j1.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=DH(12),U=this.hasTurnOwner(),X=Z.signal??new AbortController().signal,Y=async(E)=>{let O=E.type==="started"?{executionId:E.executionId,command:E.command,auxiliary:U}:E.type==="output"?{executionId:E.executionId,stream:E.stream,chunk:E.chunk,streamedBytes:E.streamedBytes,streamTruncated:E.streamTruncated,auxiliary:U}:{executionId:E.executionId,messageId:E.messageId,record:E.record,auxiliary:U,delivery:E.delivery,queued:E.queued};Q0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${E.type}`,O),await Z.onEvent?.(E)},H=await p9($,{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(E)=>{if(E.type!=="completed")await Y({...E,auxiliary:U})}}),z=i9(H),W=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",z,null,{...U?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),B=U?await this.getActiveTurnMailbox().enqueue(z,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,V={executionId:J,messageId:W,record:H,modelContent:z,auxiliary:U,...B?.delivery?{delivery:B.delivery}:{},...B?{queued:B.queued}:{}};return await Y({type:"completed",executionId:J,messageId:W,record:H,auxiliary:U,...B?.delivery?{delivery:B.delivery}:{},...B?{queued:B.queued}:{}}),V})}async initialize(){if(this.initialized)return;this.sessionLease=await g9.acquire(this.sessionId,this.workspaceRoot);try{if(!a(this.sessionId))await o4(this.workspaceRoot);let $=K0.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)q0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=v9(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 n2({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new T6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await j1.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)q0.warn(`[SessionRuntime ${this.sessionId}] recovered interrupted turn ${U}`);this.initialized=!0,q0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){q0.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,z=$.communicationStyle??this.selectedCommunicationStyle;if(L2(z,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=z}createToolExecutor($={}){let Z=new K$;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 x0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:W,...B}=Q;Z.queueMcpTaskChange({revision:0,...B})}this.executorCatalogs.set(Z,{allowed:J,blocked:U});let H={...this.config.permissions,...$.permissions},z=$.permissionMode??this.config.permissionMode??"default";return new F1(Z,{permissionConfig:H,permissionMode:z,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:z,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...z==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(G,K)=>{try{await K()}catch(F){$??=F,q0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${G} during cleanup`,F)}},J=this.chatService,U=this.sessionMcpRegistry,X=this.mcpCatalogListener,Y=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,z=this.mcpConnectionListener,Q=this.mcpLogListener,W=this.mcpInstructionsListener,B=this.mcpTaskListener,V=this.sessionLease,E=this.autoVerifyRuntime,O=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new K$,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",()=>t.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>V0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>E?.dispose()),await Z("stop the session LSP servers",()=>O?.dispose()),await Z("release the session hook model resources",()=>K0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>n0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>x0.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&&z)U.off("connectionLifecycleChanged",z);if(U&&Q)U.off("log",Q);if(U&&W)U.off("instructionsChanged",W);if(B)x0.getInstance().off("taskChanged",B);await U?.disconnectAll()}),await Z("release the session lease",()=>V?.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(t.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(s.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=A0($,this.config,J,this.modelResources.catalog,U,X);q0.debug(`${Z} ${Y.displayName} (${$.model})`);let H=Y.model.contextWindow,z=await Y2(Y.chat),Q=this.initialized?this.chatService:void 0,W=this.executionEngine?.getContextManager();this.chatService=z,this.executionEngine=new w1(z,W,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=Y.reasoning,this.currentServiceTier=Y.serviceTier,this.currentResponseVerbosity=Y.responseVerbosity;let B=Q;try{await B?.dispose?.()}catch(V){q0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,V)}}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 C$({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){q0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await c.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof c9||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await c.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await z2({sessionId:this.sessionId,configDir:U0.join(n9.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=P0.createIsolated({roots:a(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!a(this.sessionId),artifactWriter:new z1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!a(this.sessionId)}),exposeLogDetails:!a(this.sessionId),exposeInstructions:!a(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(W)=>{this.applyMcpCatalog(W,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let U=(W)=>{this.applyMcpContentCatalog(W)},X=(W)=>{this.applyMcpResourceUpdated(W)},Y=(W)=>{this.applyMcpConnectionChange(W)},H=(W)=>{this.applyMcpLog(W)},z=(W)=>{this.applyMcpInstructions(W)},Q=(W)=>{if(W.owner.sessionId!==this.sessionId||U0.resolve(W.owner.projectPath)!==U0.resolve(this.workspaceRoot))return;this.applyMcpTask(W);let{owner:B,result:V,...E}=W;Q0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",E)};this.mcpContentCatalogListener=U,this.mcpResourceUpdatedListener=X,this.mcpConnectionListener=Y,this.mcpLogListener=H,this.mcpInstructionsListener=z,this.mcpTaskListener=Q,Z.on("contentCatalogChanged",U),Z.on("resourceUpdated",X),Z.on("connectionLifecycleChanged",Y),Z.on("log",H),Z.on("instructionsChanged",z),x0.getInstance().on("taskChanged",Q);for(let[W,B]of Object.entries($))try{let V=B.type==="stdio"?{...this.sessionEnvironment,...B.env}:void 0;await Z.registerServer(W,B.type==="stdio"?{...B,...V&&Object.keys(V).length>0?{env:V}:{}}:B)}catch(V){q0.warn(`Warning: MCP server "${W}" connection failed:`,V)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(O1(Z)),this.baseRegistry.registerAll(o5(Z))}catch($){q0.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)},z=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(X,Z&&z?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((z)=>!Y.blocked?.has(z)&&(!Y.allowed||Y.allowed.has(z))))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 P9(U,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await $0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=H2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function f6(){let $=await e.getInstance().reload();z0().config.actions.setConfig($),await P0.getInstance().disconnectAll(),r9(),await $0(A())}import hQ from"fuse.js";import z$ from"node:path";import{Mutex as bH}from"async-mutex";var Q$=new bH;async function s9($){await $.reapplyEnabledSettings(),d$($.getWorkspaceRoot()),await u$($.getWorkspaceRoot()),await M6(await $0($.getWorkspaceRoot()))}async function LH($){d$($.getWorkspaceRoot());let Z=await $.refresh();return await u$($.getWorkspaceRoot()),await M6(await $0($.getWorkspaceRoot())),Z}async function C6($){let Z=await $0($),J=Array.from(new Set([Z.plugins,...N2.getInitializedInstances()])),U;for(let X of J){let Y=await LH(X);if(X===Z.plugins)U=Y}return U??{plugins:[],errors:[]}}async function AH($,Z){let J=z$.resolve($),U=k$();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 NH($){return z$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function o9($,Z){if(NH(Z)&&!(await f0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function j2($,Z,J,U="local"){return Q$.runExclusive(async()=>{let X=z$.resolve($),Y=await $0(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 k$().save({enabledPlugins:{[Z]:J}},{scope:U,projectDir:X,immediate:!0});let z=U==="global"?Array.from(new Set([Y.plugins,...N2.getInitializedInstances()])):[Y.plugins];for(let B of z)await s9(B);let Q=Y.plugins.get(Z);if(!Q)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let W=await e.getInstance().loadWorkspacePluginSettingsResolution(X);return{name:Z,requestedEnabled:J,effectiveEnabled:Q.status==="active",scope:U,source:Q.source,status:Q.status,effectiveScope:W.settings[Z]?.effectiveScope??"default"}})}async function T2($){return Q$.runExclusive(async()=>{let Z=await $0($);d$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await u$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function R6($,Z,J="global"){return Q$.runExclusive(async()=>{let U=z$.resolve($),X={...Z,...a9(Z)};await k$().save({pluginSourcePolicy:X},{scope:J,projectDir:U,immediate:!0});let Y=await $0(U),H=J==="global"?Array.from(new Set([Y.plugins,...N2.getInitializedInstances()])):[Y.plugins];for(let z of H)await s9(z);return e.getInstance().loadWorkspacePluginSourcePolicy(U)})}async function S6($,Z,J={}){return Q$.runExclusive(async()=>{let U=z$.resolve($);await o9(U,Z);let X=await e.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await h0().install(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await C6(U);return{result:Y,discovery:H}})}async function P6($,Z,J={}){return Q$.runExclusive(async()=>{let U=z$.resolve($),X=await e.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await h0().update(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await C6(U);return{result:Y,discovery:H}})}async function I6($,Z,J=!1){return Q$.runExclusive(async()=>{let U=z$.resolve($),Y=(await $0(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 h0().uninstall(Z,J);if(!H.success)return{result:H};await AH(U,Z);let z=await C6(U);return{result:H,discovery:z}})}async function k6($,Z,J){return Q$.runExclusive(async()=>{let U=z$.resolve($);await o9(U,Z);let X=await e.getInstance().loadWorkspacePluginSourcePolicy(U);return h0().addMarketplace(Z,{workspaceRoot:U,ref:J,policy:X})})}async function v6($,Z){return Q$.runExclusive(async()=>{let J=z$.resolve($),U=await e.getInstance().loadWorkspacePluginSourcePolicy(J);return h0().refreshMarketplace(Z,U)})}async function y6($,Z=!1){return Q$.runExclusive(()=>h0().removeMarketplace($,Z))}import RJ from"node:fs/promises";import SJ from"node:path";async function f2($,Z,J={}){let U=Date.now(),X=J.timeoutMs??20000,Y="unknown";try{let H=A0($,Z,"off");Y=H.model.api;let Q=await new t9({...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 z=A2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:z.code,message:z.message}}}import jH from"node:os";import e9 from"node:path";function k($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
906
|
+
`+" /init");if(!E&&X&&X!=="inherit"&&!b.some((R)=>R.id===X))X=void 0;let L=await d1({workspaceRoot:w,storeServers:K.mcpServers??{},sessionServers:$.mcpServers,cliConfigs:$.mcpConfig,strictCliConfig:$.strictMcpConfig}),N={...q.config,permissionMode:Y??q.config.permissionMode??"default",lspServers:structuredClone(D.servers),permissions:await F.loadWorkspacePermissions(w,q.config.permissions),hooks:await F.loadWorkspaceHooks(w,q.config.hooks??{})};F.validateConfig(N,q.catalog);let C=new w$(N,{...$,modelResources:q,lspResources:D,mcpServers:L,...X?{modelId:X}:{},permissionMode:N.permissionMode,reasoningEffort:H,serviceTier:z,responseVerbosity:Q,communicationStyle:W,...B?{communicationStyleDigest:B}:{},...V?{projectInstructionsDigest:V}:{},...J?{taskWorktree:J}:{},...U?{taskIsolation:U}:{}});return await C.initialize(),C}catch(G){if(!$.subagentInfo&&!(G instanceof m9)){let K=J?await n0.getChangeSummary($.sessionId).catch(()=>{return}):void 0;await w$.persistTaskStatus($.sessionId,Z,"failed","Session runtime initialization failed",K??void 0).catch((F)=>{if(F.code!=="ENOENT")q0.warn(`[SessionRuntime ${$.sessionId}] Failed to persist initialization failure`,F)})}throw G}}static async hasPendingInbox($,Z){try{return(await qH(S9($,Z))).size>0}catch(J){if(J.code==="ENOENT")return!1;throw J}}static async hasActiveGoal($,Z){return T0.hasActiveGoal($,Z)}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??A()}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 H1(this.lspResources)}isTaskSession(){return!this.options.subagentInfo&&this.options.taskIsolation!==void 0}getTaskAdmissionLimits(){let $=l$.getStats();return{maxConcurrent:$.maxConcurrent,maxQueued:$.maxQueued}}async setTaskAdmission($){if(!this.isTaskSession())return;let Z=new Date().toISOString(),J=$.state==="queued",U=await c.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 Q0.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=l$.getStats();Q0.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 A0(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 A0(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 A0(this.resolveModelConfig(Z),this.config,this.selectedReasoningEffort,this.modelResources.catalog,this.selectedServiceTier,$).responseVerbosity}getCommunicationStyleConfiguration(){return L2(this.selectedCommunicationStyle,this.getCommunicationStyleCatalog())}resolveCommunicationStyleConfiguration($){return L2($,this.getCommunicationStyleCatalog())}getCommunicationStyleCatalog(){return this.agentResources?.communicationStyles??u9}getProjectRuleCatalog(){return this.agentResources?.projectRules??d9.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 W of Q?.getAffectedPaths()??[])if(W)X.add(W)}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 z=[...X].map((Q)=>U0.isAbsolute(Q)?U0.resolve(Q):U0.resolve(this.workspaceRoot,Q)).flatMap((Q)=>{let W=U0.relative(this.workspaceRoot,Q);if(W===""||!W.startsWith("..")&&!U0.isAbsolute(W))return[U0.resolve(this.projectRoot,W)];let B=U0.relative(this.projectRoot,Q);return B===""||!B.startsWith("..")&&!U0.isAbsolute(B)?[Q]:[]});return this.getProjectRuleCatalog().contextualRules(this.projectRoot,z,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 n0.getChangeSummary(this.sessionId):void 0;return w$.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?A2(U):void 0,z=H?.message??(typeof U==="string"?U.slice(0,500):void 0),Q=await c.updateSessionMetadata($,Z,{taskStatus:J,taskStatusReason:z??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 Q0.publish({sessionId:$,projectPath:Z},"task.status",{taskStatus:Q.taskStatus,...z?{taskStatusReason:z}:{},...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(),c.listRewindCheckpoints(this.sessionId,this.workspaceRoot)}async rewindSession($){return this.assertRewindIdle(),c.rewindSession(this.sessionId,this.workspaceRoot,$)}listSubagents(){return s.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 x0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot},$)}getMcpTask($){return x0.getInstance().get($,{sessionId:this.sessionId,projectPath:this.workspaceRoot})}cancelMcpTask($,Z){return x0.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=s.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 z=Z.getAgent(H.agentId,J);if(!z)throw Error(`Resumed subagent was not persisted: ${H.agentId}`);return{source:H.source,session:z}}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 j1.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=DH(12),U=this.hasTurnOwner(),X=Z.signal??new AbortController().signal,Y=async(E)=>{let O=E.type==="started"?{executionId:E.executionId,command:E.command,auxiliary:U}:E.type==="output"?{executionId:E.executionId,stream:E.stream,chunk:E.chunk,streamedBytes:E.streamedBytes,streamTruncated:E.streamTruncated,auxiliary:U}:{executionId:E.executionId,messageId:E.messageId,record:E.record,auxiliary:U,delivery:E.delivery,queued:E.queued};Q0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},`user.shell.${E.type}`,O),await Z.onEvent?.(E)},H=await p9($,{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(E)=>{if(E.type!=="completed")await Y({...E,auxiliary:U})}}),z=i9(H),W=await this.getExecutionEngine().getContextManager().saveMessage(this.sessionId,"user",z,null,{...U?{inboxMessageId:J}:{},userShellCommand:JSON.parse(JSON.stringify(H))},this.options.subagentInfo),B=U?await this.getActiveTurnMailbox().enqueue(z,{allowBeforeTurn:!0,messageId:J,persisted:!0}):void 0,V={executionId:J,messageId:W,record:H,modelContent:z,auxiliary:U,...B?.delivery?{delivery:B.delivery}:{},...B?{queued:B.queued}:{}};return await Y({type:"completed",executionId:J,messageId:W,record:H,auxiliary:U,...B?.delivery?{delivery:B.delivery}:{},...B?{queued:B.queued}:{}}),V})}async initialize(){if(this.initialized)return;this.sessionLease=await g9.acquire(this.sessionId,this.workspaceRoot);try{if(!a(this.sessionId))await o4(this.workspaceRoot);let $=K0.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)q0.warn(`[SessionRuntime ${this.sessionId}] SessionStart hook warning: ${Z.warning}`);let J=v9(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 n2({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,servers:this.lspResources.servers});if(!this.lspManager?.available)this.autoVerifyRuntime=new T6({sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,projectRoot:this.projectRoot,environment:this.sessionEnvironment});await this.validateSystemPromptConfig(),this.activeTurnMailbox=await j1.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)q0.warn(`[SessionRuntime ${this.sessionId}] recovered ${U.outcome} turn ${U.turnId}`);this.initialized=!0,q0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){q0.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,z=$.communicationStyle??this.selectedCommunicationStyle;if(L2(z,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=z}createToolExecutor($={}){let Z=new K$;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 x0.getInstance().list({sessionId:this.sessionId,projectPath:this.workspaceRoot})){let{result:W,...B}=Q;Z.queueMcpTaskChange({revision:0,...B})}this.executorCatalogs.set(Z,{allowed:J,blocked:U});let H={...this.config.permissions,...$.permissions},z=$.permissionMode??this.config.permissionMode??"default";return new F1(Z,{permissionConfig:H,permissionMode:z,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist,contextDefaults:{sessionId:this.sessionId,workspaceRoot:this.workspaceRoot,environment:this.sessionEnvironment,permissionMode:z,mcpSamplingHandler:this.handleMcpSampling},...this.lspManager?{lspManager:this.lspManager}:{},...z==="yolo"&&this.autoVerifyRuntime?{autoVerifyRuntime:this.autoVerifyRuntime}:{},onDispose:()=>{this.executorCatalogs.delete(Z)}})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){let $,Z=async(G,K)=>{try{await K()}catch(F){$??=F,q0.warn(`[SessionRuntime ${this.sessionId}] Failed to ${G} during cleanup`,F)}},J=this.chatService,U=this.sessionMcpRegistry,X=this.mcpCatalogListener,Y=this.mcpContentCatalogListener,H=this.mcpResourceUpdatedListener,z=this.mcpConnectionListener,Q=this.mcpLogListener,W=this.mcpInstructionsListener,B=this.mcpTaskListener,V=this.sessionLease,E=this.autoVerifyRuntime,O=this.lspManager;if(this.chatService=void 0,this.executionEngine=void 0,this.activeTurnMailbox=void 0,this.currentModelMaxContextTokens=void 0,this.baseRegistry=new K$,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",()=>t.getInstance().killSession(this.sessionId)),await Z("clear the session approvals",()=>this.approvalStore.clear()),await Z("clear the session file access records",()=>V0.getInstance().clearSession(this.sessionId,this.workspaceRoot)),await Z("stop the session auto-verification processes",()=>E?.dispose()),await Z("stop the session LSP servers",()=>O?.dispose()),await Z("release the session hook model resources",()=>K0.getInstance().unbindSessionModelResources(this.sessionId,[this.projectRoot,this.workspaceRoot])),await Z("release the session worktrees",()=>n0.releaseSession(this.sessionId)),await Z("dispose the session chat service",()=>J?.dispose?.()),await Z("cancel the session MCP tasks",()=>x0.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&&z)U.off("connectionLifecycleChanged",z);if(U&&Q)U.off("log",Q);if(U&&W)U.off("instructionsChanged",W);if(B)x0.getInstance().off("taskChanged",B);await U?.disconnectAll()}),await Z("release the session lease",()=>V?.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(t.getInstance().listForSession(this.sessionId).some(($)=>$.status==="running"))throw Error("Cannot rewind while a background shell is running");if(s.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=A0($,this.config,J,this.modelResources.catalog,U,X);q0.debug(`${Z} ${Y.displayName} (${$.model})`);let H=Y.model.contextWindow,z=await Y2(Y.chat),Q=this.initialized?this.chatService:void 0,W=this.executionEngine?.getContextManager();this.chatService=z,this.executionEngine=new w1(z,W,this.workspaceRoot),this.currentModelMaxContextTokens=H,this.currentModelId=$.id,this.currentReasoning=Y.reasoning,this.currentServiceTier=Y.serviceTier,this.currentResponseVerbosity=Y.responseVerbosity;let B=Q;try{await B?.dispose?.()}catch(V){q0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,V)}}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 C$({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){q0.warn("[SessionRuntime] Failed to validate system prompt configuration:",J)}}async persistSystemPromptProvenance($){try{await c.updateSessionMetadata(this.sessionId,this.workspaceRoot,$)}catch(Z){if(!(Z instanceof c9||Z.code==="ENOENT")||this.options.subagentInfo)throw Z;await c.createSessionMetadata(this.sessionId,this.workspaceRoot,$)}}async registerBuiltinTools(){let Z=(await z2({sessionId:this.sessionId,configDir:U0.join(n9.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=P0.createIsolated({roots:a(this.sessionId)?[]:[this.workspaceRoot],samplingAvailable:!0,oauthCredentialAccess:!a(this.sessionId),artifactWriter:new z1(`${this.projectRoot}\x00${this.sessionId}`,{exposePaths:!a(this.sessionId)}),exposeLogDetails:!a(this.sessionId),exposeInstructions:!a(this.sessionId)});this.sessionMcpRegistry=Z,this.mcpCatalogBarrier=()=>Z.waitForCatalogIdle(),this.baseRegistry.setMcpCatalogBarrier(this.mcpCatalogBarrier);let J=(W)=>{this.applyMcpCatalog(W,this.initialized)};this.mcpCatalogListener=J,Z.on("catalogChanged",J);let U=(W)=>{this.applyMcpContentCatalog(W)},X=(W)=>{this.applyMcpResourceUpdated(W)},Y=(W)=>{this.applyMcpConnectionChange(W)},H=(W)=>{this.applyMcpLog(W)},z=(W)=>{this.applyMcpInstructions(W)},Q=(W)=>{if(W.owner.sessionId!==this.sessionId||U0.resolve(W.owner.projectPath)!==U0.resolve(this.workspaceRoot))return;this.applyMcpTask(W);let{owner:B,result:V,...E}=W;Q0.publish({sessionId:this.sessionId,projectPath:this.workspaceRoot},"mcp.task.changed",E)};this.mcpContentCatalogListener=U,this.mcpResourceUpdatedListener=X,this.mcpConnectionListener=Y,this.mcpLogListener=H,this.mcpInstructionsListener=z,this.mcpTaskListener=Q,Z.on("contentCatalogChanged",U),Z.on("resourceUpdated",X),Z.on("connectionLifecycleChanged",Y),Z.on("log",H),Z.on("instructionsChanged",z),x0.getInstance().on("taskChanged",Q);for(let[W,B]of Object.entries($))try{let V=B.type==="stdio"?{...this.sessionEnvironment,...B.env}:void 0;await Z.registerServer(W,B.type==="stdio"?{...B,...V&&Object.keys(V).length>0?{env:V}:{}}:B)}catch(V){q0.warn(`Warning: MCP server "${W}" connection failed:`,V)}this.baseRegistry.replaceMcpTools(Z.getCatalogSnapshot().tools),this.baseRegistry.registerAll(O1(Z)),this.baseRegistry.registerAll(o5(Z))}catch($){q0.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)},z=H.added.length>0||H.removed.length>0||H.updated.length>0;J.replaceMcpTools(X,Z&&z?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((z)=>!Y.blocked?.has(z)&&(!Y.allowed||Y.allowed.has(z))))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 P9(U,J.getConfig().model,$)};async loadAgentResources(){let $=this.options.agentResources?this.options.agentResources:await $0(this.projectRoot,{reconcilePlugins:!0});if(this.agentResources=H2($),this.subagentRegistry=this.agentResources.subagents,this.options.agents?.length)this.subagentRegistry.applyOverrides(this.options.agents)}}async function f6(){let $=await e.getInstance().reload();z0().config.actions.setConfig($),await P0.getInstance().disconnectAll(),r9(),await $0(A())}import hQ from"fuse.js";import z$ from"node:path";import{Mutex as bH}from"async-mutex";var Q$=new bH;async function s9($){await $.reapplyEnabledSettings(),d$($.getWorkspaceRoot()),await u$($.getWorkspaceRoot()),await M6(await $0($.getWorkspaceRoot()))}async function LH($){d$($.getWorkspaceRoot());let Z=await $.refresh();return await u$($.getWorkspaceRoot()),await M6(await $0($.getWorkspaceRoot())),Z}async function C6($){let Z=await $0($),J=Array.from(new Set([Z.plugins,...N2.getInitializedInstances()])),U;for(let X of J){let Y=await LH(X);if(X===Z.plugins)U=Y}return U??{plugins:[],errors:[]}}async function AH($,Z){let J=z$.resolve($),U=k$();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 NH($){return z$.isAbsolute($)||$.startsWith("./")||$.startsWith("../")||$==="~"||$.startsWith("~/")}async function o9($,Z){if(NH(Z)&&!(await f0.getInstance().getStatus($)).trusted)throw Error("Local plugin sources require a trusted workspace")}async function j2($,Z,J,U="local"){return Q$.runExclusive(async()=>{let X=z$.resolve($),Y=await $0(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 k$().save({enabledPlugins:{[Z]:J}},{scope:U,projectDir:X,immediate:!0});let z=U==="global"?Array.from(new Set([Y.plugins,...N2.getInitializedInstances()])):[Y.plugins];for(let B of z)await s9(B);let Q=Y.plugins.get(Z);if(!Q)throw Error(`Plugin disappeared during reconciliation: ${Z}`);let W=await e.getInstance().loadWorkspacePluginSettingsResolution(X);return{name:Z,requestedEnabled:J,effectiveEnabled:Q.status==="active",scope:U,source:Q.source,status:Q.status,effectiveScope:W.settings[Z]?.effectiveScope??"default"}})}async function T2($){return Q$.runExclusive(async()=>{let Z=await $0($);d$(Z.workspaceRoot);let J=await Z.plugins.refresh();return await u$(Z.workspaceRoot),{registry:Z.plugins,discovery:J}})}async function R6($,Z,J="global"){return Q$.runExclusive(async()=>{let U=z$.resolve($),X={...Z,...a9(Z)};await k$().save({pluginSourcePolicy:X},{scope:J,projectDir:U,immediate:!0});let Y=await $0(U),H=J==="global"?Array.from(new Set([Y.plugins,...N2.getInitializedInstances()])):[Y.plugins];for(let z of H)await s9(z);return e.getInstance().loadWorkspacePluginSourcePolicy(U)})}async function S6($,Z,J={}){return Q$.runExclusive(async()=>{let U=z$.resolve($);await o9(U,Z);let X=await e.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await h0().install(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await C6(U);return{result:Y,discovery:H}})}async function P6($,Z,J={}){return Q$.runExclusive(async()=>{let U=z$.resolve($),X=await e.getInstance().loadWorkspacePluginSourcePolicy(U),Y=await h0().update(Z,{...J,workspaceRoot:U,policy:X});if(!Y.success)return{result:Y};let H=await C6(U);return{result:Y,discovery:H}})}async function I6($,Z,J=!1){return Q$.runExclusive(async()=>{let U=z$.resolve($),Y=(await $0(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 h0().uninstall(Z,J);if(!H.success)return{result:H};await AH(U,Z);let z=await C6(U);return{result:H,discovery:z}})}async function k6($,Z,J){return Q$.runExclusive(async()=>{let U=z$.resolve($);await o9(U,Z);let X=await e.getInstance().loadWorkspacePluginSourcePolicy(U);return h0().addMarketplace(Z,{workspaceRoot:U,ref:J,policy:X})})}async function v6($,Z){return Q$.runExclusive(async()=>{let J=z$.resolve($),U=await e.getInstance().loadWorkspacePluginSourcePolicy(J);return h0().refreshMarketplace(Z,U)})}async function y6($,Z=!1){return Q$.runExclusive(()=>h0().removeMarketplace($,Z))}import RJ from"node:fs/promises";import SJ from"node:path";async function f2($,Z,J={}){let U=Date.now(),X=J.timeoutMs??20000,Y="unknown";try{let H=A0($,Z,"off");Y=H.model.api;let Q=await new t9({...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 z=A2(H);return{ok:!1,providerId:$.provider,modelConfigId:$.id,model:$.model,wireApi:Y,latencyMs:Date.now()-U,code:z.code,message:z.message}}}import jH from"node:os";import e9 from"node:path";function k($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
907
907
|
|
|
908
908
|
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>P().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var $J={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=k(Z),X=Z.workspaceRoot||Z.cwd||A();await $0(X);let Y=L$(X);if(!J)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(J==="list"){let z=Y.getAllNames().map((O)=>Y.getSubagent(O)).filter((O)=>O!==void 0);if(z.length===0){let O=`**Agents 管理**
|
|
909
909
|
|
|
@@ -1449,7 +1449,7 @@ ${J}
|
|
|
1449
1449
|
`)),{success:!0,message:"Schedules listed",content:Q.join(`
|
|
1450
1450
|
`)}}case"create":{let z=AQ(Y);if("error"in z)return U.sendMessage(`创建失败:${z.error}`),{success:!1,error:z.error};let Q={prompt:z.prompt,projectPath:H,trigger:z.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let W=await $.create(Q),B=W.nextRunAt?new Date(W.nextRunAt).toLocaleString():"(无)";return U.sendMessage(`[OK] 已创建定时任务 \`${W.id}\`
|
|
1451
1451
|
${r6(W.trigger)} · 下次运行: ${B}`),{success:!0,message:`Schedule ${W.id} created`}}catch(W){let B=W instanceof Error?W.message:String(W);return U.sendMessage(`创建失败:${B}`),{success:!1,error:B}}}case"remove":case"rm":{let z=Y[0];if(!z)return U.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let Q=await $.remove(z);return U.sendMessage(Q?`[OK] 已删除 \`${z}\``:`未找到 \`${z}\``),{success:Q,message:Q?"Removed":"Not found"}}case"enable":case"disable":{let z=Y[0];if(!z)return U.sendMessage(`用法:/schedule ${X} <id>`),{success:!1,error:"Missing schedule id"};let Q=await $.setEnabled(z,X==="enable");return U.sendMessage(Q?`[OK] 已${X==="enable"?"启用":"停用"} \`${z}\``:`未找到 \`${z}\``),{success:Boolean(Q),message:Q?"Updated":"Not found"}}case"run":{let z=Y[0];if(!z)return U.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await NQ(z),U.sendMessage(`[OK] 已触发 \`${z}\``),{success:!0,message:"Schedule triggered"}}catch(Q){let W=Q instanceof Error?Q.message:String(Q);return U.sendMessage(`运行失败:${W}`),{success:!1,error:W}}}default:return U.sendMessage(`未知子命令: ${X}
|
|
1452
|
-
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var U7=jQ();import*as J1 from"node:fs/promises";import*as U1 from"node:path";async function W7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??X7(X??A());if(!Y){let E=await TQ($,X??A(),J,U);if(E)return E}let z;try{z=(await J1.readdir(H)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>U1.join(H,O))}catch{return[]}let W=(await Promise.all(z.map(async(E)=>{try{let O=await J1.stat(E);return{path:E,mtime:O.mtimeMs}}catch{return null}}))).filter((E)=>E!==null).sort((E,O)=>O.mtime-E.mtime).map((E)=>E.path),B=[],V=U?$:$.toLowerCase();for(let E of W){if(B.length>=J)break;let O=U1.basename(E,".jsonl"),G=await fQ(E,V,U,O);if(B.push(...G),B.length>=J){B.length=J;break}}return B}async function TQ($,Z,J,U){try{let{syncAll:X}=await import("./chunk-y72p0x68.js"),Y=await z7();if(!Y)return null;let{SessionService:H}=await import("./chunk-
|
|
1452
|
+
使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${X}`}}}}}var U7=jQ();import*as J1 from"node:fs/promises";import*as U1 from"node:path";async function W7($,Z={}){let{maxResults:J=20,caseSensitive:U=!1,projectPath:X,storagePath:Y}=Z,H=Y??X7(X??A());if(!Y){let E=await TQ($,X??A(),J,U);if(E)return E}let z;try{z=(await J1.readdir(H)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>U1.join(H,O))}catch{return[]}let W=(await Promise.all(z.map(async(E)=>{try{let O=await J1.stat(E);return{path:E,mtime:O.mtimeMs}}catch{return null}}))).filter((E)=>E!==null).sort((E,O)=>O.mtime-E.mtime).map((E)=>E.path),B=[],V=U?$:$.toLowerCase();for(let E of W){if(B.length>=J)break;let O=U1.basename(E,".jsonl"),G=await fQ(E,V,U,O);if(B.push(...G),B.length>=J){B.length=J;break}}return B}async function TQ($,Z,J,U){try{let{syncAll:X}=await import("./chunk-y72p0x68.js"),Y=await z7();if(!Y)return null;let{SessionService:H}=await import("./chunk-n00q74bt.js");await X(Y,H.projectionDeriverForSearch());let z=U1.resolve(Z),Q=Q7(Y,$,z,J*4),W=U?$:$.toLowerCase(),B=[];for(let V of Q){if(V.role!=="user"&&V.role!=="assistant")continue;let E=a6(V.text,W,U,V.session_id,V.role,V.timestamp??void 0,0);if(E)B.push(E);if(B.length>=J)break}return B}catch{return null}}async function fQ($,Z,J,U){try{let X=await J1.readFile($,"utf8"),H=X.split(`
|
|
1453
1453
|
`).flatMap((V,E)=>{if(!V.trim())return[];try{return[{event:JSON.parse(V),index:E}]}catch{return[]}});if(!H.some(({event:V})=>V.type==="session_created"))return MQ(H,Z,J,U);let Q=new Map(H.flatMap(({event:V,index:E})=>typeof V.id==="string"?[[V.id,E+1]]:[])),W=Y7(H7(X,$)),B=new Map;for(let V of W){if(V.type==="message_created"&&(V.data.role==="user"||V.data.role==="assistant"))B.set(V.data.messageId,{role:V.data.role,content:[],timestamp:V.timestamp,lineNumber:Q.get(V.id)??0});if(V.type==="part_created"&&V.data.partType==="text"){let E=B.get(V.data.messageId),O=V.data.payload.text;if(E&&typeof O==="string")E.content.push(O)}}return[...B.values()].flatMap((V)=>{let E=a6(V.content.join(" "),Z,J,U,V.role,V.timestamp,V.lineNumber);return E?[E]:[]})}catch{return[]}}function MQ($,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 z=typeof H.content==="string"?H.content:Array.isArray(H.content)?H.content.filter((W)=>typeof W==="object"&&W!==null&&W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join(" "):"",Q=a6(z,Z,J,U,H.role,typeof X.timestamp==="string"?X.timestamp:void 0,Y+1);return Q?[Q]:[]})}function a6($,Z,J,U,X,Y,H){if(!$)return;let z=J?$:$.toLowerCase();if(!z.includes(Z))return;let Q=z.indexOf(Z),W=Math.max(0,Q-80),B=Math.min($.length,Q+Z.length+80);return{sessionId:U,role:X,content:(W>0?"...":"")+$.slice(W,B).replace(/\n/g," ")+(B<$.length?"...":""),timestamp:Y,lineNumber:H}}function B7($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
|
|
1454
1454
|
`];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(`
|
|
1455
1455
|
`)}var CQ={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=k(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let U=$.join(" ");J.sendMessage(`正在搜索: "${U}" ...`);try{let X=await W7(U,{maxResults:15,projectPath:Z.cwd}),Y=B7(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}}}},V7=CQ;var RQ={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await C0({cwd:Z.workspaceRoot??Z.cwd}).refresh(),d$(Z.workspaceRoot??Z.cwd),await u$(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 P().addAssistantMessage(U),{success:!1,error:U}}}},E7=RQ;import SQ from"node:path";function y2($){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 _7($){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 O7($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function PQ($,Z){let J=k(Z),U=$[0],X=t.getInstance(),Y=s.getInstance(),H=Z.sessionId??"",z=Z.sessionId?{sessionId:Z.sessionId,projectPath:SQ.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(U==="resume"){let O=$[1],G=$.slice(2).join(" ").trim();if(!O||!G)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 K=await Z.subagents.resume(O,G),F=`Resumed \`${O}\` as \`${K.session.id}\` (depth ${K.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:O,subagent:K.session}}}if(U==="clean"){let O=Y.cleanupExpiredSessionsForParent(z??H,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let Q=[`**后台任务列表**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Nd as a,Od as b,Pd as c,Qd as d,Rd as e}from"./chunk-
|
|
1
|
+
import{Nd as a,Od as b,Pd as c,Qd as d,Rd as e}from"./chunk-0y0wbjyf.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-j9vqys2g.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-e37k44j1.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-fbnetqrz.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{d as snapshotWorkspaceAgentResources,c as resolveWorkspaceAgentResources,e as resetWorkspaceAgentResources,a as refreshWorkspaceCommunicationStyles,b as configureInvocationPluginDirs};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Bf as h,zf as d}from"./chunk-
|
|
1
|
+
import{Bf as h,zf as d}from"./chunk-fbnetqrz.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as uc,w as vc};
|