blade-code 0.10.10 → 0.10.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-9e5z64ap.js → chunk-04wd6zez.js} +1 -1
  3. package/dist/chunk-14rzj7js.js +1 -0
  4. package/dist/{chunk-bxp1w7sh.js → chunk-21zwc98r.js} +41 -41
  5. package/dist/{chunk-7hjjjkj0.js → chunk-2mmbqha8.js} +1 -1
  6. package/dist/{chunk-j42jswx0.js → chunk-2wkt2w3f.js} +1 -1
  7. package/dist/{chunk-nmmj1x0c.js → chunk-4faz5tkt.js} +1 -1
  8. package/dist/chunk-4hawehmd.js +114 -0
  9. package/dist/{chunk-mhne9y2k.js → chunk-63rg3mhn.js} +1 -1
  10. package/dist/{chunk-hetayg68.js → chunk-670th5hb.js} +1 -1
  11. package/dist/{chunk-hveqdgt6.js → chunk-86shv4yp.js} +1 -1
  12. package/dist/chunk-86w8fd67.js +4 -0
  13. package/dist/{chunk-gvc0qqk4.js → chunk-95zwz4q8.js} +1 -1
  14. package/dist/{chunk-epek6vr2.js → chunk-9e8fyt60.js} +1 -1
  15. package/dist/{chunk-ttncpgr6.js → chunk-cscm57tr.js} +1 -1
  16. package/dist/{chunk-zyf1r2j3.js → chunk-e2s6czgg.js} +1 -1
  17. package/dist/{chunk-6kwv8ph0.js → chunk-e65vyfj7.js} +1 -1
  18. package/dist/{chunk-wnqybbry.js → chunk-eqr25kxv.js} +1 -1
  19. package/dist/{chunk-hfv5gcqj.js → chunk-evn886hs.js} +1 -1
  20. package/dist/{chunk-b6gknm33.js → chunk-h6w3ggx9.js} +1 -1
  21. package/dist/{chunk-7mhkm3x7.js → chunk-hb8krnp5.js} +1 -1
  22. package/dist/{chunk-zf183j2y.js → chunk-jh4571hm.js} +1 -1
  23. package/dist/{chunk-rhw2zkq8.js → chunk-k7caqeew.js} +1 -1
  24. package/dist/{chunk-c7201g75.js → chunk-p5zstj8j.js} +1 -1
  25. package/dist/{chunk-t9aggrv8.js → chunk-pmvfkre2.js} +1 -1
  26. package/dist/{chunk-ggq4y248.js → chunk-pqgw6t9b.js} +35 -35
  27. package/dist/{chunk-d600wn06.js → chunk-pz21tcah.js} +1 -1
  28. package/dist/{chunk-3v0ay0sf.js → chunk-tadbcnwr.js} +1 -1
  29. package/dist/{chunk-fvy56ajf.js → chunk-vaxcmm72.js} +1 -1
  30. package/dist/{chunk-3n4m3pcy.js → chunk-vdgskayb.js} +1 -1
  31. package/dist/{chunk-egmwj6xg.js → chunk-vpz57h5x.js} +1 -1
  32. package/dist/{chunk-g1qpzyt3.js → chunk-vszmbnjh.js} +1 -1
  33. package/dist/{chunk-vdj00rsv.js → chunk-vwwf7p7x.js} +1 -1
  34. package/dist/{chunk-cfwnbrrd.js → chunk-y2j96b3t.js} +1 -1
  35. package/dist/{chunk-y56s2qww.js → chunk-z24sj1r8.js} +1 -1
  36. package/dist/{chunk-jw8gb53m.js → chunk-zd3qxc5p.js} +1 -1
  37. package/dist/web/assets/{ChatView-DdX4BvAo.js → ChatView-DG6MMrFK.js} +2 -2
  38. package/dist/web/assets/{CodeBlockHighlighter-DBw81YZa.js → CodeBlockHighlighter-Cf3DBUGk.js} +1 -1
  39. package/dist/web/assets/{FilePreview-Di-mSDMs.js → FilePreview-LvuYnyjv.js} +1 -1
  40. package/dist/web/assets/{MarkdownRenderer-CxSfwebU.js → MarkdownRenderer-CkSbe36j.js} +3 -3
  41. package/dist/web/assets/{SettingsModal-CoBMb8of.js → SettingsModal-DBsb7E9J.js} +1 -1
  42. package/dist/web/assets/{TaskSwitcher-BmS-DA4i.js → TaskSwitcher-Z0KWY8g9.js} +1 -1
  43. package/dist/web/assets/{TerminalPanel-BPruynbV.js → TerminalPanel-DVWTlxtd.js} +1 -1
  44. package/dist/web/assets/{index-Bx7HzeXs.js → index-DWtXGF3o.js} +26 -26
  45. package/dist/web/index.html +1 -1
  46. package/package.json +1 -1
  47. package/dist/chunk-576pdgtm.js +0 -114
  48. package/dist/chunk-tkqrhxqr.js +0 -1
  49. package/dist/chunk-zepqp80m.js +0 -4
@@ -1,5 +1,5 @@
1
- import{ca as j,da as x0,ia as KJ,ja as O8,ka as P0}from"./chunk-epek6vr2.js";import{Ea as J7,la as $7,na as Z7,oa as r6}from"./chunk-p4zt7ts9.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-bxp1w7sh.js";import{pb as g8,qb as p8,rb as J2}from"./chunk-095x2ykj.js";import{$b as c,Hb as A2,Ib as V0,Jb as p0,Nb as f8,Pb as p2,Qb as c$,Rb as p9,Sb as i9,Vb as VJ,Yb as c9,Zb as l9,xb as X0,yb as m9,zb as g9}from"./chunk-6kwv8ph0.js";import{ac as Y7,dc as H7,lc as z7,rc as Q7}from"./chunk-576pdgtm.js";import{Cc as g4,Dc as d4}from"./chunk-ktf3bpmw.js";import{Pc as O2,Qc as z0,Rc as P,Uc as W0,Vc as X2,Wc as n$,Xc as F$,Yc as B6,Zc as M$,_c as T8,dd as p$}from"./chunk-y56s2qww.js";import{ed as k$}from"./chunk-vmq248m7.js";import{fd as Y$}from"./chunk-ybvdac8k.js";import{jd as t9,kd as Y2}from"./chunk-ah97bmns.js";import{md as L0,nd as j$}from"./chunk-2mzcxq6c.js";import{od as zJ}from"./chunk-8j01ssaf.js";import{qd as y9,rd as x9,sd as h9}from"./chunk-mhne9y2k.js";import{Ad as q7,Bd as S0,Cd as h0,Dd as r2,Ed as N2,Fd as $$,Gd as u$,Hd as d$,Id as d9,Jd as M6,Ld as $0,Md as H2,Nd as r9,td as W2,ud as B2,wd as L$,xd as r8,zd as C0}from"./chunk-hfv5gcqj.js";import{Pd as a$,Rd as q$,Sd as s1}from"./chunk-9tnaads5.js";import{Td as TJ,Vd as u9,Wd as L2,Xd as p4}from"./chunk-heqs3xan.js";import{$d as K0,Zd as g6}from"./chunk-zyf1r2j3.js";import{ae as u0}from"./chunk-7wjy6kgt.js";import{ee as g}from"./chunk-4dq9y7zn.js";import{Be as oZ,Ce as tZ,Je as K4,Ke as a9,Le as v9,Me as F8,Ne as q8,Oe as w8,Pe as D8,Qe as b8,Re as L8,Se as e,he as f4,me as M4,oe as x6,te as GJ,xe as C4,ze as P9}from"./chunk-d600wn06.js";import{$e as a8,Ye as I1,Ze as B4,_e as _,af as S,bf as m}from"./chunk-kvx3sb3z.js";import{df as T9,ef as f9}from"./chunk-f4z3gkbs.js";import{gf as u1,if as A}from"./chunk-5s123nbs.js";import{mf as I9,nf as k9}from"./chunk-s5666ta0.js";import{of as MJ,rf as NJ}from"./chunk-dsj62dcg.js";import{vf as PJ}from"./chunk-wnqybbry.js";import{Af as f0}from"./chunk-gav4hxcv.js";import{Df as X7,Ff as P$,Hf as S9,If as W4,Kf as O0}from"./chunk-363pgv1e.js";import{Mf as t0}from"./chunk-g11hq0e5.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
- [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 w0=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 w0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return w0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){throw w0.warn(`[AcpFileSystem] readTextFile ACP failed: ${Z}`),Z}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return w0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{w0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){throw w0.warn(`[AcpFileSystem] writeTextFile ACP failed: ${J}`),J}}async exists($){if(!this.capabilities.readTextFile)return w0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),w0.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 w0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=M7(J);return w0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return w0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return w0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return w0.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($)}
1
+ import{ca as j,da as x0,ia as KJ,ja as O8,ka as P0}from"./chunk-9e8fyt60.js";import{Ea as J7,la as $7,na as Z7,oa as r6}from"./chunk-p4zt7ts9.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-21zwc98r.js";import{pb as g8,qb as p8,rb as J2}from"./chunk-095x2ykj.js";import{$b as c,Hb as A2,Ib as V0,Jb as p0,Nb as f8,Pb as p2,Qb as c$,Rb as p9,Sb as i9,Vb as VJ,Yb as c9,Zb as l9,xb as X0,yb as m9,zb as g9}from"./chunk-e65vyfj7.js";import{ac as Y7,dc as H7,lc as z7,rc as Q7}from"./chunk-4hawehmd.js";import{Cc as g4,Dc as d4}from"./chunk-ktf3bpmw.js";import{Pc as O2,Qc as z0,Rc as P,Uc as W0,Vc as X2,Wc as n$,Xc as F$,Yc as B6,Zc as M$,_c as T8,dd as p$}from"./chunk-z24sj1r8.js";import{ed as k$}from"./chunk-vmq248m7.js";import{fd as Y$}from"./chunk-ybvdac8k.js";import{jd as t9,kd as Y2}from"./chunk-ah97bmns.js";import{md as A0,nd as j$}from"./chunk-2mzcxq6c.js";import{od as zJ}from"./chunk-8j01ssaf.js";import{qd as y9,rd as x9,sd as h9}from"./chunk-63rg3mhn.js";import{Ad as q7,Bd as S0,Cd as h0,Dd as r2,Ed as N2,Fd as $$,Gd as u$,Hd as d$,Id as d9,Jd as M6,Ld as $0,Md as H2,Nd as r9,td as W2,ud as B2,wd as L$,xd as r8,zd as C0}from"./chunk-evn886hs.js";import{Pd as a$,Rd as q$,Sd as s1}from"./chunk-9tnaads5.js";import{Td as TJ,Vd as u9,Wd as L2,Xd as p4}from"./chunk-heqs3xan.js";import{$d as K0,Zd as g6}from"./chunk-e2s6czgg.js";import{ae as u0}from"./chunk-7wjy6kgt.js";import{ee as g}from"./chunk-4dq9y7zn.js";import{Be as oZ,Ce as tZ,Je as K4,Ke as a9,Le as v9,Me as F8,Ne as q8,Oe as w8,Pe as D8,Qe as b8,Re as L8,Se as e,he as f4,me as M4,oe as x6,te as GJ,xe as C4,ze as P9}from"./chunk-pz21tcah.js";import{$e as a8,Ye as I1,Ze as B4,_e as _,af as S,bf as m}from"./chunk-kvx3sb3z.js";import{df as T9,ef as f9}from"./chunk-f4z3gkbs.js";import{gf as u1,if as A}from"./chunk-5s123nbs.js";import{mf as I9,nf as k9}from"./chunk-s5666ta0.js";import{of as MJ,rf as NJ}from"./chunk-dsj62dcg.js";import{vf as PJ}from"./chunk-eqr25kxv.js";import{Af as f0}from"./chunk-gav4hxcv.js";import{Df as X7,Ff as P$,Hf as S9,If as W4,Kf as O0}from"./chunk-363pgv1e.js";import{Mf as t0}from"./chunk-g11hq0e5.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
+ [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
 
5
5
  <new-diagnostics>
@@ -159,9 +159,9 @@ ${W.content}
159
159
  </instruction-file>`}).join(`
160
160
 
161
161
  `)}
162
- </project-instructions>`,files:z,contentBytes:Z-H}}var UU=/<available_skills>\s*<\/available_skills>/;async function C$($={}){let{projectPath:Z,replaceDefault:J,append:U,mode:X,includeEnvironment:Y=!0,environmentOptions:H,language:z,projectTrusted:Q,projectRuleCatalog:W,projectInstructionSourcePath:B,availableSkills:V,communicationStyle:E="auto",communicationStyleCatalog:O}=$,G=[],K=[],F=X==="plan",w,q;if(F)w=u4,q="plan_mode_prompt";else w=J??h4,q=J?"replace_default":"default";G.push(w),K.push({name:q,loaded:!0,length:w.length});let b=p4(E,O);if(b)G.push(b),K.push({name:"communication_style",loaded:!0,length:b.length});else K.push({name:"communication_style",loaded:!1});let D=Z!==void 0&&(Q??(await f0.getInstance().getStatus(Z)).state==="trusted");if(Z&&D){let N=W?W.staticRules(B??Z):await m4(Z);if(N&&N.files.length>0)G.push(N.content),K.push({name:"project_instructions",loaded:!0,length:N.content.length});else K.push({name:"project_instructions",loaded:!1})}else if(Z)K.push({name:"project_instructions",loaded:!1});if(Z&&process.env.BLADE_AUTO_MEMORY!=="0")try{let M=await new _$(Z).loadIndex();if(M)G.push(`<auto-memory>
163
- ${M}
164
- </auto-memory>`),K.push({name:"auto_memory",loaded:!0,length:M.length});else K.push({name:"auto_memory",loaded:!1})}catch{K.push({name:"auto_memory",loaded:!1})}if(Y){let N=g4(Z?{...H,workingDirectory:Z}:H);if(N)G.push(N),K.push({name:"environment",loaded:!0,length:N.length})}if(U?.trim())G.push(U.trim()),K.push({name:"append",loaded:!0,length:U.trim().length});let L=G.join(`
162
+ </project-instructions>`,files:z,contentBytes:Z-H}}var UU=/<available_skills>\s*<\/available_skills>/;async function C$($={}){let{projectPath:Z,replaceDefault:J,append:U,mode:X,includeEnvironment:Y=!0,environmentOptions:H,language:z,projectTrusted:Q,projectRuleCatalog:W,projectInstructionSourcePath:B,availableSkills:V,communicationStyle:E="auto",communicationStyleCatalog:O}=$,G=[],K=[],F=X==="plan",w,q;if(F)w=u4,q="plan_mode_prompt";else w=J??h4,q=J?"replace_default":"default";G.push(w),K.push({name:q,loaded:!0,length:w.length});let b=p4(E,O);if(b)G.push(b),K.push({name:"communication_style",loaded:!0,length:b.length});else K.push({name:"communication_style",loaded:!1});let D=Z!==void 0&&(Q??(await f0.getInstance().getStatus(Z)).state==="trusted");if(Z&&D){let N=W?W.staticRules(B??Z):await m4(Z);if(N&&N.files.length>0)G.push(N.content),K.push({name:"project_instructions",loaded:!0,length:N.content.length});else K.push({name:"project_instructions",loaded:!1})}else if(Z)K.push({name:"project_instructions",loaded:!1});if(Z&&process.env.BLADE_AUTO_MEMORY!=="0")try{let C=await new _$(Z).loadIndex();if(C)G.push(`<auto-memory>
163
+ ${C}
164
+ </auto-memory>`),K.push({name:"auto_memory",loaded:!0,length:C.length});else K.push({name:"auto_memory",loaded:!1})}catch{K.push({name:"auto_memory",loaded:!1})}if(Y){let N=g4(Z?{...H,workingDirectory:Z}:H);if(N)G.push(N),K.push({name:"environment",loaded:!0,length:N.length})}if(U?.trim())G.push(U.trim()),K.push({name:"append",loaded:!0,length:U.trim().length});let L=G.join(`
165
165
 
166
166
  ---
167
167
 
@@ -194,7 +194,7 @@ ${W.content}`).join(`
194
194
  `);if(J.at(-1)==="")J.pop();if(J.length>WZ)throw new J0(`patch exceeds the ${WZ} line limit`);if(J[0]!==UZ)throw new J0(`first line must be "${UZ}"`,1);if(J.at(-1)!==XZ)throw new J0(`last line must be "${XZ}"`,J.length);let U=[],X=0,Y=1;while(Y<J.length-1){if(U.length>=zZ)throw new J0(`patch exceeds the ${zZ} file operation limit`,Y+1);let H=J[Y],z=Y+1;if(H.startsWith(z5)){let Q=c1(H.slice(z5.length),z);Y++;let W=[];while(Y<J.length-1&&!H5(J[Y])){let B=J[Y];if(!B.startsWith("+"))throw new J0('every Add File content line must start with "+"',Y+1);W.push(B.slice(1)),Y++}if(W.length===0)throw new J0('Add File requires at least one "+" content line',z);U.push({kind:"add",path:Q,content:`${W.join(`
195
195
  `)}
196
196
  `,line:z});continue}if(H.startsWith(Q5)){U.push({kind:"delete",path:c1(H.slice(Q5.length),z),line:z}),Y++;continue}if(H.startsWith(W5)){let Q=c1(H.slice(W5.length),z);Y++;let W;if(J[Y]?.startsWith(YZ))W=c1(J[Y].slice(YZ.length),Y+1),Y++;let B=[],V=!1;while(Y<J.length-1&&!H5(J[Y])){let E=J[Y];if(E!=="@@"&&!E.startsWith("@@ "))throw new J0('Update File content must begin with "@@"',Y+1);if(++X>QZ)throw new J0(`patch exceeds the ${QZ} hunk limit`,Y+1);let O=Y+1,G=E==="@@"?void 0:E.slice(3);Y++;let K=[],F=[],w=!1,q=!1;while(Y<J.length-1&&!H5(J[Y])&&J[Y]!=="@@"&&!J[Y].startsWith("@@ ")){let b=J[Y];if(b===LU){w=!0,Y++;break}let D=b[0];if(D!==" "&&D!=="-"&&D!=="+")throw new J0('hunk lines must start with " ", "-", or "+"',Y+1);let L=b.slice(1);if(D!=="+")K.push(L);if(D!=="-")F.push(L);if(D!==" ")q=!0;Y++}B.push({...G?{changeContext:G}:{},oldLines:K,newLines:F,isEndOfFile:w,hasChange:q,line:O}),V||=q}if(!W&&!V)throw new J0("Update File must change content or include a Move to destination",z);U.push({kind:"update",path:Q,...W?{movePath:W}:{},chunks:B,line:z});continue}throw new J0("expected Add File, Delete File, or Update File header",z)}if(U.length===0)throw new J0("patch must contain at least one file operation");return U}function BZ($){return B5($).flatMap((Z)=>Z.kind==="update"&&Z.movePath?[Z.path,Z.movePath]:[Z.path])}function H5($){return Boolean($?.startsWith(z5)||$?.startsWith(Q5)||$?.startsWith(W5))}function c1($,Z){if($!==$.trim()||$.length===0||$.length>4096)throw new J0("file path is empty, padded, or too long",Z);if($.includes(`
197
- `)||$.includes("\r")||$.includes("\\")||JZ.posix.isAbsolute($)||JZ.win32.isAbsolute($))throw new J0("file paths must be relative POSIX paths",Z);if($.split("/").some((U)=>U.length===0||U==="."||U===".."))throw new J0('file paths cannot contain empty, "." or ".." segments',Z);return $}import{isUtf8 as FZ}from"node:buffer";import{promises as B0}from"node:fs";import D0 from"node:path";import{nanoid as NU}from"nanoid";class V5 extends Error{filePath;hunkLine;constructor($,Z,J){super(`Cannot apply patch to ${$} (hunk line ${Z}): ${J}`);this.filePath=$;this.hunkLine=Z;this.name="ApplyPatchContextError"}}function E5($,Z,J){let U=AU($),X=$.replace(/\r\n/g,`
197
+ `)||$.includes("\r")||$.includes("\\")||JZ.posix.isAbsolute($)||JZ.win32.isAbsolute($))throw new J0("file paths must be relative POSIX paths",Z);if($.split("/").some((U)=>U.length===0||U==="."||U===".."))throw new J0('file paths cannot contain empty, "." or ".." segments',Z);return $}import{isUtf8 as FZ}from"node:buffer";import{promises as B0}from"node:fs";import b0 from"node:path";import{nanoid as NU}from"nanoid";class V5 extends Error{filePath;hunkLine;constructor($,Z,J){super(`Cannot apply patch to ${$} (hunk line ${Z}): ${J}`);this.filePath=$;this.hunkLine=Z;this.name="ApplyPatchContextError"}}function E5($,Z,J){let U=AU($),X=$.replace(/\r\n/g,`
198
198
  `),Y=X.endsWith(`
199
199
  `),H=X.split(`
200
200
  `);if(Y)H.pop();let z=0,Q=!1;for(let B of Z){let V=z;if(B.changeContext){let O=VZ(H,[B.changeContext],z,!1);if(O===void 0)throw new V5(J,B.line,`context "${B.changeContext}" was not found`);if(V=O+1,!B.hasChange){z=V;continue}}let E;if(B.oldLines.length===0)E=B.isEndOfFile?H.length:V;else E=VZ(H,B.oldLines,V,B.isEndOfFile);if(E===void 0){let O=B.oldLines.slice(0,3).join(`
@@ -203,7 +203,7 @@ ${O}`:"insertion point could not be resolved")}if(B.hasChange)H.splice(E,B.oldLi
203
203
  `),J=$.indexOf(`
204
204
  `);return Z>=0&&Z===J-1?`\r
205
205
  `:`
206
- `}var qZ=10485760,EZ=33554432,jU=new Set([".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"]),TU={lstat:($)=>B0.lstat($),readFile:($)=>B0.readFile($),writeFile:($,Z,J)=>B0.writeFile($,Z,J),mkdir:($)=>B0.mkdir($),rename:($,Z)=>B0.rename($,Z),rm:($,Z)=>B0.rm($,Z),rmdir:($)=>B0.rmdir($),syncFile:async($)=>{let Z=await B0.open($,"r");try{await Z.sync()}finally{await Z.close()}},syncDirectory:async($)=>{let Z=await B0.open($,"r");try{await Z.sync()}finally{await Z.close()}}};async function wZ($,Z,J){let U=await B0.realpath(Z),X=[];for(let z of $){J?.throwIfAborted();let Q=await _Z(z.path,U),W=z.kind==="update"&&z.movePath?await _Z(z.movePath,U):void 0;X.push({operation:z,sourcePath:Q,movePath:W})}AZ(X.flatMap(({sourcePath:z,movePath:Q})=>Q?[z,Q]:[z]));let Y=[],H=0;for(let z of X){J?.throwIfAborted();let{operation:Q,sourcePath:W,movePath:B}=z;if(Q.kind==="add"){await OZ(W),H+=Buffer.byteLength(Q.content),Y.push({kind:"add",path:W,oldContent:null,newContent:Q.content,mode:420});continue}let V=await MU(W);if(H+=Buffer.byteLength(V.content),Q.kind==="delete"){Y.push({kind:"delete",path:W,oldContent:V.content,newContent:null,mode:V.mode});continue}let E=E5(V.content,Q.chunks,Q.path);if(H+=Buffer.byteLength(E),B)await OZ(B),Y.push({kind:"delete",path:W,oldContent:V.content,newContent:null,mode:V.mode},{kind:"add",path:B,oldContent:null,newContent:E,mode:V.mode});else{if(E===V.content)throw Error(`Patch does not change ${Q.path}`);Y.push({kind:"update",path:W,oldContent:V.content,newContent:E,mode:V.mode})}}return NZ(H),{workspaceRoot:U,changes:Y,affectedPaths:Y.map((z)=>z.path).sort()}}async function DZ($,Z,J,U){if($.some((z)=>z.kind!=="update"||z.movePath))throw Error("ACP remote ApplyPatch supports Update File operations only because the ACP filesystem protocol does not provide atomic add, delete, or rename primitives");let X=$.map((z)=>fU(z.path,Z));AZ(X);let Y=[],H=0;for(let z=0;z<$.length;z++){U?.throwIfAborted();let Q=$[z];if(Q.kind!=="update")continue;let W=X[z],B=await J.readTextFile(W);PU(B,Q.path);let V=E5(B,Q.chunks,Q.path);if(V===B)throw Error(`Patch does not change ${Q.path}`);H+=Buffer.byteLength(B,"utf8")+Buffer.byteLength(V,"utf8"),Y.push({kind:"update",path:W,oldContent:B,newContent:V})}return NZ(H),{workspaceRoot:Z,changes:Y,affectedPaths:Y.map((z)=>z.path).sort()}}async function bZ($,Z,J=TU){let U=NU(12),X=new Map($.changes.filter((B)=>B.newContent!==null).map((B)=>[B.path,KZ(B.path,U,"stage")])),Y=new Map($.changes.filter((B)=>B.oldContent!==null).map((B)=>[B.path,KZ(B.path,U,"backup")])),H=new Set,z=[],Q;try{for(let B of $.changes){if(Z?.throwIfAborted(),B.newContent===null)continue;await RU(D0.dirname(B.path),z,J)}Q=await a4($.workspaceRoot,U,$,X,Y);for(let B of $.changes){if(Z?.throwIfAborted(),B.newContent===null)continue;let V=X.get(B.path);await J.writeFile(V,B.newContent,{flag:"wx",mode:B.mode??420}),await J.syncFile(V),X.set(B.path,V)}await CU($,J),Z?.throwIfAborted();for(let B of $.changes){if(B.oldContent===null)continue;let V=Y.get(B.path);await J.rename(B.path,V),Y.set(B.path,V)}await GZ($,J);for(let B of $.changes){Z?.throwIfAborted();let V=X.get(B.path);if(!V)continue;await J.rename(V,B.path),H.add(B.path)}await GZ($,J),await s4(Q)}catch(B){let V=await SU(X,Y,H,z,J);if(V.length>0)throw AggregateError([B,...V],"ApplyPatch failed and the local transaction could not be fully rolled back");if(Q)await Z5(Q);throw B}if((await Promise.allSettled([...Y.values()].map((B)=>J.rm(B,{force:!0})))).every((B)=>B.status==="fulfilled")&&Q)await Z5(Q)}async function LZ($,Z,J){let U=[];try{for(let X of $.changes){if(J?.throwIfAborted(),X.oldContent===null||X.newContent===null)throw Error("ACP remote transaction received an unsupported change");if(await Z.readTextFile(X.path)!==X.oldContent)throw Error(`Remote file changed after patch preflight: ${X.path}`);if(U.push(X),await Z.writeTextFile(X.path,X.newContent),await Z.readTextFile(X.path)!==X.newContent)throw Error(`Remote write verification failed: ${X.path}`)}}catch(X){let Y=[];for(let H of U.reverse())try{if(await Z.writeTextFile(H.path,H.oldContent),await Z.readTextFile(H.path)!==H.oldContent)throw Error(`Remote rollback verification failed: ${H.path}`)}catch(z){Y.push(z)}if(Y.length>0)throw AggregateError([X,...Y],"ApplyPatch failed and the ACP remote transaction could not be fully rolled back");throw X}}async function _Z($,Z){let J=D0.resolve(Z,...$.split("/"));if(!X0.isWithinWorkspace(J,Z)||X0.isRestricted(J)||!await X0.isWithinWorkspaceResolved(J,Z))throw Error(`Patch path is outside or restricted: ${$}`);let U=[],X=J;while(!0){try{if((await B0.lstat(X)).isSymbolicLink())throw Error(`Symbolic links cannot be patched: ${$}`);let z=await B0.realpath(X),Q=D0.join(z,...U.reverse());if(!X0.isWithinWorkspace(Q,Z))throw Error(`Patch path escapes the workspace: ${$}`);return Q}catch(H){let z=H.code;if(z!=="ENOENT"&&z!=="ENOTDIR")throw H}let Y=D0.dirname(X);if(Y===X)throw Error(`Cannot resolve patch path: ${$}`);U.push(D0.basename(X)),X=Y}}function fU($,Z){if($.split("/").some((H)=>jU.has(H)))throw Error(`Patch path is restricted: ${$}`);let J=/^[A-Za-z]:[\\/]/.test(Z)?D0.win32:D0.posix;if(!J.isAbsolute(Z))throw Error("ACP workspace root must be absolute");let U=J.resolve(Z),X=J.resolve(U,...$.split("/")),Y=J.relative(U,X);if(Y===".."||Y.startsWith(`..${J.sep}`)||J.isAbsolute(Y))throw Error(`Patch path escapes the ACP workspace: ${$}`);return X}async function MU($){let Z=await B0.lstat($);if(!Z.isFile()||Z.isSymbolicLink())throw Error(`Patch target is not a regular file: ${$}`);if(Z.size>qZ)throw Error(`Patch target exceeds the file size limit: ${$}`);let J=await B0.readFile($);if(!FZ(J))throw Error(`ApplyPatch supports UTF-8 text files only: ${$}`);return{content:J.toString("utf8"),mode:Z.mode&511}}async function OZ($){try{await B0.lstat($)}catch(Z){if(Z.code==="ENOENT")return;throw Z}throw Error(`Add File target already exists: ${$}`)}function AZ($){let Z=new Set,J=process.platform==="win32"||$.some((U)=>/^[A-Za-z]:\\/.test(U));for(let U of $){let X=J?U.toLowerCase():U;if(Z.has(X))throw Error(`Patch contains overlapping file operations: ${U}`);Z.add(X)}}async function CU($,Z){for(let J of $.changes){if(J.oldContent===null){try{await Z.lstat(J.path)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}throw Error(`File appeared after patch preflight: ${J.path}`)}let U=await Z.lstat(J.path);if(!U.isFile()||U.isSymbolicLink())throw Error(`Patch target changed type after preflight: ${J.path}`);let X=await Z.readFile(J.path);if(!FZ(X)||X.toString("utf8")!==J.oldContent)throw Error(`File changed after patch preflight: ${J.path}`)}}async function RU($,Z,J){let U=[],X=$;while(!0){try{let H=await J.lstat(X);if(!H.isDirectory()||H.isSymbolicLink())throw Error(`Patch parent is not a regular directory: ${X}`);break}catch(H){if(H.code!=="ENOENT")throw H}U.push(X);let Y=D0.dirname(X);if(Y===X)throw Error(`Cannot create patch parent: ${$}`);X=Y}for(let Y of U.reverse())await J.mkdir(Y),Z.push(Y)}async function SU($,Z,J,U,X){let Y=[];for(let H of J)await X.rm(H,{force:!0}).catch((z)=>Y.push(z));for(let[H,z]of[...Z].reverse())try{await X.rm(H,{force:!0}),await X.rename(z,H)}catch(Q){Y.push(Q)}for(let H of $.values())await X.rm(H,{force:!0}).catch((z)=>Y.push(z));for(let H of U.reverse())await X.rmdir(H).catch((z)=>{let Q=z.code;if(Q!=="ENOTEMPTY"&&Q!=="ENOENT")Y.push(z)});return await Promise.allSettled([...new Set([...Z.keys(),...J].map((H)=>D0.dirname(H)))].map((H)=>X.syncDirectory(H))),Y}async function GZ($,Z){for(let J of[...new Set($.changes.map((U)=>D0.dirname(U.path)))])await Z.syncDirectory(J)}function KZ($,Z,J){return D0.join(D0.dirname($),`.${D0.basename($)}.blade-patch-${Z}.${J}`)}function PU($,Z){if(Buffer.byteLength($,"utf8")>qZ)throw Error(`Patch target exceeds the file size limit: ${Z}`)}function NZ($){if($>EZ)throw Error(`Patch transaction exceeds the ${EZ} byte limit`)}var O5=j({name:"ApplyPatch",displayName:"Apply Patch",kind:"write",strict:!0,isConcurrencySafe:!0,parallelism:"shared",schema:_.Object({patch:_.String({minLength:1,description:"A complete *** Begin Patch / *** End Patch document containing relative file operations"})}),affectedPaths:({patch:$})=>_5($),extractSignatureContent:({patch:$})=>{let Z=_5($),J=Z.slice(0,5).join(", ");return Z.length>5?`${J} (+${Z.length-5} more)`:J||"invalid patch"},description:{short:"Atomically applies a multi-file text patch",long:"Parses and preflights the complete patch before changing files. Local changes use sorted multi-path locks, same-directory staging, backups, and rollback. ACP remote files support update-only transactions with verified compensating rollback because ACP has no delete or rename API.",usageNotes:["Use relative POSIX paths only. Absolute paths and traversal are rejected.","Use *** Add File, *** Delete File, or *** Update File sections.","Update hunks begin with @@ and every hunk line begins with space, -, or +.","Existing local files must have been read in this Session before patching.","The full patch is all-or-nothing; any parse, context, path, or commit failure rolls back."],examples:[{description:"Update one file and add another",params:{patch:`*** Begin Patch
206
+ `}var qZ=10485760,EZ=33554432,jU=new Set([".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"]),TU={lstat:($)=>B0.lstat($),readFile:($)=>B0.readFile($),writeFile:($,Z,J)=>B0.writeFile($,Z,J),mkdir:($)=>B0.mkdir($),rename:($,Z)=>B0.rename($,Z),rm:($,Z)=>B0.rm($,Z),rmdir:($)=>B0.rmdir($),syncFile:async($)=>{let Z=await B0.open($,"r");try{await Z.sync()}finally{await Z.close()}},syncDirectory:async($)=>{let Z=await B0.open($,"r");try{await Z.sync()}finally{await Z.close()}}};async function wZ($,Z,J){let U=await B0.realpath(Z),X=[];for(let z of $){J?.throwIfAborted();let Q=await _Z(z.path,U),W=z.kind==="update"&&z.movePath?await _Z(z.movePath,U):void 0;X.push({operation:z,sourcePath:Q,movePath:W})}AZ(X.flatMap(({sourcePath:z,movePath:Q})=>Q?[z,Q]:[z]));let Y=[],H=0;for(let z of X){J?.throwIfAborted();let{operation:Q,sourcePath:W,movePath:B}=z;if(Q.kind==="add"){await OZ(W),H+=Buffer.byteLength(Q.content),Y.push({kind:"add",path:W,oldContent:null,newContent:Q.content,mode:420});continue}let V=await MU(W);if(H+=Buffer.byteLength(V.content),Q.kind==="delete"){Y.push({kind:"delete",path:W,oldContent:V.content,newContent:null,mode:V.mode});continue}let E=E5(V.content,Q.chunks,Q.path);if(H+=Buffer.byteLength(E),B)await OZ(B),Y.push({kind:"delete",path:W,oldContent:V.content,newContent:null,mode:V.mode},{kind:"add",path:B,oldContent:null,newContent:E,mode:V.mode});else{if(E===V.content)throw Error(`Patch does not change ${Q.path}`);Y.push({kind:"update",path:W,oldContent:V.content,newContent:E,mode:V.mode})}}return NZ(H),{workspaceRoot:U,changes:Y,affectedPaths:Y.map((z)=>z.path).sort()}}async function DZ($,Z,J,U){if($.some((z)=>z.kind!=="update"||z.movePath))throw Error("ACP remote ApplyPatch supports Update File operations only because the ACP filesystem protocol does not provide atomic add, delete, or rename primitives");let X=$.map((z)=>fU(z.path,Z));AZ(X);let Y=[],H=0;for(let z=0;z<$.length;z++){U?.throwIfAborted();let Q=$[z];if(Q.kind!=="update")continue;let W=X[z],B=await J.readTextFile(W);PU(B,Q.path);let V=E5(B,Q.chunks,Q.path);if(V===B)throw Error(`Patch does not change ${Q.path}`);H+=Buffer.byteLength(B,"utf8")+Buffer.byteLength(V,"utf8"),Y.push({kind:"update",path:W,oldContent:B,newContent:V})}return NZ(H),{workspaceRoot:Z,changes:Y,affectedPaths:Y.map((z)=>z.path).sort()}}async function bZ($,Z,J=TU){let U=NU(12),X=new Map($.changes.filter((B)=>B.newContent!==null).map((B)=>[B.path,KZ(B.path,U,"stage")])),Y=new Map($.changes.filter((B)=>B.oldContent!==null).map((B)=>[B.path,KZ(B.path,U,"backup")])),H=new Set,z=[],Q;try{for(let B of $.changes){if(Z?.throwIfAborted(),B.newContent===null)continue;await RU(b0.dirname(B.path),z,J)}Q=await a4($.workspaceRoot,U,$,X,Y);for(let B of $.changes){if(Z?.throwIfAborted(),B.newContent===null)continue;let V=X.get(B.path);await J.writeFile(V,B.newContent,{flag:"wx",mode:B.mode??420}),await J.syncFile(V),X.set(B.path,V)}await CU($,J),Z?.throwIfAborted();for(let B of $.changes){if(B.oldContent===null)continue;let V=Y.get(B.path);await J.rename(B.path,V),Y.set(B.path,V)}await GZ($,J);for(let B of $.changes){Z?.throwIfAborted();let V=X.get(B.path);if(!V)continue;await J.rename(V,B.path),H.add(B.path)}await GZ($,J),await s4(Q)}catch(B){let V=await SU(X,Y,H,z,J);if(V.length>0)throw AggregateError([B,...V],"ApplyPatch failed and the local transaction could not be fully rolled back");if(Q)await Z5(Q);throw B}if((await Promise.allSettled([...Y.values()].map((B)=>J.rm(B,{force:!0})))).every((B)=>B.status==="fulfilled")&&Q)await Z5(Q)}async function LZ($,Z,J){let U=[];try{for(let X of $.changes){if(J?.throwIfAborted(),X.oldContent===null||X.newContent===null)throw Error("ACP remote transaction received an unsupported change");if(await Z.readTextFile(X.path)!==X.oldContent)throw Error(`Remote file changed after patch preflight: ${X.path}`);if(U.push(X),await Z.writeTextFile(X.path,X.newContent),await Z.readTextFile(X.path)!==X.newContent)throw Error(`Remote write verification failed: ${X.path}`)}}catch(X){let Y=[];for(let H of U.reverse())try{if(await Z.writeTextFile(H.path,H.oldContent),await Z.readTextFile(H.path)!==H.oldContent)throw Error(`Remote rollback verification failed: ${H.path}`)}catch(z){Y.push(z)}if(Y.length>0)throw AggregateError([X,...Y],"ApplyPatch failed and the ACP remote transaction could not be fully rolled back");throw X}}async function _Z($,Z){let J=b0.resolve(Z,...$.split("/"));if(!X0.isWithinWorkspace(J,Z)||X0.isRestricted(J)||!await X0.isWithinWorkspaceResolved(J,Z))throw Error(`Patch path is outside or restricted: ${$}`);let U=[],X=J;while(!0){try{if((await B0.lstat(X)).isSymbolicLink())throw Error(`Symbolic links cannot be patched: ${$}`);let z=await B0.realpath(X),Q=b0.join(z,...U.reverse());if(!X0.isWithinWorkspace(Q,Z))throw Error(`Patch path escapes the workspace: ${$}`);return Q}catch(H){let z=H.code;if(z!=="ENOENT"&&z!=="ENOTDIR")throw H}let Y=b0.dirname(X);if(Y===X)throw Error(`Cannot resolve patch path: ${$}`);U.push(b0.basename(X)),X=Y}}function fU($,Z){if($.split("/").some((H)=>jU.has(H)))throw Error(`Patch path is restricted: ${$}`);let J=/^[A-Za-z]:[\\/]/.test(Z)?b0.win32:b0.posix;if(!J.isAbsolute(Z))throw Error("ACP workspace root must be absolute");let U=J.resolve(Z),X=J.resolve(U,...$.split("/")),Y=J.relative(U,X);if(Y===".."||Y.startsWith(`..${J.sep}`)||J.isAbsolute(Y))throw Error(`Patch path escapes the ACP workspace: ${$}`);return X}async function MU($){let Z=await B0.lstat($);if(!Z.isFile()||Z.isSymbolicLink())throw Error(`Patch target is not a regular file: ${$}`);if(Z.size>qZ)throw Error(`Patch target exceeds the file size limit: ${$}`);let J=await B0.readFile($);if(!FZ(J))throw Error(`ApplyPatch supports UTF-8 text files only: ${$}`);return{content:J.toString("utf8"),mode:Z.mode&511}}async function OZ($){try{await B0.lstat($)}catch(Z){if(Z.code==="ENOENT")return;throw Z}throw Error(`Add File target already exists: ${$}`)}function AZ($){let Z=new Set,J=process.platform==="win32"||$.some((U)=>/^[A-Za-z]:\\/.test(U));for(let U of $){let X=J?U.toLowerCase():U;if(Z.has(X))throw Error(`Patch contains overlapping file operations: ${U}`);Z.add(X)}}async function CU($,Z){for(let J of $.changes){if(J.oldContent===null){try{await Z.lstat(J.path)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}throw Error(`File appeared after patch preflight: ${J.path}`)}let U=await Z.lstat(J.path);if(!U.isFile()||U.isSymbolicLink())throw Error(`Patch target changed type after preflight: ${J.path}`);let X=await Z.readFile(J.path);if(!FZ(X)||X.toString("utf8")!==J.oldContent)throw Error(`File changed after patch preflight: ${J.path}`)}}async function RU($,Z,J){let U=[],X=$;while(!0){try{let H=await J.lstat(X);if(!H.isDirectory()||H.isSymbolicLink())throw Error(`Patch parent is not a regular directory: ${X}`);break}catch(H){if(H.code!=="ENOENT")throw H}U.push(X);let Y=b0.dirname(X);if(Y===X)throw Error(`Cannot create patch parent: ${$}`);X=Y}for(let Y of U.reverse())await J.mkdir(Y),Z.push(Y)}async function SU($,Z,J,U,X){let Y=[];for(let H of J)await X.rm(H,{force:!0}).catch((z)=>Y.push(z));for(let[H,z]of[...Z].reverse())try{await X.rm(H,{force:!0}),await X.rename(z,H)}catch(Q){Y.push(Q)}for(let H of $.values())await X.rm(H,{force:!0}).catch((z)=>Y.push(z));for(let H of U.reverse())await X.rmdir(H).catch((z)=>{let Q=z.code;if(Q!=="ENOTEMPTY"&&Q!=="ENOENT")Y.push(z)});return await Promise.allSettled([...new Set([...Z.keys(),...J].map((H)=>b0.dirname(H)))].map((H)=>X.syncDirectory(H))),Y}async function GZ($,Z){for(let J of[...new Set($.changes.map((U)=>b0.dirname(U.path)))])await Z.syncDirectory(J)}function KZ($,Z,J){return b0.join(b0.dirname($),`.${b0.basename($)}.blade-patch-${Z}.${J}`)}function PU($,Z){if(Buffer.byteLength($,"utf8")>qZ)throw Error(`Patch target exceeds the file size limit: ${Z}`)}function NZ($){if($>EZ)throw Error(`Patch transaction exceeds the ${EZ} byte limit`)}var O5=j({name:"ApplyPatch",displayName:"Apply Patch",kind:"write",strict:!0,isConcurrencySafe:!0,parallelism:"shared",schema:_.Object({patch:_.String({minLength:1,description:"A complete *** Begin Patch / *** End Patch document containing relative file operations"})}),affectedPaths:({patch:$})=>_5($),extractSignatureContent:({patch:$})=>{let Z=_5($),J=Z.slice(0,5).join(", ");return Z.length>5?`${J} (+${Z.length-5} more)`:J||"invalid patch"},description:{short:"Atomically applies a multi-file text patch",long:"Parses and preflights the complete patch before changing files. Local changes use sorted multi-path locks, same-directory staging, backups, and rollback. ACP remote files support update-only transactions with verified compensating rollback because ACP has no delete or rename API.",usageNotes:["Use relative POSIX paths only. Absolute paths and traversal are rejected.","Use *** Add File, *** Delete File, or *** Update File sections.","Update hunks begin with @@ and every hunk line begins with space, -, or +.","Existing local files must have been read in this Session before patching.","The full patch is all-or-nothing; any parse, context, path, or commit failure rolls back."],examples:[{description:"Update one file and add another",params:{patch:`*** Begin Patch
207
207
  *** Update File: src/app.ts
208
208
  @@
209
209
  -const ready = false;
@@ -253,11 +253,11 @@ ${JSON.stringify({patch:w,startLine:E+1,matchLine:z+1})}
253
253
  `);if(mU(V,E)>=0.85)return B.join(`
254
254
  `)}return null}function mU($,Z){let J=$.split(`
255
255
  `),U=Z.split(`
256
- `);if(J.length!==U.length)return 0;if(J.length===0)return 1;let X=0;for(let Y=0;Y<J.length;Y++)if(J[Y].trim()===U[Y].trim())X++;return X/J.length}var K5=j({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:i.filePath({description:"Absolute path of the file to edit"}),old_string:_.String({minLength:1,description:"String to replace"}),new_string:_.String({description:"Replacement string (can be empty)"}),replace_all:S(_.Boolean({description:"Replace all matches (default: first only)"}),!1)}),description:{short:"Performs exact string replacements in files",long:"Performs exact string replacements in files.",usageNotes:["You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.","When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.","The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.","Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."]},async execute($,Z){let{file_path:J,old_string:U,new_string:X,replace_all:Y}=$,{updateOutput:H,sessionId:z,messageId:Q}=Z,W=Z.signal??new AbortController().signal;try{H?.("Starting to read file...");let B=a(z),V=B?E$(z):V$(),E;try{if(B)H?.("通过 IDE 读取文件...");E=await V.readTextFile(J)}catch(f){let C=f;if(C.code==="ENOENT"||C.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:"文件不存在"}};throw f}if(typeof W.throwIfAborted==="function")W.throwIfAborted();if(z){let f=V0.getInstance();if(!f.hasFileBeenRead(J,z))return{success:!1,llmContent:"You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.",error:{type:"validation_error",message:"File not read before edit"},metadata:{requiresRead:!0}};let C=await f.checkExternalModification(J,z);if(C.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before editing.
256
+ `);if(J.length!==U.length)return 0;if(J.length===0)return 1;let X=0;for(let Y=0;Y<J.length;Y++)if(J[Y].trim()===U[Y].trim())X++;return X/J.length}var K5=j({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:i.filePath({description:"Absolute path of the file to edit"}),old_string:_.String({minLength:1,description:"String to replace"}),new_string:_.String({description:"Replacement string (can be empty)"}),replace_all:S(_.Boolean({description:"Replace all matches (default: first only)"}),!1)}),description:{short:"Performs exact string replacements in files",long:"Performs exact string replacements in files.",usageNotes:["You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.","When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: spaces + line number + tab. Everything after that tab is the actual file content to match. Never include any part of the line number prefix in the old_string or new_string.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.","The edit will FAIL if old_string is not unique in the file. Either provide a larger string with more surrounding context to make it unique or use replace_all to change every instance of old_string.","Use replace_all for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance."]},async execute($,Z){let{file_path:J,old_string:U,new_string:X,replace_all:Y}=$,{updateOutput:H,sessionId:z,messageId:Q}=Z,W=Z.signal??new AbortController().signal;try{H?.("Starting to read file...");let B=a(z),V=B?E$(z):V$(),E;try{if(B)H?.("通过 IDE 读取文件...");E=await V.readTextFile(J)}catch(f){let M=f;if(M.code==="ENOENT"||M.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:"文件不存在"}};throw f}if(typeof W.throwIfAborted==="function")W.throwIfAborted();if(z){let f=V0.getInstance();if(!f.hasFileBeenRead(J,z))return{success:!1,llmContent:"You must use your Read tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file.",error:{type:"validation_error",message:"File not read before edit"},metadata:{requiresRead:!0}};let M=await f.checkExternalModification(J,z);if(M.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before editing.
257
257
 
258
- Details: ${C.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:C.message}}}}if(U===X)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let O=iU(E,U);if(!O.matched){let f=lU(E,U,J);return{success:!1,llmContent:f.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:f.metadata}}}let G=O.matched;if(O.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${O.strategy}`);let K=cU(E,G);if(K.length>1&&!Y){let f=E.split(`
259
- `),C=0,h=[];for(let I=0;I<f.length;I++){let o=f[I],q0=C,H0=C+o.length;for(let s0 of K)if(s0>=q0&&s0<H0){let r=Math.max(0,I-1),o0=Math.min(f.length-1,I+1),I0=f.slice(r,o0+1).map((h2)=>h2.trim()).join(" ").slice(0,80);h.push({line:I+1,column:s0-q0+1,context:I0})}C=H0+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${K.length} locations (must be unique).`,"","**Matches found at:**",...h.map((I,o)=>` ${o+1}. Line ${I.line}`),"","**Action Required:** Add 3-5 lines of surrounding context to make old_string unique.","","**Tips for quick success:**","• Include the function/class name that wraps the target code","• Add 2-3 lines before and after the target","• Include unique comments or variable names nearby",`• Or use replace_all=true to change all ${K.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
260
- `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:h.map((I)=>({line:I.line,column:I.column})),count:K.length}}}}else H?.(`找到 ${K.length} 个匹配项,开始替换...`);let F,w;if(Y)F=E.split(G).join(X),w=K.length;else{let f=E.indexOf(G);F=E.substring(0,f)+X+E.substring(f+G.length),w=1}if(typeof W.throwIfAborted==="function")W.throwIfAborted();let q,b,D=!1;if(!B&&z&&Q)try{q=new p0({sessionId:z,workspaceRoot:Z.workspaceRoot}),await q.initialize(),b=await q.createSnapshot(J,Q)}catch(f){console.warn("[EditTool] 创建快照失败:",f),q=void 0,b=void 0}if(B)H?.("通过 IDE 写入文件...");try{await V.writeTextFile(J,F)}catch(f){if(q&&b)await q.discardSnapshot(J,b).catch((C)=>console.warn("[EditTool] 丢弃未完成快照失败:",C));throw f}if(q&&b)try{await q.recordPostEditState(J,b),D=!0}catch(f){console.warn("[EditTool] 完成快照失败:",f),await q.discardSnapshot(J,b).catch((C)=>console.warn("[EditTool] 丢弃未完成快照失败:",C))}if(z)await V0.getInstance().recordFileEdit(J,z,"edit");let L=await V.stat(J),N=CZ(E,F,G,X,4),M=gU(J),R=w===1?`替换 1 处匹配到 ${M}`:`替换 ${w} 处匹配到 ${M}`,T={file_path:J,matches_found:K.length,replacements_made:w,replace_all:Y,old_string_length:U.length,new_string_length:X.length,original_size:E.length,new_size:F.length,size_diff:F.length-E.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:D,session_id:z,message_id:Q,diff_snippet:N,summary:R,kind:"edit",oldContent:E,newContent:F};return{success:!0,llmContent:N?`Edited ${J} (${w} replacement${w>1?"s":""}):
258
+ Details: ${M.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:M.message}}}}if(U===X)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let O=iU(E,U);if(!O.matched){let f=lU(E,U,J);return{success:!1,llmContent:f.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:f.metadata}}}let G=O.matched;if(O.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${O.strategy}`);let K=cU(E,G);if(K.length>1&&!Y){let f=E.split(`
259
+ `),M=0,h=[];for(let I=0;I<f.length;I++){let o=f[I],w0=M,H0=M+o.length;for(let s0 of K)if(s0>=w0&&s0<H0){let r=Math.max(0,I-1),o0=Math.min(f.length-1,I+1),I0=f.slice(r,o0+1).map((h2)=>h2.trim()).join(" ").slice(0,80);h.push({line:I+1,column:s0-w0+1,context:I0})}M=H0+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${K.length} locations (must be unique).`,"","**Matches found at:**",...h.map((I,o)=>` ${o+1}. Line ${I.line}`),"","**Action Required:** Add 3-5 lines of surrounding context to make old_string unique.","","**Tips for quick success:**","• Include the function/class name that wraps the target code","• Add 2-3 lines before and after the target","• Include unique comments or variable names nearby",`• Or use replace_all=true to change all ${K.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
260
+ `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:h.map((I)=>({line:I.line,column:I.column})),count:K.length}}}}else H?.(`找到 ${K.length} 个匹配项,开始替换...`);let F,w;if(Y)F=E.split(G).join(X),w=K.length;else{let f=E.indexOf(G);F=E.substring(0,f)+X+E.substring(f+G.length),w=1}if(typeof W.throwIfAborted==="function")W.throwIfAborted();let q,b,D=!1;if(!B&&z&&Q)try{q=new p0({sessionId:z,workspaceRoot:Z.workspaceRoot}),await q.initialize(),b=await q.createSnapshot(J,Q)}catch(f){console.warn("[EditTool] 创建快照失败:",f),q=void 0,b=void 0}if(B)H?.("通过 IDE 写入文件...");try{await V.writeTextFile(J,F)}catch(f){if(q&&b)await q.discardSnapshot(J,b).catch((M)=>console.warn("[EditTool] 丢弃未完成快照失败:",M));throw f}if(q&&b)try{await q.recordPostEditState(J,b),D=!0}catch(f){console.warn("[EditTool] 完成快照失败:",f),await q.discardSnapshot(J,b).catch((M)=>console.warn("[EditTool] 丢弃未完成快照失败:",M))}if(z)await V0.getInstance().recordFileEdit(J,z,"edit");let L=await V.stat(J),N=CZ(E,F,G,X,4),C=gU(J),R=w===1?`替换 1 处匹配到 ${C}`:`替换 ${w} 处匹配到 ${C}`,T={file_path:J,matches_found:K.length,replacements_made:w,replace_all:Y,old_string_length:U.length,new_string_length:X.length,original_size:E.length,new_size:F.length,size_diff:F.length-E.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:D,session_id:z,message_id:Q,diff_snippet:N,summary:R,kind:"edit",oldContent:E,newContent:F};return{success:!0,llmContent:N?`Edited ${J} (${w} replacement${w>1?"s":""}):
261
261
  ${N}`:`Edited ${J} (${w} replacement${w>1?"s":""})`,metadata:T}}catch(B){let V=B;if(V.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${V.message}`,error:{type:"execution_error",message:V.message,details:V}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=pU($.file_path);return Z?`**/*${Z}`:"**/*"}});function vZ($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function iU($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let J=PZ($,Z);if(J)return{matched:J,strategy:"line_trim"};let U=vZ(Z),Y=vZ($).indexOf(U);if(Y!==-1)return{matched:$.substring(Y,Y+Z.length),strategy:"normalize_quotes"};let H=RZ(Z);if(H!==Z&&$.includes(H))return{matched:H,strategy:"unescape"};let z=IZ($,Z);if(z)return{matched:z,strategy:"whitespace_normalize"};let Q=SZ($,Z);if(Q)return{matched:Q,strategy:"flexible"};let W=kZ($,Z);if(W)return{matched:W,strategy:"block_anchor"};return{matched:null,strategy:"failed"}}function cU($,Z){if(Z.length===0)return[];let J=[],U=$.indexOf(Z);while(U!==-1)J.push(U),U=$.indexOf(Z,U+Z.length);return J}function lU($,Z,J){let U=$.split(`
262
262
  `),X=U.length,Y=nU($,Z,3),H=0,z=Math.min(20,X);if(Y.length>0){let E=Y[0];H=Math.max(0,E.lineNumber-10),z=Math.min(X,E.lineNumber+10)}let W=U.slice(H,z).map((E,O)=>{return` ${(H+O+1).toString().padStart(4)}: ${E}`}).join(`
263
263
  `),B=`String not found in file.
@@ -293,10 +293,10 @@ Common issues:
293
293
  `),X=Z.split(`
294
294
  `);if(X.length===1)return U.map((Q,W)=>({text:Q,lineNumber:W+1,similarity:yZ(Z.trim(),Q.trim())})).filter((Q)=>Q.similarity>0.5).sort((Q,W)=>W.similarity-Q.similarity).slice(0,J);let Y=X.length,H=[];for(let z=0;z<=U.length-Y;z++){let Q=U.slice(z,z+Y).join(`
295
295
  `),W=yZ(Z,Q);if(W>0.5)H.push({text:Q,lineNumber:z+1,similarity:W})}return H.sort((z,Q)=>Q.similarity-z.similarity).slice(0,J)}function yZ($,Z){let J=(E)=>E.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),U=J($),X=J(Z);if(U===X)return 1;let Y=U.length,H=X.length;if(Y===0)return H===0?1:0;if(H===0)return 0;let z=200,Q=U.substring(0,z),W=X.substring(0,z),B=rU(Q,W),V=Math.max(Q.length,W.length);return 1-B/V}function rU($,Z){let J=$.length,U=Z.length,X=Array(J+1).fill(null).map(()=>Array(U+1).fill(0));for(let Y=0;Y<=J;Y++)X[Y][0]=Y;for(let Y=0;Y<=U;Y++)X[0][Y]=Y;for(let Y=1;Y<=J;Y++)for(let H=1;H<=U;H++){let z=$[Y-1]===Z[H-1]?0:1;X[Y][H]=Math.min(X[Y-1][H]+1,X[Y][H-1]+1,X[Y-1][H-1]+z)}return X[J][U]}import{basename as aU,extname as xZ}from"path";var F5=j({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({file_path:i.filePath({description:"File path to read (must be absolute)"}),offset:_.Optional(i.lineNumber({description:"Starting line number (0-based, text files only)"})),limit:_.Optional(i.lineLimit({description:"Number of lines to read (text files only)"})),encoding:i.encoding()}),description:{short:"Read files from the local filesystem",long:"Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.",usageNotes:["The file_path parameter must be an absolute path, not a relative path","By default, it reads up to 2000 lines starting from the beginning of the file","You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters","Any lines longer than 2000 characters will be truncated","Results are returned using cat -n format, with line numbers starting at 1","This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as this is a multimodal LLM.","This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.","This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.","This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.","You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.","You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.","If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."],examples:[{description:"Read the entire file (recommended)",params:{file_path:"/path/to/file.ts"}},{description:"Read the first 100 lines",params:{file_path:"/path/to/file.txt",limit:100}},{description:"Read 100 lines starting at line 50 (large file)",params:{file_path:"/path/to/large-file.log",offset:50,limit:100}}],important:["file_path must be absolute","Prefer reading the entire file (omit offset and limit)","Use offset/limit only for very large files","Line numbers start at 1 (cat -n format)"]},async execute($,Z){let{file_path:J,offset:U,limit:X,encoding:Y="utf8"}=$,{updateOutput:H,sessionId:z}=Z,Q=Z.signal??new AbortController().signal;try{H?.("Starting file read...");let W=a(z),B=W?E$(z):V$();try{if(!await B.exists(J))throw Error("File not found")}catch(D){return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:`File not found: ${J}`}}}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(z)await V0.getInstance().recordFileRead(J,z);let V=await B.stat(J);if(V?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${J}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let E=xZ(J).toLowerCase(),O=sU(E),G=oU(E),K,F={file_path:J,file_size:V?.size,file_type:E,last_modified:V?.mtime instanceof Date?V.mtime.toISOString():void 0,encoding:Y,acp_mode:W};if(G&&Y==="utf8"){if(W)H?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),F.acp_fallback=!0;else H?.("检测到二进制文件,使用 base64 编码...");K=(await B.readBinaryFile(J)).toString("base64"),F.encoding="base64",F.is_binary=!0}else if(O){if(W)H?.("通过 IDE 读取文件...");K=await B.readTextFile(J)}else{if(W)F.acp_fallback=!0;let D=await B.readBinaryFile(J);if(Y==="base64")K=D.toString("base64");else if(Y==="binary")K=D.toString("binary");else K=D.toString("utf8")}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if((U!==void 0||X!==void 0)&&Y==="utf8"&&O){let D=K.split(`
296
- `),L=U||0,N=X!==void 0?L+X:D.length,M=D.slice(L,N);K=M.map((R,T)=>{let f=L+T+1,C=R.length>2000?`${R.substring(0,2000)}...`:R;return`${f.toString().padStart(6)}|${C}`}).join(`
297
- `),F.lines_read=M.length,F.total_lines=D.length,F.start_line=L+1,F.end_line=Math.min(N,D.length)}let w=aU(J),q=F.lines_read||F.total_lines,b=q?`读取 ${q} 行从 ${w}`:`读取 ${w}`;return F.summary=b,{success:!0,llmContent:K,metadata:F}}catch(W){let B=W;if(B.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=xZ($.file_path);return Z?`**/*${Z}`:"**/*"}});function sU($){return[".txt",".md",".js",".ts",".jsx",".tsx",".json",".xml",".html",".htm",".css",".scss",".sass",".less",".yml",".yaml",".toml",".ini",".cfg",".py",".rb",".php",".java",".cpp",".c",".h",".hpp",".rs",".go",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".vue",".svelte",".astro",".dockerfile",".gitignore",".env"].includes($)||$===""}function oU($){return[".jpg",".jpeg",".png",".gif",".bmp",".svg",".ico",".webp",".mp3",".wav",".mp4",".avi",".mov",".wmv",".flv",".webm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".ttf",".otf",".woff",".woff2",".eot"].includes($)}import{promises as tU}from"fs";import{basename as eU,dirname as $3,extname as Z3}from"path";var q5=j({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:i.filePath({description:"Absolute file path to write"}),content:_.String({description:"Content to write"}),encoding:i.encoding(),create_directories:S(_.Boolean({description:"Automatically create missing parent directories"}),!0)}),description:{short:"Writes a file to the local filesystem",long:"Writes a file to the local filesystem.",usageNotes:["This tool will overwrite the existing file if there is one at the provided path.","If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.","Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked."]},async execute($,Z){let{file_path:J,content:U,encoding:X,create_directories:Y}=$,{updateOutput:H,sessionId:z,messageId:Q}=Z,W=Z.signal??new AbortController().signal;try{H?.("开始写入文件...");let B=a(z),V=B?E$(z):V$();if(Y){let N=$3(J);try{await V.mkdir(N,{recursive:!0,mode:493})}catch(M){if(M.code!=="EEXIST")throw M}}if(typeof W.throwIfAborted==="function")W.throwIfAborted();let E=!1,O=null;try{if(E=await V.exists(J),E&&X==="utf8")try{O=await V.readTextFile(J)}catch(N){console.warn("[WriteTool] 读取旧文件内容失败:",N)}}catch{}if(E&&z){let N=V0.getInstance();if(!N.hasFileBeenRead(J,z))return{success:!1,llmContent:"If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.",error:{type:"validation_error",message:"File not read before write"},metadata:{requiresRead:!0}};let M=await N.checkExternalModification(J,z);if(M.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before writing.
296
+ `),L=U||0,N=X!==void 0?L+X:D.length,C=D.slice(L,N);K=C.map((R,T)=>{let f=L+T+1,M=R.length>2000?`${R.substring(0,2000)}...`:R;return`${f.toString().padStart(6)}|${M}`}).join(`
297
+ `),F.lines_read=C.length,F.total_lines=D.length,F.start_line=L+1,F.end_line=Math.min(N,D.length)}let w=aU(J),q=F.lines_read||F.total_lines,b=q?`读取 ${q} 行从 ${w}`:`读取 ${w}`;return F.summary=b,{success:!0,llmContent:K,metadata:F}}catch(W){let B=W;if(B.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:B}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=xZ($.file_path);return Z?`**/*${Z}`:"**/*"}});function sU($){return[".txt",".md",".js",".ts",".jsx",".tsx",".json",".xml",".html",".htm",".css",".scss",".sass",".less",".yml",".yaml",".toml",".ini",".cfg",".py",".rb",".php",".java",".cpp",".c",".h",".hpp",".rs",".go",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".vue",".svelte",".astro",".dockerfile",".gitignore",".env"].includes($)||$===""}function oU($){return[".jpg",".jpeg",".png",".gif",".bmp",".svg",".ico",".webp",".mp3",".wav",".mp4",".avi",".mov",".wmv",".flv",".webm",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".zip",".tar",".gz",".rar",".7z",".exe",".dll",".so",".ttf",".otf",".woff",".woff2",".eot"].includes($)}import{promises as tU}from"fs";import{basename as eU,dirname as $3,extname as Z3}from"path";var q5=j({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,parallelism:"shared",affectedPaths:($)=>[$.file_path],schema:_.Object({file_path:i.filePath({description:"Absolute file path to write"}),content:_.String({description:"Content to write"}),encoding:i.encoding(),create_directories:S(_.Boolean({description:"Automatically create missing parent directories"}),!0)}),description:{short:"Writes a file to the local filesystem",long:"Writes a file to the local filesystem.",usageNotes:["This tool will overwrite the existing file if there is one at the provided path.","If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.","ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.","NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.","Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked."]},async execute($,Z){let{file_path:J,content:U,encoding:X,create_directories:Y}=$,{updateOutput:H,sessionId:z,messageId:Q}=Z,W=Z.signal??new AbortController().signal;try{H?.("开始写入文件...");let B=a(z),V=B?E$(z):V$();if(Y){let N=$3(J);try{await V.mkdir(N,{recursive:!0,mode:493})}catch(C){if(C.code!=="EEXIST")throw C}}if(typeof W.throwIfAborted==="function")W.throwIfAborted();let E=!1,O=null;try{if(E=await V.exists(J),E&&X==="utf8")try{O=await V.readTextFile(J)}catch(N){console.warn("[WriteTool] 读取旧文件内容失败:",N)}}catch{}if(E&&z){let N=V0.getInstance();if(!N.hasFileBeenRead(J,z))return{success:!1,llmContent:"If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first.",error:{type:"validation_error",message:"File not read before write"},metadata:{requiresRead:!0}};let C=await N.checkExternalModification(J,z);if(C.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before writing.
298
298
 
299
- Details: ${M.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:M.message}}}}let G=!1,K,F;if(typeof W.throwIfAborted==="function")W.throwIfAborted();if(!B&&z&&Q)try{K=new p0({sessionId:z,workspaceRoot:Z.workspaceRoot}),await K.initialize(),F=await K.createSnapshot(J,Q)}catch(N){console.warn("[WriteTool] 创建快照失败:",N),K=void 0,F=void 0}try{if(X==="utf8"){if(B)H?.("通过 IDE 写入文件...");await V.writeTextFile(J,U)}else{if(B)return{success:!1,llmContent:"Binary file writes are not supported in ACP mode. The IDE only supports text file operations. Please use encoding='utf8' for text files, or ask the user to write the file manually.",error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let N;if(X==="base64")N=Buffer.from(U,"base64");else if(X==="binary")N=Buffer.from(U,"binary");else N=Buffer.from(U,"utf8");await tU.writeFile(J,N)}}catch(N){if(K&&F)await K.discardSnapshot(J,F).catch((M)=>console.warn("[WriteTool] 丢弃未完成快照失败:",M));throw N}if(K&&F)try{await K.recordPostEditState(J,F),G=!0}catch(N){console.warn("[WriteTool] 完成快照失败:",N),await K.discardSnapshot(J,F).catch((M)=>console.warn("[WriteTool] 丢弃未完成快照失败:",M))}if(z)await V0.getInstance().recordFileEdit(J,z,"write");if(typeof W.throwIfAborted==="function")W.throwIfAborted();let w=await V.stat(J),q=X==="utf8"?U.split(`
299
+ Details: ${C.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:C.message}}}}let G=!1,K,F;if(typeof W.throwIfAborted==="function")W.throwIfAborted();if(!B&&z&&Q)try{K=new p0({sessionId:z,workspaceRoot:Z.workspaceRoot}),await K.initialize(),F=await K.createSnapshot(J,Q)}catch(N){console.warn("[WriteTool] 创建快照失败:",N),K=void 0,F=void 0}try{if(X==="utf8"){if(B)H?.("通过 IDE 写入文件...");await V.writeTextFile(J,U)}else{if(B)return{success:!1,llmContent:"Binary file writes are not supported in ACP mode. The IDE only supports text file operations. Please use encoding='utf8' for text files, or ask the user to write the file manually.",error:{type:"validation_error",message:"Binary writes not supported in ACP mode"}};let N;if(X==="base64")N=Buffer.from(U,"base64");else if(X==="binary")N=Buffer.from(U,"binary");else N=Buffer.from(U,"utf8");await tU.writeFile(J,N)}}catch(N){if(K&&F)await K.discardSnapshot(J,F).catch((C)=>console.warn("[WriteTool] 丢弃未完成快照失败:",C));throw N}if(K&&F)try{await K.recordPostEditState(J,F),G=!0}catch(N){console.warn("[WriteTool] 完成快照失败:",N),await K.discardSnapshot(J,F).catch((C)=>console.warn("[WriteTool] 丢弃未完成快照失败:",C))}if(z)await V0.getInstance().recordFileEdit(J,z,"write");if(typeof W.throwIfAborted==="function")W.throwIfAborted();let w=await V.stat(J),q=X==="utf8"?U.split(`
300
300
  `).length:0,b=eU(J),D=null;if(O&&X==="utf8"&&O!==U){if(O.length<1048576&&U.length<1048576)D=MZ(O,U,4)}let L={file_path:J,content_size:U.length,file_size:w?.size,encoding:X,created_directories:Y,snapshot_created:G,session_id:z,message_id:Q,last_modified:w?.mtime instanceof Date?w.mtime.toISOString():void 0,has_diff:!!D,summary:X==="utf8"?`写入 ${q} 行到 ${b}`:`写入 ${w?.size?J3(w.size):"unknown"} 到 ${b}`,kind:"edit",oldContent:O||"",newContent:X==="utf8"?U:void 0};return{success:!0,llmContent:O?`Wrote ${J} (${U.length} chars, updated existing file)`:`Created ${J} (${U.length} chars, new file)`,metadata:L}}catch(B){let V=B;if(V.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${V.message}`,error:{type:"execution_error",message:V.message,details:V}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Z=Z3($.file_path);return Z?`**/*${Z}`:"**/*"}});function J3($){let Z=["B","KB","MB","GB"],J=$,U=0;while(J>=1024&&U<Z.length-1)J/=1024,U++;return`${J.toFixed(1)}${Z[U]}`}function U3($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function w5($){let Z=$.tokenBudget?.toString()??"none",J=$.tokenBudget===void 0?"unbounded":Math.max(0,$.tokenBudget-$.tokensUsed).toString(),U=$.completionVerification?[`Completion verification attempt: ${$.completionVerification.attempt}`,`Completion verification status: ${$.completionVerification.status}`].join(`
301
301
  `):"Completion verification: not requested";return`<system-reminder>
302
302
  <goal-state>
@@ -473,7 +473,7 @@ Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan
473
473
 
474
474
  Use the relative_path values above for Read/Edit operations.`;else F=`No files found matching "${J}"`;return{success:!0,llmContent:F,metadata:{...K,matches:G,summary:`找到 ${E.length} 个匹配 "${J}" 的文件`}}}catch(B){let V=B;if(V.name==="AbortError")return{success:!1,llmContent:"File search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${V.message}`,metadata:{summary:`搜索失败: ${V.message}`},error:{type:"execution_error",message:V.message,details:V}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function N3($,Z,J,U){let X=U.getIgnorePatterns(),Y=[],H=!1;return await new Promise((z,Q)=>{if(J.signal.aborted){Q(S5("文件搜索被用户中止"));return}let W=b3.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:J.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!J.includeDirectories,ignore:X}),B=!1,V=null,E=()=>{if(V){if(J.signal.removeEventListener)J.signal.removeEventListener("abort",V);else if("onabort"in J.signal)J.signal.onabort=null;V=null}},O=()=>{if(!B)B=!0,H=!0,W.destroy(),E(),z({matches:Y,wasTruncated:H})},G=(K)=>{if(J.signal.aborted){if(!B)B=!0,W.destroy(S5("文件搜索被用户中止"));return}if(Y.length>=J.maxResults){O();return}let F=K.path.replace(/\\/g,"/"),w=L3($,F);if(U.shouldIgnore(F))return;let q=K.stats?K.stats.isDirectory():!1;if(q&&U.shouldIgnoreDirectory(F))return;let b=K.stats&&K.stats.isFile()?K.stats.size:void 0,D=K.stats?K.stats.mtime.toISOString():void 0;if(Y.push({path:w,relative_path:F,is_directory:q,size:b,modified:D}),Y.length>=J.maxResults)O()};if(W.on("data",G),V=()=>{if(!B)B=!0,E(),W.destroy(S5("文件搜索被用户中止"))},J.signal.addEventListener)J.signal.addEventListener("abort",V);else if("onabort"in J.signal)J.signal.onabort=V;W.once("error",(K)=>{if(!B)B=!0,E(),Q(K)}),W.once("end",()=>{if(!B)B=!0,E(),z({matches:Y,wasTruncated:H})})})}function j3($){return $.sort((Z,J)=>{if(Z.is_directory!==J.is_directory)return Z.is_directory?1:-1;if(Z.modified&&J.modified)return new Date(J.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(J.relative_path)})}import{execSync as k5,spawn as v5}from"child_process";import{existsSync as I5}from"fs";import{readdir as T3,readFile as f3}from"fs/promises";import{join as M3,relative as C3}from"path";import R3 from"picomatch";function S3(){let{platform:$,arch:Z}=process,J={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},U=`${$}-${Z}`,X=J[U];if(!X)return null;try{let Y=new URL("../../../../vendor/ripgrep/"+X,import.meta.url).pathname;if(I5(Y))return Y}catch{}return null}function cZ(){try{let Z=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",J=k5(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(J)return J}catch{}let $=S3();if($&&I5($))return $;try{let Z=t0("@vscode/ripgrep");if(Z?.rgPath&&I5(Z.rgPath))return Z.rgPath}catch{}return null}async function P3($){try{return k5("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function I3(){try{return k5("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function k3($,Z,J,U){let X=cZ();if(!X)throw Error("ripgrep not available");return new Promise((Y,H)=>{let z=v5(X,$,{stdio:["pipe","pipe","pipe"]}),Q="",W="";z.stdout.on("data",(V)=>{Q+=V.toString()}),z.stderr.on("data",(V)=>{W+=V.toString()}),z.on("close",(V)=>{Y({stdout:Q,stderr:W,exitCode:V||0})}),z.on("error",(V)=>{H(V)});let B=()=>{z.kill("SIGTERM"),H(Error("搜索被用户中止"))};J.addEventListener("abort",B),z.on("close",()=>{J.removeEventListener("abort",B)})})}async function v3($,Z,J,U){let X=["grep","-n"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);if(X.push("-e",$),J.glob)X.push("--",J.glob);return new Promise((Y,H)=>{let z=v5("git",X,{cwd:Z,stdio:["pipe","pipe","pipe"]}),Q="",W="";z.stdout.on("data",(V)=>{Q+=V.toString()}),z.stderr.on("data",(V)=>{W+=V.toString()}),z.on("close",(V)=>{Y({stdout:Q,stderr:W,exitCode:V||0})}),z.on("error",(V)=>{H(V)});let B=()=>{z.kill("SIGTERM"),H(Error("搜索被用户中止"))};U.addEventListener("abort",B),z.on("close",()=>{U.removeEventListener("abort",B)})})}async function y3($,Z,J,U){let X=["-rn"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);for(let Y of S$)X.push("--exclude-dir="+Y.replace(/^\./,""));return X.push("-e",$,Z),new Promise((Y,H)=>{let z=v5("grep",X,{stdio:["pipe","pipe","pipe"]}),Q="",W="";z.stdout.on("data",(V)=>{Q+=V.toString()}),z.stderr.on("data",(V)=>{W+=V.toString()}),z.on("close",(V)=>{Y({stdout:Q,stderr:W,exitCode:V||0})}),z.on("error",(V)=>{H(V)});let B=()=>{z.kill("SIGTERM"),H(Error("搜索被用户中止"))};U.addEventListener("abort",B),z.on("close",()=>{U.removeEventListener("abort",B)})})}async function x3($,Z,J,U){let X=[],Y=new RegExp($,J.caseInsensitive?"gi":"g"),H=await h3(Z,U),z=0;for(let Q of H){if(U.throwIfAborted(),lZ(Q))continue;if(J.glob&&!u3(Q,J.glob))continue;try{(await f3(Q,"utf-8")).split(`
475
475
  `).forEach((V,E)=>{if(Y.test(V))X.push({file_path:C3(Z,Q),line_number:E+1,content:V})}),z++}catch(W){continue}}return{matches:X,totalFiles:z}}async function h3($,Z){let J=[];async function U(X){Z.throwIfAborted();try{let Y=await T3(X,{withFileTypes:!0});for(let H of Y){Z.throwIfAborted();let z=M3(X,H.name);if(H.isDirectory()){if(!lZ(z))await U(z)}else if(H.isFile())J.push(z)}}catch(Y){}}return await U($),J}function lZ($){for(let Z of S$)if($.includes(Z))return!0;return!1}function u3($,Z){return R3(Z)($)}function d3($){let Z=[];if($.case_insensitive)Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Z.push("-l");break;case"count":Z.push("-c");break;case"content":if($.line_numbers)Z.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Z.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Z.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Z.push("-A",$.context_after.toString())}if($.type)Z.push("--type",$.type);for(let J of S$)Z.push("--glob",`!${J}/**`);if($.glob)Z.push("--glob",$.glob);if($.head_limit!==void 0){let J=($.offset??0)+$.head_limit;Z.push("-m",J.toString())}return Z.push($.pattern),Z.push($.path),Z}function m3($,Z){if(!$.trim())return[];let J=$.trim().split(`
476
- `),U=[];switch(Z){case"files_with_matches":return J.map((X)=>({file_path:X.trim()}));case"count":return J.map((X)=>{let[Y,H]=X.split(":");return{file_path:Y,count:parseInt(H,10)}});case"content":for(let X of J){let Y=g3(X);if(Y)U.push(Y)}return U;default:return[]}}function g3($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),U=$.substring(Z+1),X=U.indexOf(":");if(X!==-1&&/^\d+$/.test(U.substring(0,X))){let Y=parseInt(U.substring(0,X),10),H=U.substring(X+1);return{file_path:J,line_number:Y,content:H}}else return{file_path:J,content:U}}var y5=j({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({pattern:i.pattern({description:"The regular expression pattern to search for in file contents"}),path:_.Optional(_.String({description:"File or directory to search in (rg PATH). Defaults to current working directory"})),glob:_.Optional(_.String({description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'})),type:_.Optional(_.String({description:"File type to search (rg --type). Common types: js, py, rust, go, java, etc."})),output_mode:S(m(["content","files_with_matches","count"],{description:"Output mode: content, files_with_matches, or count. Defaults to files_with_matches."}),"files_with_matches"),"-i":_.Optional(_.Boolean({description:"Case insensitive search (rg -i)"})),"-n":S(_.Boolean({description:"Show line numbers in content output (rg -n). Defaults to true."}),!0),"-B":_.Optional(i.nonNegativeInt({description:"Lines before each match (rg -B)"})),"-A":_.Optional(i.nonNegativeInt({description:"Lines after each match (rg -A)"})),"-C":_.Optional(i.nonNegativeInt({description:"Lines before and after each match (rg -C)"})),head_limit:_.Optional(i.positiveInt({description:"Limit output to first N lines or entries"})),offset:_.Optional(i.nonNegativeInt({description:"Skip first N lines or entries before applying head_limit"})),multiline:S(_.Boolean({description:"Enable multiline matching (rg -U --multiline-dotall)"}),!1)}),description:{short:"A powerful search tool built on ripgrep",long:'A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")\n - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n'},async execute($,Z){let{pattern:J,path:U,glob:X,type:Y,output_mode:H,"-i":z,"-n":Q=!0,"-B":W,"-A":B,"-C":V,head_limit:E,offset:O,multiline:G}=$,{updateOutput:K}=Z,F=Z.signal??new AbortController().signal,w=U??Z.workspaceRoot??A();try{K?.(`使用智能搜索策略查找模式 "${J}"...`);let q=null,b="ripgrep",D=[],L=cZ();if(L)try{K?.(`使用 ripgrep (${L})`);let R=d3({pattern:J,path:w,glob:X,type:Y,output_mode:H,case_insensitive:z??!1,line_numbers:Q,context_before:W,context_after:B,context:V,head_limit:E,offset:O,multiline:G??!1});q=await k3(R,H,F,K),b="ripgrep"}catch{K?.("[WARN] ripgrep 失败,尝试降级策略..."),q=null}if(!q&&await P3(w))try{K?.("使用 git grep"),q=await v3(J,w,{caseInsensitive:z??!1,glob:X,contextLines:V},F),b="git-grep"}catch{K?.("[WARN] git grep 失败,继续尝试其他策略..."),q=null}if(!q&&I3())try{K?.("使用系统 grep"),q=await y3(J,w,{caseInsensitive:z??!1,contextLines:V},F),b="system-grep"}catch{K?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),q=null}if(!q)K?.("使用纯 JavaScript 搜索实现"),D=(await x3(J,w,{caseInsensitive:z??!1,glob:X,multiline:G??!1},F)).matches,b="fallback",q={stdout:"",stderr:"",exitCode:0};else D=m3(q.stdout,H);let N=D.length;if(O!==void 0&&O>0)D=D.slice(O);if(E!==void 0&&D.length>E)D=D.slice(0,E);let M={search_pattern:J,search_path:w,output_mode:H,case_insensitive:z??!1,total_matches:D.length,original_total:N,offset:O,head_limit:E,strategy:b,exit_code:q?.exitCode};if(q&&q.exitCode!==0&&q.stderr)return{success:!1,llmContent:`Search execution failed: ${q.stderr}`,metadata:{...M,summary:`搜索失败: ${q.stderr}`},error:{type:"execution_error",message:q.stderr}};return{success:!0,llmContent:D,metadata:{...M,summary:D.length>0?`搜索 "${J}" 找到 ${D.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(q){let b=q;if(b.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${b.message}`,metadata:{summary:`搜索失败: ${b.message}`},error:{type:"execution_error",message:b.message,details:b}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{isAbsolute as p3,resolve as i3}from"node:path";var x5=j({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({command:i.command({description:"Bash command to execute"}),timeout:i.timeout(1000,300000,30000),cwd:_.Optional(_.String({description:"Working directory (optional; applies only to this command). To persist, use cd"})),env:i.environment(),run_in_background:S(_.Boolean({description:"Run in background (suitable for long-running commands)"}),!1)}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
476
+ `),U=[];switch(Z){case"files_with_matches":return J.map((X)=>({file_path:X.trim()}));case"count":return J.map((X)=>{let[Y,H]=X.split(":");return{file_path:Y,count:parseInt(H,10)}});case"content":for(let X of J){let Y=g3(X);if(Y)U.push(Y)}return U;default:return[]}}function g3($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),U=$.substring(Z+1),X=U.indexOf(":");if(X!==-1&&/^\d+$/.test(U.substring(0,X))){let Y=parseInt(U.substring(0,X),10),H=U.substring(X+1);return{file_path:J,line_number:Y,content:H}}else return{file_path:J,content:U}}var y5=j({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({pattern:i.pattern({description:"The regular expression pattern to search for in file contents"}),path:_.Optional(_.String({description:"File or directory to search in (rg PATH). Defaults to current working directory"})),glob:_.Optional(_.String({description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'})),type:_.Optional(_.String({description:"File type to search (rg --type). Common types: js, py, rust, go, java, etc."})),output_mode:S(m(["content","files_with_matches","count"],{description:"Output mode: content, files_with_matches, or count. Defaults to files_with_matches."}),"files_with_matches"),"-i":_.Optional(_.Boolean({description:"Case insensitive search (rg -i)"})),"-n":S(_.Boolean({description:"Show line numbers in content output (rg -n). Defaults to true."}),!0),"-B":_.Optional(i.nonNegativeInt({description:"Lines before each match (rg -B)"})),"-A":_.Optional(i.nonNegativeInt({description:"Lines after each match (rg -A)"})),"-C":_.Optional(i.nonNegativeInt({description:"Lines before and after each match (rg -C)"})),head_limit:_.Optional(i.positiveInt({description:"Limit output to first N lines or entries"})),offset:_.Optional(i.nonNegativeInt({description:"Skip first N lines or entries before applying head_limit"})),multiline:S(_.Boolean({description:"Enable multiline matching (rg -U --multiline-dotall)"}),!1)}),description:{short:"A powerful search tool built on ripgrep",long:'A powerful search tool built on ripgrep\n\n Usage:\n - ALWAYS use Grep for search tasks. NEVER invoke `grep` or `rg` as a Bash command. The Grep tool has been optimized for correct permissions and access.\n - Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")\n - Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")\n - Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts\n - Use Task tool for open-ended searches requiring multiple rounds\n - Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use `interface\\{\\}` to find `interface{}` in Go code)\n - Multiline matching: By default patterns match within single lines only. For cross-line patterns like `struct \\{[\\s\\S]*?field`, use `multiline: true`\n'},async execute($,Z){let{pattern:J,path:U,glob:X,type:Y,output_mode:H,"-i":z,"-n":Q=!0,"-B":W,"-A":B,"-C":V,head_limit:E,offset:O,multiline:G}=$,{updateOutput:K}=Z,F=Z.signal??new AbortController().signal,w=U??Z.workspaceRoot??A();try{K?.(`使用智能搜索策略查找模式 "${J}"...`);let q=null,b="ripgrep",D=[],L=cZ();if(L)try{K?.(`使用 ripgrep (${L})`);let R=d3({pattern:J,path:w,glob:X,type:Y,output_mode:H,case_insensitive:z??!1,line_numbers:Q,context_before:W,context_after:B,context:V,head_limit:E,offset:O,multiline:G??!1});q=await k3(R,H,F,K),b="ripgrep"}catch{K?.("[WARN] ripgrep 失败,尝试降级策略..."),q=null}if(!q&&await P3(w))try{K?.("使用 git grep"),q=await v3(J,w,{caseInsensitive:z??!1,glob:X,contextLines:V},F),b="git-grep"}catch{K?.("[WARN] git grep 失败,继续尝试其他策略..."),q=null}if(!q&&I3())try{K?.("使用系统 grep"),q=await y3(J,w,{caseInsensitive:z??!1,contextLines:V},F),b="system-grep"}catch{K?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),q=null}if(!q)K?.("使用纯 JavaScript 搜索实现"),D=(await x3(J,w,{caseInsensitive:z??!1,glob:X,multiline:G??!1},F)).matches,b="fallback",q={stdout:"",stderr:"",exitCode:0};else D=m3(q.stdout,H);let N=D.length;if(O!==void 0&&O>0)D=D.slice(O);if(E!==void 0&&D.length>E)D=D.slice(0,E);let C={search_pattern:J,search_path:w,output_mode:H,case_insensitive:z??!1,total_matches:D.length,original_total:N,offset:O,head_limit:E,strategy:b,exit_code:q?.exitCode};if(q&&q.exitCode!==0&&q.stderr)return{success:!1,llmContent:`Search execution failed: ${q.stderr}`,metadata:{...C,summary:`搜索失败: ${q.stderr}`},error:{type:"execution_error",message:q.stderr}};return{success:!0,llmContent:D,metadata:{...C,summary:D.length>0?`搜索 "${J}" 找到 ${D.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(q){let b=q;if(b.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${b.message}`,metadata:{summary:`搜索失败: ${b.message}`},error:{type:"execution_error",message:b.message,details:b}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{isAbsolute as p3,resolve as i3}from"node:path";var x5=j({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({command:i.command({description:"Bash command to execute"}),timeout:i.timeout(1000,300000,30000),cwd:_.Optional(_.String({description:"Working directory (optional; applies only to this command). To persist, use cd"})),env:i.environment(),run_in_background:S(_.Boolean({description:"Run in background (suitable for long-running commands)"}),!1)}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
477
477
 
478
478
  IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
479
479
 
@@ -493,7 +493,7 @@ Before executing commands:
493
493
  ${U}`:"",J?`stdout:
494
494
  ${J}`:""].filter(Boolean);return Y.length>0?`${X}
495
495
  ${Y.join(`
496
- `)}`:X}async function l3($,Z,J,U,X,Y,H){let z=Date.now();try{let W=await Z4(Y).execute($,{cwd:Z||A(),env:J,timeout:U,signal:X,onOutput:(F)=>{H?.(F)}}),B=Date.now()-z;if(X.aborted||W.error==="Command was aborted"||W.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:W.stdout,stderr:W.stderr,execution_time:B}};if(W.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:W.stdout,stderr:W.stderr,execution_time:B}};let V=$.length>30?`${$.substring(0,30)}...`:$,E=W.exitCode===0?`执行命令成功 (${B}ms): ${V}`:`执行命令完成 (退出码 ${W.exitCode}, ${B}ms): ${V}`,O={command:$,execution_time:B,exit_code:W.exitCode,stdout_length:W.stdout.length,stderr_length:W.stderr.length,has_stderr:W.stderr.length>0,acp_mode:!0,summary:E},G=c$.truncateForLLM(W.stdout.trim(),W.stderr.trim(),$),K={stdout:G.stdout,stderr:G.stderr,execution_time:B,exit_code:W.exitCode,...G.truncationInfo&&{truncation_info:G.truncationInfo}};return{success:W.success,llmContent:K,...W.success?{}:{error:{type:"execution_error",message:nZ(W.exitCode,void 0,G.stdout,G.stderr)}},metadata:O}}catch(Q){let W=Q,B=Date.now()-z;return{success:!1,llmContent:`Command execution failed: ${W.message}`,error:{type:"execution_error",message:W.message,details:W},metadata:{command:$,execution_time:B,error:W.message}}}}async function n3($,Z,J,U,X,Y,H){return new Promise((z)=>{let Q=Date.now(),W="",B="",V=!1,E=H?.executable??"bash",O=H?.args??["-c",$],G=H?.inheritProcessEnv===!1?r3(process.env):process.env,{child:K,processTree:F}=u0(E,O,{cwd:Z||A(),env:{...G,...J,...H?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),w,q=()=>{return w??=F.terminate(),w};K.stdout?.on("data",(L)=>{W+=L.toString()}),K.stderr?.on("data",(L)=>{B+=L.toString()});let b=setTimeout(()=>{V=!0,q()},U),D=()=>{q(),clearTimeout(b)};if(X.addEventListener)X.addEventListener("abort",D);else if("onabort"in X)X.onabort=D;if(X.aborted)D();K.on("close",async(L,N)=>{if(H?.cleanup(),clearTimeout(b),X.removeEventListener)X.removeEventListener("abort",D);else if("onabort"in X)X.onabort=null;let M=Date.now()-Q;if(V||X.aborted)await q();if(V){z({success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,sandboxed:Boolean(H),timeout:!0,stdout:W,stderr:B,execution_time:M}});return}if(X.aborted){z({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,sandboxed:Boolean(H),aborted:!0,stdout:W,stderr:B,execution_time:M}});return}if(H&&P1(L,B)){z({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:B.trim()||"Workspace sandbox failed to start"},metadata:{command:$,sandbox_required:!0,sandboxed:!1,execution_time:M,exit_code:L,stderr:B,summary:"Workspace sandbox failed closed"}});return}let R=$.length>30?`${$.substring(0,30)}...`:$,T=L===0?`执行命令成功 (${M}ms): ${R}`:`执行命令完成 (退出码 ${L}, ${M}ms): ${R}`,f={command:$,execution_time:M,exit_code:L,signal:N,stdout_length:W.length,stderr_length:B.length,has_stderr:B.length>0,sandboxed:Boolean(H),summary:T},C=c$.truncateForLLM(W.trim(),B.trim(),$),h={stdout:C.stdout,stderr:C.stderr,execution_time:M,exit_code:L,signal:N,...C.truncationInfo&&{truncation_info:C.truncationInfo}},p=L===0;z({success:p,llmContent:h,...p?{}:{error:{type:"execution_error",message:nZ(L,N,C.stdout,C.stderr)}},metadata:f})}),K.on("error",(L)=>{if(H?.cleanup(),clearTimeout(b),X.removeEventListener)X.removeEventListener("abort",D);else if("onabort"in X)X.onabort=null;z({success:!1,llmContent:`Command execution failed: ${L.message}`,error:{type:"execution_error",message:L.message,details:L}})})})}function r3($){return Object.fromEntries(["CI","COLORTERM","FORCE_COLOR","LANG","LANGUAGE","LC_ALL","LC_CTYPE","NO_COLOR","PATH","TERM","TZ"].flatMap((J)=>{let U=$[J];return U===void 0?[]:[[J,U]]}))}var h5=j({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:_.Object({shell_id:_.String({minLength:1,description:"Background Shell ID to terminate"})}),description:{short:"Kills a running background bash shell by its ID",long:`
496
+ `)}`:X}async function l3($,Z,J,U,X,Y,H){let z=Date.now();try{let W=await Z4(Y).execute($,{cwd:Z||A(),env:J,timeout:U,signal:X,onOutput:(F)=>{H?.(F)}}),B=Date.now()-z;if(X.aborted||W.error==="Command was aborted"||W.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:W.stdout,stderr:W.stderr,execution_time:B}};if(W.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:W.stdout,stderr:W.stderr,execution_time:B}};let V=$.length>30?`${$.substring(0,30)}...`:$,E=W.exitCode===0?`执行命令成功 (${B}ms): ${V}`:`执行命令完成 (退出码 ${W.exitCode}, ${B}ms): ${V}`,O={command:$,execution_time:B,exit_code:W.exitCode,stdout_length:W.stdout.length,stderr_length:W.stderr.length,has_stderr:W.stderr.length>0,acp_mode:!0,summary:E},G=c$.truncateForLLM(W.stdout.trim(),W.stderr.trim(),$),K={stdout:G.stdout,stderr:G.stderr,execution_time:B,exit_code:W.exitCode,...G.truncationInfo&&{truncation_info:G.truncationInfo}};return{success:W.success,llmContent:K,...W.success?{}:{error:{type:"execution_error",message:nZ(W.exitCode,void 0,G.stdout,G.stderr)}},metadata:O}}catch(Q){let W=Q,B=Date.now()-z;return{success:!1,llmContent:`Command execution failed: ${W.message}`,error:{type:"execution_error",message:W.message,details:W},metadata:{command:$,execution_time:B,error:W.message}}}}async function n3($,Z,J,U,X,Y,H){return new Promise((z)=>{let Q=Date.now(),W="",B="",V=!1,E=H?.executable??"bash",O=H?.args??["-c",$],G=H?.inheritProcessEnv===!1?r3(process.env):process.env,{child:K,processTree:F}=u0(E,O,{cwd:Z||A(),env:{...G,...J,...H?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),w,q=()=>{return w??=F.terminate(),w};K.stdout?.on("data",(L)=>{W+=L.toString()}),K.stderr?.on("data",(L)=>{B+=L.toString()});let b=setTimeout(()=>{V=!0,q()},U),D=()=>{q(),clearTimeout(b)};if(X.addEventListener)X.addEventListener("abort",D);else if("onabort"in X)X.onabort=D;if(X.aborted)D();K.on("close",async(L,N)=>{if(H?.cleanup(),clearTimeout(b),X.removeEventListener)X.removeEventListener("abort",D);else if("onabort"in X)X.onabort=null;let C=Date.now()-Q;if(V||X.aborted)await q();if(V){z({success:!1,llmContent:`Command execution timed out (${U}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,sandboxed:Boolean(H),timeout:!0,stdout:W,stderr:B,execution_time:C}});return}if(X.aborted){z({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,sandboxed:Boolean(H),aborted:!0,stdout:W,stderr:B,execution_time:C}});return}if(H&&P1(L,B)){z({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:B.trim()||"Workspace sandbox failed to start"},metadata:{command:$,sandbox_required:!0,sandboxed:!1,execution_time:C,exit_code:L,stderr:B,summary:"Workspace sandbox failed closed"}});return}let R=$.length>30?`${$.substring(0,30)}...`:$,T=L===0?`执行命令成功 (${C}ms): ${R}`:`执行命令完成 (退出码 ${L}, ${C}ms): ${R}`,f={command:$,execution_time:C,exit_code:L,signal:N,stdout_length:W.length,stderr_length:B.length,has_stderr:B.length>0,sandboxed:Boolean(H),summary:T},M=c$.truncateForLLM(W.trim(),B.trim(),$),h={stdout:M.stdout,stderr:M.stderr,execution_time:C,exit_code:L,signal:N,...M.truncationInfo&&{truncation_info:M.truncationInfo}},p=L===0;z({success:p,llmContent:h,...p?{}:{error:{type:"execution_error",message:nZ(L,N,M.stdout,M.stderr)}},metadata:f})}),K.on("error",(L)=>{if(H?.cleanup(),clearTimeout(b),X.removeEventListener)X.removeEventListener("abort",D);else if("onabort"in X)X.onabort=null;z({success:!1,llmContent:`Command execution failed: ${L.message}`,error:{type:"execution_error",message:L.message,details:L}})})})}function r3($){return Object.fromEntries(["CI","COLORTERM","FORCE_COLOR","LANG","LANGUAGE","LC_ALL","LC_CTYPE","NO_COLOR","PATH","TERM","TZ"].flatMap((J)=>{let U=$[J];return U===void 0?[]:[[J,U]]}))}var h5=j({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:_.Object({shell_id:_.String({minLength:1,description:"Background Shell ID to terminate"})}),description:{short:"Kills a running background bash shell by its ID",long:`
497
497
  - Kills a running background bash shell by its ID
498
498
  - Takes a shell_id parameter identifying the shell to kill
499
499
  - Returns a success or failure status
@@ -644,20 +644,20 @@ ${X}
644
644
 
645
645
  ${B.additionalContext}`};if(B.warning)console.warn(`[ToolExecutor] PostToolUseFailure hook warning: ${B.warning}`)}catch(B){console.warn("[ToolExecutor] PostToolUseFailure hook execution failed:",B)}return this.addToHistory({executionId:$,toolName:Z,params:J,result:W,startTime:Y,endTime:z,context:U}),this.emit("executionFailed",{executionId:$,toolName:Z,error:H,duration:z-Y,timestamp:z}),W}async executeAll($){return Promise.all($.map((Z)=>this.execute(Z.toolName,Z.params,Z.context)))}async executeParallel($,Z=5){let J=Z>0?Z:Number.POSITIVE_INFINITY;if(!Number.isFinite(J)||J>=$.length)return this.executeAll($);let U=Array($.length),X=0,Y=async()=>{while(X<$.length){let H=X++,z=$[H];U[H]=await this.execute(z.toolName,z.params,z.context)}};return await Promise.all(Array.from({length:Math.min(J,$.length)},()=>Y())),U}getSchedulerStats(){return this.scheduler.getStats()}getExecutionHistory($){return $?this.executionHistory.slice(-$):[...this.executionHistory]}clearHistory(){this.executionHistory.length=0,this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let J of this.executionHistory){if(J.result.success)$.successfulExecutions++;else $.failedExecutions++;Z+=J.endTime-J.startTime,$.toolUsage.set(J.toolName,($.toolUsage.get(J.toolName)||0)+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}getRegistry(){return this.registry}dispose(){if(this.disposed)return;this.disposed=!0,this.onDispose?.(),this.removeAllListeners()}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory.splice(0,this.executionHistory.length-this.maxHistorySize)}}import{EventEmitter as NX}from"events";var U2=new Set(["Read","Edit","Write","ApplyPatch","Glob","Grep","Bash","WriteStdin","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree"]);class Y6{loadedTools=new Set(U2);deferredTools=new Set;register($){if(U2.has($))this.loadedTools.add($);else this.deferredTools.add($)}unregister($){if(U2.has($))return;this.loadedTools.delete($),this.deferredTools.delete($)}syncDynamicTools($,Z){let J=new Set(Z);for(let U of $)if(!J.has(U))this.unregister(U);for(let U of Z)if(!this.loadedTools.has(U)&&!this.deferredTools.has(U))this.register(U)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,Z){return $.filter((J)=>this.isLoaded(J.name)).map((J)=>J.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
646
646
  `)}reset(){this.loadedTools=new Set(U2),this.deferredTools.clear()}}class K$ extends NX{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new Y6;pendingMcpCatalogChanges=[];pendingMcpContentChanges=[];pendingMcpResourceUpdates=[];pendingMcpConnectionChanges=[];pendingMcpLogs=[];pendingMcpInstructionChanges=[];pendingMcpTaskChanges=[];mcpCatalogBarrier=async()=>{return};constructor(){super()}get deferredToolManager(){return this._deferredManager}setMcpCatalogBarrier($){this.mcpCatalogBarrier=$}waitForMcpCatalogIdle(){return this.mcpCatalogBarrier()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Z=[];for(let J of $)try{this.register(J)}catch(U){Z.push(`${J.name}: ${U.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($)??this.mcpTools.get($);if(!Z)return!1;let J=this.tools.delete($)?"builtin":"mcp";return this.mcpTools.delete($),this.removeFromIndexes(Z),this._deferredManager.unregister($),this.emit("toolUnregistered",{type:J,toolName:$,timestamp:Date.now()}),!0}get($){return this.tools.get($)||this.mcpTools.get($)}has($){return this.tools.has($)||this.mcpTools.has($)}getAll(){return[...Array.from(this.tools.values()),...Array.from(this.mcpTools.values())]}getBuiltinTools(){return Array.from(this.tools.values())}getMcpTools(){return Array.from(this.mcpTools.values())}getByCategory($){let Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((J)=>{let U=typeof J.description==="string"?J.description:J.description.short;return J.name.toLowerCase().includes(Z)||U.toLowerCase().includes(Z)||J.displayName.toLowerCase().includes(Z)||J.category&&J.category.toLowerCase().includes(Z)||J.tags.some((X)=>X.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();return this._deferredManager.filterDeclarations(this.getAll(),$)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new K$;$.setMcpCatalogBarrier(this.mcpCatalogBarrier);for(let Z of this.tools.values())$.register(Z);for(let Z of this.mcpTools.values())$.registerMcpTool(Z);return $}registerMcpTool($){if(this.tools.has($.name))throw Error(`MCP 工具 '${$.name}' 与内置工具冲突`);if(this.mcpTools.has($.name))this.removeFromIndexes(this.mcpTools.get($.name)),this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}replaceMcpTools($,Z){let J=new Map;for(let X of $){if(J.has(X.name))throw Error(`MCP catalog contains duplicate tool '${X.name}'`);if(this.tools.has(X.name))throw Error(`MCP tool '${X.name}' conflicts with a builtin tool`);J.set(X.name,X)}let U=[...this.mcpTools.keys()];for(let X of this.mcpTools.values())this.removeFromIndexes(X);this.mcpTools=J;for(let X of J.values())this.updateIndexes(X);if(this._deferredManager.syncDynamicTools(U,[...J.keys()]),Z){if(this.pendingMcpCatalogChanges.push(structuredClone(Z)),this.pendingMcpCatalogChanges.length>32)this.pendingMcpCatalogChanges.shift()}this.emit("mcpCatalogReplaced",{toolCount:J.size,change:Z,timestamp:Date.now()})}drainMcpCatalogChanges(){let $=this.pendingMcpCatalogChanges;return this.pendingMcpCatalogChanges=[],$}queueMcpContentChange($){if(this.pendingMcpContentChanges.push(structuredClone($)),this.pendingMcpContentChanges.length>32)this.pendingMcpContentChanges.shift()}drainMcpContentChanges(){let $=this.pendingMcpContentChanges;return this.pendingMcpContentChanges=[],$}queueMcpResourceUpdated($){if(!this.pendingMcpResourceUpdates.some((J)=>J.serverName===$.serverName&&J.uri===$.uri))this.pendingMcpResourceUpdates.push(structuredClone($));if(this.pendingMcpResourceUpdates.length>32)this.pendingMcpResourceUpdates.shift()}drainMcpResourceUpdates(){let $=this.pendingMcpResourceUpdates;return this.pendingMcpResourceUpdates=[],$}queueMcpConnectionChange($){if(this.pendingMcpConnectionChanges.push(structuredClone($)),this.pendingMcpConnectionChanges.length>32)this.pendingMcpConnectionChanges.shift()}drainMcpConnectionChanges(){let $=this.pendingMcpConnectionChanges;return this.pendingMcpConnectionChanges=[],$}queueMcpLog($){if(this.pendingMcpLogs.push(structuredClone($)),this.pendingMcpLogs.length>64)this.pendingMcpLogs.shift()}drainMcpLogs(){let $=this.pendingMcpLogs;return this.pendingMcpLogs=[],$}queueMcpInstructionsChange($){if(this.pendingMcpInstructionChanges.push(structuredClone($)),this.pendingMcpInstructionChanges.length>32)this.pendingMcpInstructionChanges.shift()}drainMcpInstructionsChanges(){let $=this.pendingMcpInstructionChanges;return this.pendingMcpInstructionChanges=[],$}queueMcpTaskChange($){if(this.pendingMcpTaskChanges.push(structuredClone($)),this.pendingMcpTaskChanges.length>64)this.pendingMcpTaskChanges.shift()}drainMcpTaskChanges(){let $=this.pendingMcpTaskChanges;return this.pendingMcpTaskChanges=[],$}removeMcpTools($){let Z=0,J=O8($);for(let U of this.mcpTools.keys())if(U.startsWith(J)){let X=this.mcpTools.get(U);this.mcpTools.delete(U),this.removeFromIndexes(X),this._deferredManager.unregister(U),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:U,serverName:$,timestamp:Date.now()})}return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let J=this.tags.get(Z);if(J){if(J.delete($.name),J.size===0)this.tags.delete(Z)}}}}import*as K8 from"crypto";import{nanoid as jX}from"nanoid";class H6{assemble($){if($.length===0)return null;let Z=this.assembleSession($),J=this.assembleConversation($),U=this.assembleToolCalls($);return{session:Z,conversation:J,toolCalls:U}}assembleContextData($,Z,J){let U=this.assemble($);if(!U)return null;return{layers:{system:Z,session:U.session,conversation:U.conversation,tool:{recentCalls:U.toolCalls,toolStates:{},dependencies:{}},workspace:J},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let Z=$.find((H)=>H.type==="session_created"),J=Z?.sessionId??$[0].sessionId,U=new Date(Z?.timestamp??$[0].timestamp).getTime(),X=$.filter((H)=>H.type==="session_updated"),Y=X.length>0?X[X.length-1]:null;return{sessionId:J,userId:void 0,preferences:{},configuration:Y?.data??{},startTime:U}}assembleConversation($){let Z=new Map,J;for(let H of $){if(H.type==="message_created")Z.set(H.data.messageId,{id:H.data.messageId,role:H.data.role,content:"",timestamp:new Date(H.timestamp).getTime(),metadata:H.data.model||H.data.inboxMessageId||H.data.metadata&&typeof H.data.metadata==="object"&&!Array.isArray(H.data.metadata)?{...H.data.metadata&&typeof H.data.metadata==="object"&&!Array.isArray(H.data.metadata)?H.data.metadata:{},...H.data.model?{model:H.data.model}:{},...H.data.inboxMessageId?{inboxMessageId:H.data.inboxMessageId}:{}}:void 0});if(H.type==="part_created"){let{partType:z,messageId:Q,payload:W}=H.data,B=Z.get(Q);if(z==="text"&&B){let V=W;B.content=V.text??""}if(z==="image"&&B)B.content=B.content?`${B.content}
647
- [Image]`:"[Image]";if(z==="summary"){let V=W;if(V.text)J=V.text}}if(H.type==="part_updated"){let{partType:z,messageId:Q,payload:W}=H.data,B=Z.get(Q);if(z==="text"&&B){let V=W;B.content=V.text??""}}}let U=Array.from(Z.values()),X=$[$.length-1],Y=new Date(X.timestamp).getTime();return{messages:U,summary:J,topics:[],lastActivity:Y}}assembleToolCalls($){let Z=new Map;for(let J of $){if(J.type!=="part_created")continue;let{partType:U,partId:X,payload:Y}=J.data;if(U==="tool_call"){let H=Y,z=H.toolCallId??X;Z.set(z,{id:z,name:H.toolName??"unknown",input:H.input??null,timestamp:new Date(J.timestamp).getTime(),status:"pending"})}if(U==="tool_result"){let H=Y,z=H.toolCallId??X,Q=Z.get(z);if(Q)Q.output=H.output??void 0,Q.status=H.error?"error":"success",Q.error=H.error??void 0;else Z.set(z,{id:z,name:H.toolName??"unknown",input:null,output:H.output??void 0,timestamp:new Date(J.timestamp).getTime(),status:H.error?"error":"success",error:H.error??void 0})}}return Array.from(Z.values())}}class z6{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,J=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=J}async compress($){let Z=$.layers.conversation.messages,J=$.layers.tool.recentCalls,U=Z.filter((V)=>V.role==="system"),X=Z.filter((V)=>V.role!=="system"),Y=this.getRecentMessages(X),H=X.slice(0,-this.recentMessagesLimit),z=await this.generateSummary(H),Q=this.extractKeyPoints(H,J),W=this.generateToolSummary(J),B=this.estimateTokenCount(z,Q,Y,W);return{summary:z,keyPoints:Q,recentMessages:[...U,...Y],toolSummary:W,tokenCount:B}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,J=new Set,U=new Set;for(let Y of $){let H=Y.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,50);if(V)Z.add(V)}}),["创建","删除","修改","更新","实现","开发"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,30);if(V)J.add(V)}}),["决定","选择","确定","采用","使用"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,40);if(V)U.add(V)}})}let X=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)X+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(J.size>0)X+=` 执行操作:${Array.from(J).slice(0,3).join("、")}。`;if(U.size>0)X+=` 关键决策:${Array.from(U).slice(0,2).join("、")}。`;return X.length>this.maxSummaryLength?X.substring(0,this.maxSummaryLength)+"...":X}extractKeyPoints($,Z){let J=new Set;for(let X of $)if(X.role==="user")this.extractQuestions(X.content).forEach((z)=>J.add(`用户问题:${z}`)),this.extractRequests(X.content).forEach((z)=>J.add(`用户请求:${z}`));else if(X.role==="assistant")this.extractSolutions(X.content).forEach((H)=>J.add(`解决方案:${H}`));return this.summarizeToolUsage(Z).forEach((X)=>J.add(`工具使用:${X}`)),Array.from(J).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,J=Date.now()-600000;for(let X of $){let Y=Z.get(X.name)||{count:0,success:0,recent:0};if(Y.count++,X.status==="success")Y.success++;if(X.timestamp>J)Y.recent++;Z.set(X.name,Y)}let U=[];for(let[X,Y]of Array.from(Z.entries())){let H=Math.round(Y.success/Y.count*100);U.push(`${X}(${Y.count}次,成功率${H}%)`)}return`工具调用:${U.join("、")}`}estimateTokenCount($,Z,J,U){let X=$.length+Z.join(" ").length;if(U)X+=U.length;for(let Y of J)X+=Y.content.length;return Math.ceil(X/4)}extractContext($,Z,J){let U=$.indexOf(Z);if(U===-1)return null;let X=Math.max(0,U-J/2),Y=Math.min($.length,U+J/2);return $.substring(X,Y).trim()}extractQuestions($){let Z=[],J=["?","?","如何","怎么","什么","为什么"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractRequests($){let Z=[],J=["请","帮我","需要","想要","希望","能否"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractSolutions($){let Z=[],J=["可以","建议","推荐","应该","最好","解决方案"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>10&&Y.length<150)Z.push(Y)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],J=$.filter((U)=>Date.now()-U.timestamp<1800000);if(J.length>0){let U=new Map;J.forEach((X)=>{let Y=U.get(X.name)||[];Y.push(X),U.set(X.name,Y)});for(let[X,Y]of Array.from(U.entries())){let H=Y.filter((z)=>z.status==="success").length;Z.push(`${X}(${Y.length}次,${H}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let J=$.layers.conversation.messages.reduce((U,X)=>U+X.content.length,0);return Math.ceil(J/4)}}class v${defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let J={...this.defaultOptions,...Z},U={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,J),tool:J.includeTools?this.filterTools($.layers.tool,J):{recentCalls:[],toolStates:{},dependencies:{}},workspace:J.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return U.metadata.totalTokens=this.estimateTokens(U),U}filterConversation($,Z){let J=[...$.messages];if(Z.timeWindow>0){let U=Date.now()-Z.timeWindow;J=J.filter((X)=>X.timestamp>=U||X.role==="system")}if(Z.priority>1)J=this.filterByPriority(J,Z.priority);if(Z.maxMessages>0)J=this.limitMessages(J,Z.maxMessages);if(Z.maxTokens>0)J=this.limitByTokens(J,Z.maxTokens);return{messages:J,summary:$.summary,topics:this.updateTopics(J,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let J=[...$.recentCalls];if(Z.timeWindow>0){let Q=Date.now()-Z.timeWindow;J=J.filter((W)=>W.timestamp>=Q)}let U=J.filter((Q)=>Q.status==="success"),X=J.filter((Q)=>Q.status==="error"),Y=Math.min(20,U.length),H=Math.min(10,X.length);return{recentCalls:[...U.slice(-Y),...X.slice(-H)].sort((Q,W)=>Q.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((J)=>{if(J.role==="system")return!0;return this.calculateMessagePriority(J)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let J=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Y)=>J.includes(Y)))Z+=2;if(J.includes("```")||J.includes("function")||J.includes("class"))Z+=1;let X=(Date.now()-$.timestamp)/3600000;if(X<1)Z+=2;else if(X<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let J=$.filter((H)=>H.role==="system"),U=$.filter((H)=>H.role!=="system"),X=Z-J.length,Y=X>0?U.slice(-X):[];return[...J,...Y].sort((H,z)=>H.timestamp-z.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let J=0,U=[];for(let X=$.length-1;X>=0;X--){let Y=$[X],H=this.estimateMessageTokens(Y);if(Y.role==="system")if(J+H<=Z)U.unshift(Y),J+=H;else{let z=this.compressMessage(Y,Z-J);U.unshift(z),J+=this.estimateMessageTokens(z)}else if(J+H<=Z)U.unshift(Y),J+=H;else break}return U.sort((X,Y)=>X.timestamp-Y.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let J=Z*4;if($.content.length<=J)return $;let U=$.content.substring(0,J-3)+"...";return{...$,content:U,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let J=new Set(Z);for(let U of $)this.extractTopicsFromMessage(U).forEach((Y)=>J.add(Y));return Array.from(J).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),J=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((X)=>{if(Z.includes(X))J.push(X)}),J}estimateTokens($){let Z=0;for(let U of $.layers.conversation.messages)Z+=this.estimateMessageTokens(U);let J=JSON.stringify($.layers.system);if(Z+=Math.ceil(J.length/4),$.layers.tool.recentCalls.length>0){let U=JSON.stringify($.layers.tool);Z+=Math.ceil(U.length/8)}return Z}static createPresets(){return{lightweight:new v$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new v$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new v$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new v$({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class Q6{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,J){let U=Date.now(),X={data:Z,timestamp:U,accessCount:0,lastAccess:U,ttl:J||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,X)}get($){let Z=this.cache.get($);if(!Z)return null;let J=Date.now();if(J-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=J,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,J){let U=`summary:${$}:${Z.length}`;this.set(U,{summary:J,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let J=`summary:${$}:${Z}`;return this.get(J)}cacheToolResult($,Z,J){let U=this.hashInput(Z),X=`tool:${$}:${U}`;this.set(X,J,1800000)}getToolResult($,Z){let J=this.hashInput(Z),U=`tool:${$}:${J}`;return this.get(U)}cacheCompressedContext($,Z){let J=`compressed:${$}`;this.set(J,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,J=[];for(let[U,X]of Array.from(this.cache.entries()))$+=X.accessCount,Z+=this.estimateItemSize(X),J.push({key:U,accessCount:X.accessCount,lastAccess:X.lastAccess});return J.sort((U,X)=>X.accessCount-U.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:J.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[J,U]of Array.from(this.cache.entries()))if($-U.timestamp>U.ttl)Z.push(J);Z.forEach((J)=>this.cache.delete(J))}evictLeastUsed(){let $=null,Z=1/0,J=Date.now();for(let[U,X]of Array.from(this.cache.entries())){let Y=1/(J-X.lastAccess+1),H=X.accessCount,z=Y*H;if(z<Z)Z=z,$=U}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),J=0;for(let U=0;U<Z.length;U++){let X=Z.charCodeAt(U);J=(J<<5)-J+X,J=J&J}return Math.abs(J).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let J=this.cache.get($);if(J)return J.ttl=Z,J.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let J=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,J)}warmup($){$.forEach(({key:Z,value:J,ttl:U})=>{this.set(Z,J,U)})}}class W6{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}class q1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||O0();this.options={projectPath:$.projectPath||A(),storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new W6(this.options.storage.maxMemorySize),this.persistent=new G8(this.options.projectPath,100),this.cache=new Q6(this.options.storage.cacheSize,300000),this.compressor=new z6,this.filter=new v$(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let U=J.sessionId||this.generateSessionId(),X=Date.now(),Y={layers:{system:await this.createSystemContext(),session:{sessionId:U,userId:$,preferences:Z,configuration:J,startTime:X},conversation:{messages:[],topics:[],lastActivity:X},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:X}};return this.memory.setContext(Y),await this.persistent.initSession(U),this.currentSessionId=U,console.log(`新会话已创建: ${U}`),U}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new H6().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let U={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(U);let X=this.memory.getContext();if(X&&this.shouldCompress(X))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,U=null,X,Y,H){return this.persistent.saveMessage($,Z,J,U,X,Y,H)}async saveToolUse($,Z,J,U=null,X){return this.persistent.saveToolUse($,Z,J,U,X)}async saveToolResult($,Z,J,U,X=null,Y,H,z,Q){return this.persistent.saveToolResult($,Z,J,U,X,Y,H,z,Q)}async saveCompaction($,Z,J,U=null){return this.persistent.saveCompaction($,Z,J,U)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),U=this.shouldCompress(J),X;if(U){let Y=this.hashContext(J);if(X=this.cache.getCompressedContext(Y)??void 0,!X)X=await this.compressor.compress(J),this.cache.cacheCompressedContext(Y,X)}return{context:J,compressed:X,tokenCount:X?X.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),U=[];for(let X of J){let Y=await this.persistent.getSessionSummary(X);if(Y){let H=this.calculateRelevance($,Y.topics);if(H>0)U.push({sessionId:X,summary:`${Y.messageCount}条消息,主题:${Y.topics.join("、")}`,lastActivity:Y.lastActivity,relevanceScore:H})}}return U.sort((X,Y)=>Y.relevanceScore-X.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return Y$()}generateMessageId(){return jX()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=this.options.projectPath;return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return K8.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),U=0;for(let X of Z)if(J.includes(X.toLowerCase())||X.toLowerCase().includes(J))U+=1;return U}}class w1{chatService;contextManager;memoryAdapter;constructor($,Z,J){this.chatService=$,this.contextManager=Z||new q1({projectPath:J||A()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}class A8 extends Error{constructor($){super(`Task admission queue is full (max ${$})`);this.name="TaskAdmissionQueueFullError"}}class N8 extends Error{constructor($){super(`Task already owns an admission slot or queue entry: ${$}`);this.name="TaskAdmissionConflictError"}}class D1 extends Error{constructor($="Task admission was cancelled"){super($);this.name="TaskAdmissionCancelledError"}}class j8{maxConcurrent=3;maxQueued=100;inFlight=0;queue=[];activeKeys=new Set;explicitlyConfigured=!1;admit($){if(this.validateLimits($.maxConcurrent,$.maxQueued),!this.explicitlyConfigured)this.applyConfiguration($.maxConcurrent,$.maxQueued);if(!$.key.trim())throw Error("Task admission key must not be blank");if(this.activeKeys.has($.key))throw new N8($.key);if(this.inFlight>=this.maxConcurrent&&this.queue.length>=this.maxQueued)throw new A8(this.maxQueued);let Z,J,U=new Promise((z,Q)=>{Z=z,J=Q});U.catch(()=>{return});let X={key:$.key,signal:$.signal,onUpdate:$.onUpdate,resolve:Z,reject:J,snapshot:this.snapshot("queued",1),settled:!1},Y=(z)=>{this.cancelPending(X,new D1(z||void 0))},H={ready:U,getSnapshot:()=>({...X.snapshot}),cancel:Y,release:()=>{if(X.permit)X.permit.release();else Y("Task admission released before execution")}};if(this.activeKeys.add($.key),$.signal?.aborted)return Y(String($.signal.reason||"Task admission was cancelled")),H;if($.signal)X.abortListener=()=>Y(String($.signal?.reason||"Task admission was cancelled")),$.signal.addEventListener("abort",X.abortListener,{once:!0});if(this.inFlight<this.maxConcurrent)this.startPending(X);else this.queue.push(X),this.publishQueueSnapshots();return H}configure($,Z){this.validateLimits($,Z),this.explicitlyConfigured=!0,this.applyConfiguration($,Z)}applyConfiguration($,Z){this.maxConcurrent=$,this.maxQueued=Z,this.drain(),this.publishQueueSnapshots()}getStats(){return{inFlight:this.inFlight,queued:this.queue.length,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}resetForTests(){for(let $ of[...this.queue])this.cancelPending($,new D1("Scheduler reset"));this.queue.length=0,this.activeKeys.clear(),this.inFlight=0,this.maxConcurrent=3,this.maxQueued=100,this.explicitlyConfigured=!1}startPending($){if($.settled)return;this.detachAbort($),this.inFlight++;let Z=!1,J={release:()=>{if(Z)return;Z=!0,$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),this.inFlight=Math.max(0,this.inFlight-1),this.drain(),this.publishQueueSnapshots()}};$.permit=J,$.snapshot=this.snapshot("running"),this.publish($),$.resolve(J),this.publishQueueSnapshots()}cancelPending($,Z){if($.settled)return;if($.permit)return;let J=this.queue.indexOf($);if(J>=0)this.queue.splice(J,1);$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),$.reject(Z),this.publishQueueSnapshots()}drain(){while(this.inFlight<this.maxConcurrent&&this.queue.length>0){let $=this.queue.shift();if($&&!$.settled)this.startPending($)}}publishQueueSnapshots(){for(let[$,Z]of this.queue.entries())Z.snapshot=this.snapshot("queued",$+1),this.publish(Z)}snapshot($,Z){return{state:$,...Z!==void 0?{queuePosition:Z}:{},queueDepth:this.queue.length,inFlight:this.inFlight,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}publish($){try{$.onUpdate?.({...$.snapshot})}catch{}}detachAbort($){if($.abortListener&&$.signal)$.signal.removeEventListener("abort",$.abortListener);$.abortListener=void 0}validateLimits($,Z){if(!b8($))throw Error(`maxConcurrent must be an integer between ${F8} and ${q8}`);if(!L8(Z))throw Error(`maxQueued must be an integer between ${w8} and ${D8}`)}}var l$=new j8;var x=g("Agent");class b0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;legacyMcpRegistry;agentResources;subagentRegistry;constructor($,Z={},J,U){this.config=$,this.runtimeOptions=Z,this.toolExecutor=J||this.createDefaultToolExecutor(),this.sessionRuntime=U,this.agentResources=U?.getAgentResources(),this.subagentRegistry=this.agentResources?.subagents}createDefaultToolExecutor(){let $=new K$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new F1($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?B6(Z):F$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){let J=T8(),U=L0($,this.config,J?"auto":"off");if(this.log(`${Z} ${U.displayName} (${$.model})`),U.model.reasoning&&!J)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(U.chat.reasoningEnabled)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=U.model.contextWindow,this.chatService=await Y2(U.chat);let X=this.executionEngine?.getContextManager();this.executionEngine=new w1(this.chatService,X),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=B6($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}async switchModel($){if(!this.isInitialized)throw Error("Agent未初始化");await this.switchModelIfNeeded($)}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await X2(),n$().length===0)throw Error(`没有可用的模型配置
647
+ [Image]`:"[Image]";if(z==="summary"){let V=W;if(V.text)J=V.text}}if(H.type==="part_updated"){let{partType:z,messageId:Q,payload:W}=H.data,B=Z.get(Q);if(z==="text"&&B){let V=W;B.content=V.text??""}}}let U=Array.from(Z.values()),X=$[$.length-1],Y=new Date(X.timestamp).getTime();return{messages:U,summary:J,topics:[],lastActivity:Y}}assembleToolCalls($){let Z=new Map;for(let J of $){if(J.type!=="part_created")continue;let{partType:U,partId:X,payload:Y}=J.data;if(U==="tool_call"){let H=Y,z=H.toolCallId??X;Z.set(z,{id:z,name:H.toolName??"unknown",input:H.input??null,timestamp:new Date(J.timestamp).getTime(),status:"pending"})}if(U==="tool_result"){let H=Y,z=H.toolCallId??X,Q=Z.get(z);if(Q)Q.output=H.output??void 0,Q.status=H.error?"error":"success",Q.error=H.error??void 0;else Z.set(z,{id:z,name:H.toolName??"unknown",input:null,output:H.output??void 0,timestamp:new Date(J.timestamp).getTime(),status:H.error?"error":"success",error:H.error??void 0})}}return Array.from(Z.values())}}class z6{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,J=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=J}async compress($){let Z=$.layers.conversation.messages,J=$.layers.tool.recentCalls,U=Z.filter((V)=>V.role==="system"),X=Z.filter((V)=>V.role!=="system"),Y=this.getRecentMessages(X),H=X.slice(0,-this.recentMessagesLimit),z=await this.generateSummary(H),Q=this.extractKeyPoints(H,J),W=this.generateToolSummary(J),B=this.estimateTokenCount(z,Q,Y,W);return{summary:z,keyPoints:Q,recentMessages:[...U,...Y],toolSummary:W,tokenCount:B}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,J=new Set,U=new Set;for(let Y of $){let H=Y.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,50);if(V)Z.add(V)}}),["创建","删除","修改","更新","实现","开发"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,30);if(V)J.add(V)}}),["决定","选择","确定","采用","使用"].forEach((B)=>{if(H.includes(B)){let V=this.extractContext(H,B,40);if(V)U.add(V)}})}let X=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)X+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(J.size>0)X+=` 执行操作:${Array.from(J).slice(0,3).join("、")}。`;if(U.size>0)X+=` 关键决策:${Array.from(U).slice(0,2).join("、")}。`;return X.length>this.maxSummaryLength?X.substring(0,this.maxSummaryLength)+"...":X}extractKeyPoints($,Z){let J=new Set;for(let X of $)if(X.role==="user")this.extractQuestions(X.content).forEach((z)=>J.add(`用户问题:${z}`)),this.extractRequests(X.content).forEach((z)=>J.add(`用户请求:${z}`));else if(X.role==="assistant")this.extractSolutions(X.content).forEach((H)=>J.add(`解决方案:${H}`));return this.summarizeToolUsage(Z).forEach((X)=>J.add(`工具使用:${X}`)),Array.from(J).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,J=Date.now()-600000;for(let X of $){let Y=Z.get(X.name)||{count:0,success:0,recent:0};if(Y.count++,X.status==="success")Y.success++;if(X.timestamp>J)Y.recent++;Z.set(X.name,Y)}let U=[];for(let[X,Y]of Array.from(Z.entries())){let H=Math.round(Y.success/Y.count*100);U.push(`${X}(${Y.count}次,成功率${H}%)`)}return`工具调用:${U.join("、")}`}estimateTokenCount($,Z,J,U){let X=$.length+Z.join(" ").length;if(U)X+=U.length;for(let Y of J)X+=Y.content.length;return Math.ceil(X/4)}extractContext($,Z,J){let U=$.indexOf(Z);if(U===-1)return null;let X=Math.max(0,U-J/2),Y=Math.min($.length,U+J/2);return $.substring(X,Y).trim()}extractQuestions($){let Z=[],J=["?","?","如何","怎么","什么","为什么"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractRequests($){let Z=[],J=["请","帮我","需要","想要","希望","能否"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractSolutions($){let Z=[],J=["可以","建议","推荐","应该","最好","解决方案"],U=$.split(/[。!.!]/);for(let X of U)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>10&&Y.length<150)Z.push(Y)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],J=$.filter((U)=>Date.now()-U.timestamp<1800000);if(J.length>0){let U=new Map;J.forEach((X)=>{let Y=U.get(X.name)||[];Y.push(X),U.set(X.name,Y)});for(let[X,Y]of Array.from(U.entries())){let H=Y.filter((z)=>z.status==="success").length;Z.push(`${X}(${Y.length}次,${H}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let J=$.layers.conversation.messages.reduce((U,X)=>U+X.content.length,0);return Math.ceil(J/4)}}class v${defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let J={...this.defaultOptions,...Z},U={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,J),tool:J.includeTools?this.filterTools($.layers.tool,J):{recentCalls:[],toolStates:{},dependencies:{}},workspace:J.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return U.metadata.totalTokens=this.estimateTokens(U),U}filterConversation($,Z){let J=[...$.messages];if(Z.timeWindow>0){let U=Date.now()-Z.timeWindow;J=J.filter((X)=>X.timestamp>=U||X.role==="system")}if(Z.priority>1)J=this.filterByPriority(J,Z.priority);if(Z.maxMessages>0)J=this.limitMessages(J,Z.maxMessages);if(Z.maxTokens>0)J=this.limitByTokens(J,Z.maxTokens);return{messages:J,summary:$.summary,topics:this.updateTopics(J,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let J=[...$.recentCalls];if(Z.timeWindow>0){let Q=Date.now()-Z.timeWindow;J=J.filter((W)=>W.timestamp>=Q)}let U=J.filter((Q)=>Q.status==="success"),X=J.filter((Q)=>Q.status==="error"),Y=Math.min(20,U.length),H=Math.min(10,X.length);return{recentCalls:[...U.slice(-Y),...X.slice(-H)].sort((Q,W)=>Q.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((J)=>{if(J.role==="system")return!0;return this.calculateMessagePriority(J)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let J=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Y)=>J.includes(Y)))Z+=2;if(J.includes("```")||J.includes("function")||J.includes("class"))Z+=1;let X=(Date.now()-$.timestamp)/3600000;if(X<1)Z+=2;else if(X<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let J=$.filter((H)=>H.role==="system"),U=$.filter((H)=>H.role!=="system"),X=Z-J.length,Y=X>0?U.slice(-X):[];return[...J,...Y].sort((H,z)=>H.timestamp-z.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let J=0,U=[];for(let X=$.length-1;X>=0;X--){let Y=$[X],H=this.estimateMessageTokens(Y);if(Y.role==="system")if(J+H<=Z)U.unshift(Y),J+=H;else{let z=this.compressMessage(Y,Z-J);U.unshift(z),J+=this.estimateMessageTokens(z)}else if(J+H<=Z)U.unshift(Y),J+=H;else break}return U.sort((X,Y)=>X.timestamp-Y.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let J=Z*4;if($.content.length<=J)return $;let U=$.content.substring(0,J-3)+"...";return{...$,content:U,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let J=new Set(Z);for(let U of $)this.extractTopicsFromMessage(U).forEach((Y)=>J.add(Y));return Array.from(J).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),J=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((X)=>{if(Z.includes(X))J.push(X)}),J}estimateTokens($){let Z=0;for(let U of $.layers.conversation.messages)Z+=this.estimateMessageTokens(U);let J=JSON.stringify($.layers.system);if(Z+=Math.ceil(J.length/4),$.layers.tool.recentCalls.length>0){let U=JSON.stringify($.layers.tool);Z+=Math.ceil(U.length/8)}return Z}static createPresets(){return{lightweight:new v$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new v$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new v$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new v$({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class Q6{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,J){let U=Date.now(),X={data:Z,timestamp:U,accessCount:0,lastAccess:U,ttl:J||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,X)}get($){let Z=this.cache.get($);if(!Z)return null;let J=Date.now();if(J-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=J,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,J){let U=`summary:${$}:${Z.length}`;this.set(U,{summary:J,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let J=`summary:${$}:${Z}`;return this.get(J)}cacheToolResult($,Z,J){let U=this.hashInput(Z),X=`tool:${$}:${U}`;this.set(X,J,1800000)}getToolResult($,Z){let J=this.hashInput(Z),U=`tool:${$}:${J}`;return this.get(U)}cacheCompressedContext($,Z){let J=`compressed:${$}`;this.set(J,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,J=[];for(let[U,X]of Array.from(this.cache.entries()))$+=X.accessCount,Z+=this.estimateItemSize(X),J.push({key:U,accessCount:X.accessCount,lastAccess:X.lastAccess});return J.sort((U,X)=>X.accessCount-U.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:J.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[J,U]of Array.from(this.cache.entries()))if($-U.timestamp>U.ttl)Z.push(J);Z.forEach((J)=>this.cache.delete(J))}evictLeastUsed(){let $=null,Z=1/0,J=Date.now();for(let[U,X]of Array.from(this.cache.entries())){let Y=1/(J-X.lastAccess+1),H=X.accessCount,z=Y*H;if(z<Z)Z=z,$=U}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),J=0;for(let U=0;U<Z.length;U++){let X=Z.charCodeAt(U);J=(J<<5)-J+X,J=J&J}return Math.abs(J).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let J=this.cache.get($);if(J)return J.ttl=Z,J.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let J=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,J)}warmup($){$.forEach(({key:Z,value:J,ttl:U})=>{this.set(Z,J,U)})}}class W6{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}class q1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||O0();this.options={projectPath:$.projectPath||A(),storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new W6(this.options.storage.maxMemorySize),this.persistent=new G8(this.options.projectPath,100),this.cache=new Q6(this.options.storage.cacheSize,300000),this.compressor=new z6,this.filter=new v$(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let U=J.sessionId||this.generateSessionId(),X=Date.now(),Y={layers:{system:await this.createSystemContext(),session:{sessionId:U,userId:$,preferences:Z,configuration:J,startTime:X},conversation:{messages:[],topics:[],lastActivity:X},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:X}};return this.memory.setContext(Y),await this.persistent.initSession(U),this.currentSessionId=U,console.log(`新会话已创建: ${U}`),U}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new H6().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let U={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(U);let X=this.memory.getContext();if(X&&this.shouldCompress(X))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,U=null,X,Y,H){return this.persistent.saveMessage($,Z,J,U,X,Y,H)}async saveToolUse($,Z,J,U=null,X){return this.persistent.saveToolUse($,Z,J,U,X)}async saveToolResult($,Z,J,U,X=null,Y,H,z,Q){return this.persistent.saveToolResult($,Z,J,U,X,Y,H,z,Q)}async saveCompaction($,Z,J,U=null){return this.persistent.saveCompaction($,Z,J,U)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),U=this.shouldCompress(J),X;if(U){let Y=this.hashContext(J);if(X=this.cache.getCompressedContext(Y)??void 0,!X)X=await this.compressor.compress(J),this.cache.cacheCompressedContext(Y,X)}return{context:J,compressed:X,tokenCount:X?X.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),U=[];for(let X of J){let Y=await this.persistent.getSessionSummary(X);if(Y){let H=this.calculateRelevance($,Y.topics);if(H>0)U.push({sessionId:X,summary:`${Y.messageCount}条消息,主题:${Y.topics.join("、")}`,lastActivity:Y.lastActivity,relevanceScore:H})}}return U.sort((X,Y)=>Y.relevanceScore-X.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return Y$()}generateMessageId(){return jX()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=this.options.projectPath;return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return K8.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),U=0;for(let X of Z)if(J.includes(X.toLowerCase())||X.toLowerCase().includes(J))U+=1;return U}}class w1{chatService;contextManager;memoryAdapter;constructor($,Z,J){this.chatService=$,this.contextManager=Z||new q1({projectPath:J||A()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}class A8 extends Error{constructor($){super(`Task admission queue is full (max ${$})`);this.name="TaskAdmissionQueueFullError"}}class N8 extends Error{constructor($){super(`Task already owns an admission slot or queue entry: ${$}`);this.name="TaskAdmissionConflictError"}}class D1 extends Error{constructor($="Task admission was cancelled"){super($);this.name="TaskAdmissionCancelledError"}}class j8{maxConcurrent=3;maxQueued=100;inFlight=0;queue=[];activeKeys=new Set;explicitlyConfigured=!1;admit($){if(this.validateLimits($.maxConcurrent,$.maxQueued),!this.explicitlyConfigured)this.applyConfiguration($.maxConcurrent,$.maxQueued);if(!$.key.trim())throw Error("Task admission key must not be blank");if(this.activeKeys.has($.key))throw new N8($.key);if(this.inFlight>=this.maxConcurrent&&this.queue.length>=this.maxQueued)throw new A8(this.maxQueued);let Z,J,U=new Promise((z,Q)=>{Z=z,J=Q});U.catch(()=>{return});let X={key:$.key,signal:$.signal,onUpdate:$.onUpdate,resolve:Z,reject:J,snapshot:this.snapshot("queued",1),settled:!1},Y=(z)=>{this.cancelPending(X,new D1(z||void 0))},H={ready:U,getSnapshot:()=>({...X.snapshot}),cancel:Y,release:()=>{if(X.permit)X.permit.release();else Y("Task admission released before execution")}};if(this.activeKeys.add($.key),$.signal?.aborted)return Y(String($.signal.reason||"Task admission was cancelled")),H;if($.signal)X.abortListener=()=>Y(String($.signal?.reason||"Task admission was cancelled")),$.signal.addEventListener("abort",X.abortListener,{once:!0});if(this.inFlight<this.maxConcurrent)this.startPending(X);else this.queue.push(X),this.publishQueueSnapshots();return H}configure($,Z){this.validateLimits($,Z),this.explicitlyConfigured=!0,this.applyConfiguration($,Z)}applyConfiguration($,Z){this.maxConcurrent=$,this.maxQueued=Z,this.drain(),this.publishQueueSnapshots()}getStats(){return{inFlight:this.inFlight,queued:this.queue.length,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}resetForTests(){for(let $ of[...this.queue])this.cancelPending($,new D1("Scheduler reset"));this.queue.length=0,this.activeKeys.clear(),this.inFlight=0,this.maxConcurrent=3,this.maxQueued=100,this.explicitlyConfigured=!1}startPending($){if($.settled)return;this.detachAbort($),this.inFlight++;let Z=!1,J={release:()=>{if(Z)return;Z=!0,$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),this.inFlight=Math.max(0,this.inFlight-1),this.drain(),this.publishQueueSnapshots()}};$.permit=J,$.snapshot=this.snapshot("running"),this.publish($),$.resolve(J),this.publishQueueSnapshots()}cancelPending($,Z){if($.settled)return;if($.permit)return;let J=this.queue.indexOf($);if(J>=0)this.queue.splice(J,1);$.settled=!0,this.detachAbort($),this.activeKeys.delete($.key),$.reject(Z),this.publishQueueSnapshots()}drain(){while(this.inFlight<this.maxConcurrent&&this.queue.length>0){let $=this.queue.shift();if($&&!$.settled)this.startPending($)}}publishQueueSnapshots(){for(let[$,Z]of this.queue.entries())Z.snapshot=this.snapshot("queued",$+1),this.publish(Z)}snapshot($,Z){return{state:$,...Z!==void 0?{queuePosition:Z}:{},queueDepth:this.queue.length,inFlight:this.inFlight,maxConcurrent:this.maxConcurrent,maxQueued:this.maxQueued}}publish($){try{$.onUpdate?.({...$.snapshot})}catch{}}detachAbort($){if($.abortListener&&$.signal)$.signal.removeEventListener("abort",$.abortListener);$.abortListener=void 0}validateLimits($,Z){if(!b8($))throw Error(`maxConcurrent must be an integer between ${F8} and ${q8}`);if(!L8(Z))throw Error(`maxQueued must be an integer between ${w8} and ${D8}`)}}var l$=new j8;var x=g("Agent");class L0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;legacyMcpRegistry;agentResources;subagentRegistry;constructor($,Z={},J,U){this.config=$,this.runtimeOptions=Z,this.toolExecutor=J||this.createDefaultToolExecutor(),this.sessionRuntime=U,this.agentResources=U?.getAgentResources(),this.subagentRegistry=this.agentResources?.subagents}createDefaultToolExecutor(){let $=new K$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new F1($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?B6(Z):F$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){let J=T8(),U=A0($,this.config,J?"auto":"off");if(this.log(`${Z} ${U.displayName} (${$.model})`),U.model.reasoning&&!J)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(U.chat.reasoningEnabled)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=U.model.contextWindow,this.chatService=await Y2(U.chat);let X=this.executionEngine?.getContextManager();this.executionEngine=new w1(this.chatService,X),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=B6($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}async switchModel($){if(!this.isInitialized)throw Error("Agent未初始化");await this.switchModelIfNeeded($)}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await X2(),n$().length===0)throw Error(`没有可用的模型配置
648
648
 
649
649
  `+`请先使用以下命令添加模型:
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 b0(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 b0($.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).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=this.sessionRuntime.beginTurn();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 M=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()=>M(await this.sessionRuntime.drainSteering(R)),drainOrSeal:async()=>{let I=await this.sessionRuntime.drainSteeringOrSeal(R);return{...I,messages:await M(I.messages)}}}:void 0},C;if(O.permissionMode==="plan")C=yield*this.runPlanLoop(E,O,f);else C=yield*this.runLoop(E,O,f);if(C.success&&C.metadata?.targetMode&&O.permissionMode==="plan"){let I=C.metadata.targetMode,o=C.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 q0=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},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")q0=E+H0;else q0=[...E,{type:"text",text:H0}]}C=yield*this.runLoop(q0,O,{...f,inputMessageId:void 0})}if(!this.sessionRuntime||!R)return C;if(C.success&&!O.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(R);let h=await this.sessionRuntime.recordGoalProgress({tokens:C.metadata?.tokensUsed??0,elapsedMs:C.metadata?.duration??0});if(h)yield{kind:"goal_updated",goal:h};if(!C.success||O.signal?.aborted){if(h=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":C.error?.message??"goal paused after turn failure"),h)yield{kind:"goal_updated",goal:h}}let p=C.success&&!O.signal?.aborted&&D<20;if(b=await this.sessionRuntime.finishTurn(R,{continuePending:p}),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(!C.success||O.signal?.aborted)return C;if(h=await this.sessionRuntime.getGoal(),!h||h.status!=="active"&&h.status!=="verifying")return C;if(w=await this.sessionRuntime.beginGoalContinuation(),!w)return C;b=this.sessionRuntime.beginTurn(),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-nmmj1x0c.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(`
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;if(M.success&&!O.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(R);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-4faz5tkt.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>
@@ -688,7 +688,7 @@ Warning: Some files could not be loaded:
688
688
  `):O.stdout,K=/^Binary files .+ differ$/m.test(G)||G.includes("GIT binary patch"),F=K?{additions:0,deletions:0}:cX(G),w=x8(G,I8);return{path:V,patch:w.patch,...F,binary:K,truncated:w.truncated}})),Q=gX,W=Y.length>H.length,B=z.map((V)=>{let E=x8(V.patch,Q);return Q=Math.max(0,Q-Buffer.byteLength(E.patch)),W||=E.truncated,E.truncated?{...V,patch:E.patch,truncated:!0}:V});return{baseCommit:$.baseCommit,files:B,truncated:W}}async inspectChanges($){let[Z,J,U,X]=await Promise.all([v($.worktreeRoot,["diff","--name-only","-z",$.baseCommit,"--"]),v($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`]),v($.worktreeRoot,["diff","--numstat",$.baseCommit,"--"]),v($.worktreeRoot,["ls-files","--others","--exclude-standard","-z"])]);if(Z.code!==0||J.code!==0||U.code!==0||X.code!==0)return null;let Y=0,H=0;for(let z of U.stdout.split(`
689
689
  `)){let[Q,W]=z.split("\t");if(/^\d+$/.test(Q??""))Y+=Number(Q);if(/^\d+$/.test(W??""))H+=Number(W)}for(let z of X.stdout.split("\x00").filter(Boolean))try{let Q=E0($.worktreeRoot,z),W=await V6(Q);if(!W.isFile()||W.size>10485760)continue;let B=await PX(Q);if(B.includes(0))continue;let V=B.toString("utf8");if(V.length>0)Y+=V.split(`
690
690
  `).length-(V.endsWith(`
691
- `)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...X.stdout.split("\x00").filter(Boolean)]).size,additions:Y,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var n0=new d8;function nX($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class m8{manager;constructor($=n0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:nX($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,U=await this.manager.getChangeSummary(J);if($.success&&this.isClean(U))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:U?.changedFiles,commits:U?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var r$=new m8;var A0=g("Agent");function rX($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}class s{static instance=null;runningAgents=new Map;sessionStore=i0.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!s.instance)s.instance=new s;return s.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let U of $)if(U.status==="running"){let X=this.runningAgents.has(U.id),Y=Z-U.lastActiveAt,H=U.processId!==void 0&&rX(U.processId),z=U.processId===void 0&&Y<=1800000;if(!X&&!H&&!z)A0.warn(`Cleaning up orphaned agent session: ${U.id}`),this.sessionStore.updateSession(U.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:U,parentSessionId:X,parentProjectPath:Y,permissionMode:H,reasoningEffort:z,serviceTier:Q,responseVerbosity:W,communicationStyle:B,agentId:V,existingMessages:E,taskListId:O,workspaceRoot:G=A(),isolation:K=Z.isolation??"none",restoredWorktree:F,rootAgentId:w,resumedFrom:q,resumeDepth:b=0,agentResources:D,modelResources:L,lspResources:N,onEvent:M,onCompleted:R}=$,T=V||Y$("agent");if(this.runningAgents.has(T)||this.sessionStore.loadSession(T))throw Error(`Subagent session already exists: ${T}`);let f=new AbortController,C={schemaVersion:2,id:T,subagentType:Z.name,description:J,prompt:U,messages:E||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,parentSessionId:X,parentProjectPath:Y,rootAgentId:w??T,resumedFrom:q,resumeDepth:b,configSnapshot:$2(Z),taskListId:O,workspaceRoot:G,isolation:K,worktree:F};this.sessionStore.saveSession(C);let h=Date.now(),p=this.executeAgent(T,Z,U,X,H,z,Q,W,B,f.signal,E,O,G,K,F,D,L,N,M,R);return this.runningAgents.set(T,{id:T,promise:p,abortController:f,startTime:h}),p.then(()=>this.runningAgents.delete(T),()=>this.runningAgents.delete(T)),A0.info(`Background agent started: ${T} (${Z.name})`),T}async executeAgent($,Z,J,U,X,Y,H,z,Q,W,B,V,E=A(),O="none",G,K,F,w,q,b){let D=Date.now(),L,N,M,R=!1,T=async(f)=>{if(!M||R)return;let C=await r$.finalize({agentId:$,lease:M,success:f});return R=!0,this.sessionStore.updateSession($,{worktree:C.worktree}),C};try{if(W.aborted)throw Error("Agent execution was cancelled");M=await r$.prepare({agentId:$,sourceWorkspaceRoot:E,isolation:O,restoredWorktree:G}),this.sessionStore.updateSession($,{worktree:M.worktree});let f=Z.systemPrompt?.trim(),C=Z.model&&Z.model!=="inherit"?Z.model:void 0,h=Z.permissionMode??X,p=this.sessionStore.loadSession($);L=await w$.create({sessionId:$,workspaceRoot:M.workspaceRoot,modelId:C,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,agentResources:K,modelResources:F,lspResources:w,...(B?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:U?{parentSessionId:U,subagentType:Z.name,isSidechain:!1,resumedFrom:p?.resumedFrom,rootAgentId:p?.rootAgentId??$,resumeDepth:p?.resumeDepth??0}:void 0}),N=await b0.createWithRuntime(L,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:C,maxTurns:Z.maxTurns,permissionMode:h,...f?{appendSystemPrompt:f}:{}});let I={messages:B||[],userId:"subagent",sessionId:$,taskListId:V,workspaceRoot:M.workspaceRoot,worktreeActive:Boolean(M.worktree),permissionMode:h,subagentInfo:{parentSessionId:U||"",subagentType:Z.name,isSidechain:!1,resumedFrom:p?.resumedFrom,rootAgentId:p?.rootAgentId??$,resumeDepth:p?.resumeDepth??0}},o=new Set,q0=new Set,H0=await r0(N.chatStream(J,I,{signal:W,...Z.name===a$?{outputSchema:W2}:{}}),async(I0)=>{if(I0.kind==="tool_result"&&"function"in I0.toolCall)_2(q0,I0.toolCall.function.name,I0.result,I.workspaceRoot),V2(o,I0.toolCall.function.name,I0.result,I.workspaceRoot);try{await q?.(I0,$)}catch(h2){A0.warn(`Subagent event observer failed: ${$}`,h2)}});this.sessionStore.updateSession($,{messages:I.messages});let s0=Date.now()-D,r=H0.success?{success:!0,message:H0.finalMessage||"",agentId:$,verificationCommands:[...o],verificationVerdict:Z.name===a$?B2(H0.metadata?.structuredOutput):q$(Z.name)?E2(H0.finalMessage):void 0,modifiedFiles:[...q0],stats:{tokens:H0.metadata?.tokensUsed||0,toolCalls:H0.metadata?.toolCallsCount||0,duration:s0}}:{success:!1,message:"",agentId:$,error:H0.error?.message||"Unknown error",stats:{duration:s0}},o0=await T(r.success);if(o0?.preserved)r.worktreePath=o0.worktreePath,r.worktreeBranch=o0.worktreeBranch,r.worktree=o0.worktree;let x2=this.sessionStore.markCompleted($,{success:r.success,message:r.message,error:r.error,verificationCommands:r.verificationCommands,verificationVerdict:r.verificationVerdict,modifiedFiles:r.modifiedFiles},r.stats);if(x2)try{await b?.(x2)}catch(I0){A0.warn(`Subagent completion observer failed: ${$}`,I0)}return A0.info(`Background agent completed: ${$} (success=${r.success})`),r}catch(f){let C=Date.now()-D,h=f instanceof Error?f.message:String(f),p;try{p=await T(!1)}catch(o){A0.warn(`Failed to preserve worktree for background agent ${$}`,o)}let I=this.sessionStore.markCompleted($,{success:!1,message:"",error:h},{duration:C});if(I)try{await b?.(I)}catch(o){A0.warn(`Subagent completion observer failed: ${$}`,o)}return A0.warn(`Background agent failed: ${$}`,f),{success:!1,message:"",agentId:$,error:h,stats:{duration:C},worktreePath:p?.worktreePath,worktreeBranch:p?.worktreeBranch,worktree:p?.worktree}}finally{try{if(N&&typeof N.destroy==="function")await N.destroy()}finally{await L?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return r5(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let U=this.runningAgents.get($);if(!U)return this.getAgent($,J);if(Z>0){let X=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([U.promise,X])==="timeout")return this.getAgent($,J)}else await U.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:U,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,newAgentId:W=Y$("agent"),agentResources:B,modelResources:V,lspResources:E,onEvent:O,onCompleted:G}=$,K=n5($.owner),F=this.getAgent(Z,K);if(!F){A0.warn(`Cannot resume agent ${Z}: session not found`);return}if(F.subagentType!==U.name){A0.warn(`Cannot resume agent ${Z}: requested type ${U.name} does not match ${F.subagentType}`);return}if(this.isRunning(Z)||F.status==="running"){A0.warn(`Cannot resume agent ${Z}: still running`);return}if(W===Z){A0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let w=F.configSnapshot?{...F.configSnapshot}:U;return{agentId:this.startBackgroundAgent({config:w,description:F.description,prompt:J,parentSessionId:K.sessionId,parentProjectPath:K.projectPath,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,agentId:W,existingMessages:F.messages,taskListId:F.taskListId,workspaceRoot:F.workspaceRoot,isolation:F.isolation,restoredWorktree:F.worktree,rootAgentId:F.rootAgentId,resumedFrom:F.id,resumeDepth:F.resumeDepth+1,agentResources:B,modelResources:V,lspResources:E,onEvent:O,onCompleted:G}),source:F}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let U=this.sessionStore.loadSession($);if(U&&U.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),A0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:r5(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),U=0;for(let X of this.listForSession($)){if(X.status==="running")continue;if(J-X.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(X.id))U++}return U}}class E6{config;agentResources;modelResources;lspResources;constructor($,Z,J,U){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=U}async execute($){let Z=Date.now(),J=$.subagentSessionId??Y$("agent"),U,X,Y;try{let H=this.getAppendSystemPrompt(),z=$.workspaceRoot||A(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:$.modelId,W=this.config.permissionMode??$.permissionMode,B={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};X=await w$.create({sessionId:J,workspaceRoot:z,modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:B,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),U=await b0.createWithRuntime(X,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:W,...H?{appendSystemPrompt:H}:{}});let V="",E=0,O=0,G=new Set,K=new Set;Y={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:z,completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:W,subagentInfo:B,signal:$.signal};let F=async(D)=>{if(D.kind==="tool_result"&&"function"in D.toolCall)_2(K,D.toolCall.function.name,D.result,z),V2(G,D.toolCall.function.name,D.result,z);await $.onEvent?.(D)},w=this.config.name===a$?U.chatStream($.prompt,Y,{outputSchema:W2}):U.chatStream($.prompt,Y),q=await r0(w,F);if(q.success)V=q.finalMessage||"",E=q.metadata?.toolCallsCount||0,O=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let b=Date.now()-Z;return{success:!0,message:V,agentId:J,messages:Y.messages,verificationCommands:[...G],verificationVerdict:this.config.name===a$?B2(q.metadata?.structuredOutput):q$(this.config.name)?E2(V):void 0,modifiedFiles:[...K],stats:{tokens:O,toolCalls:E,duration:b}}}catch(H){let z=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:Y?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:z}}}finally{if(U&&typeof U.destroy==="function")await U.destroy().catch(()=>{return});await X?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as D$}from"node:path";function _6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?D$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?D$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,U=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${U>0?` to ${U} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?D$(J):"file"}`}case"Bash":{let{command:J,description:U}=Z;if(U)return`${U}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:U}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(U){let Y=D$(U);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:U}=Z;return J?`Updating task ${U||""}: ${J}`.trim():`Updating task ${U||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?D$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:U}=Z,X=Z.resume_from||Z.resume;if(X)return`Resuming ${U||"agent"} from ${X}`;if(J)return`${U||"Agent"}: ${J}`;return`Running ${U||"agent"}`}case"LSP":{let{operation:J,filePath:U}=Z,X=U?D$(U):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?D$(J):"notebook"}`}default:return`${$}`}}function aX($,Z){if(!Z?.success&&!Z?.metadata)return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function sX($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!g8(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let U=5,X=J.slice(0,U).map((Y)=>Y.relative_path);if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
691
+ `)?1:0)}catch{}return{changedFiles:new Set([...Z.stdout.split("\x00").filter(Boolean),...X.stdout.split("\x00").filter(Boolean)]).size,additions:Y,deletions:H,commits:Number.parseInt(J.stdout.trim(),10)||0}}}var n0=new d8;function nX($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class m8{manager;constructor($=n0){this.manager=$}async prepare($){let Z=$.isolation??"none";if(Z!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot,ownerAgentId:$.agentId};let J=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:nX($.agentId)});return{isolation:Z,workspaceRoot:J.workspaceRoot,ownerAgentId:$.restoredWorktree?.sessionId??$.agentId,worktree:J}}async finalize($){let{worktree:Z}=$.lease;if(!Z)return{preserved:!1,removed:!1};let J=$.lease.ownerAgentId??$.agentId,U=await this.manager.getChangeSummary(J);if($.success&&this.isClean(U))return await this.manager.exit({sessionId:J,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:J,action:"keep"}),{preserved:!0,removed:!1,worktreePath:Z.worktreeRoot,worktreeBranch:Z.branch,worktree:Z,changedFiles:U?.changedFiles,commits:U?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var r$=new m8;var N0=g("Agent");function rX($){try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z&&Z.code==="EPERM"}}class s{static instance=null;runningAgents=new Map;sessionStore=i0.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!s.instance)s.instance=new s;return s.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let U of $)if(U.status==="running"){let X=this.runningAgents.has(U.id),Y=Z-U.lastActiveAt,H=U.processId!==void 0&&rX(U.processId),z=U.processId===void 0&&Y<=1800000;if(!X&&!H&&!z)N0.warn(`Cleaning up orphaned agent session: ${U.id}`),this.sessionStore.updateSession(U.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:U,parentSessionId:X,parentProjectPath:Y,permissionMode:H,reasoningEffort:z,serviceTier:Q,responseVerbosity:W,communicationStyle:B,agentId:V,existingMessages:E,taskListId:O,workspaceRoot:G=A(),isolation:K=Z.isolation??"none",restoredWorktree:F,rootAgentId:w,resumedFrom:q,resumeDepth:b=0,agentResources:D,modelResources:L,lspResources:N,onEvent:C,onCompleted:R}=$,T=V||Y$("agent");if(this.runningAgents.has(T)||this.sessionStore.loadSession(T))throw Error(`Subagent session already exists: ${T}`);let f=new AbortController,M={schemaVersion:2,id:T,subagentType:Z.name,description:J,prompt:U,messages:E||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),processId:process.pid,parentSessionId:X,parentProjectPath:Y,rootAgentId:w??T,resumedFrom:q,resumeDepth:b,configSnapshot:$2(Z),taskListId:O,workspaceRoot:G,isolation:K,worktree:F};this.sessionStore.saveSession(M);let h=Date.now(),p=this.executeAgent(T,Z,U,X,H,z,Q,W,B,f.signal,E,O,G,K,F,D,L,N,C,R);return this.runningAgents.set(T,{id:T,promise:p,abortController:f,startTime:h}),p.then(()=>this.runningAgents.delete(T),()=>this.runningAgents.delete(T)),N0.info(`Background agent started: ${T} (${Z.name})`),T}async executeAgent($,Z,J,U,X,Y,H,z,Q,W,B,V,E=A(),O="none",G,K,F,w,q,b){let D=Date.now(),L,N,C,R=!1,T=async(f)=>{if(!C||R)return;let M=await r$.finalize({agentId:$,lease:C,success:f});return R=!0,this.sessionStore.updateSession($,{worktree:M.worktree}),M};try{if(W.aborted)throw Error("Agent execution was cancelled");C=await r$.prepare({agentId:$,sourceWorkspaceRoot:E,isolation:O,restoredWorktree:G}),this.sessionStore.updateSession($,{worktree:C.worktree});let f=Z.systemPrompt?.trim(),M=Z.model&&Z.model!=="inherit"?Z.model:void 0,h=Z.permissionMode??X,p=this.sessionStore.loadSession($);L=await w$.create({sessionId:$,workspaceRoot:C.workspaceRoot,modelId:M,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,agentResources:K,modelResources:F,lspResources:w,...(B?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:$}}:{},subagentInfo:U?{parentSessionId:U,subagentType:Z.name,isSidechain:!1,resumedFrom:p?.resumedFrom,rootAgentId:p?.rootAgentId??$,resumeDepth:p?.resumeDepth??0}:void 0}),N=await L0.createWithRuntime(L,{sessionId:$,toolWhitelist:Z.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...Z.disallowedTools??[]],modelId:M,maxTurns:Z.maxTurns,permissionMode:h,...f?{appendSystemPrompt:f}:{}});let I={messages:B||[],userId:"subagent",sessionId:$,taskListId:V,workspaceRoot:C.workspaceRoot,worktreeActive:Boolean(C.worktree),permissionMode:h,subagentInfo:{parentSessionId:U||"",subagentType:Z.name,isSidechain:!1,resumedFrom:p?.resumedFrom,rootAgentId:p?.rootAgentId??$,resumeDepth:p?.resumeDepth??0}},o=new Set,w0=new Set,H0=await r0(N.chatStream(J,I,{signal:W,...Z.name===a$?{outputSchema:W2}:{}}),async(I0)=>{if(I0.kind==="tool_result"&&"function"in I0.toolCall)_2(w0,I0.toolCall.function.name,I0.result,I.workspaceRoot),V2(o,I0.toolCall.function.name,I0.result,I.workspaceRoot);try{await q?.(I0,$)}catch(h2){N0.warn(`Subagent event observer failed: ${$}`,h2)}});this.sessionStore.updateSession($,{messages:I.messages});let s0=Date.now()-D,r=H0.success?{success:!0,message:H0.finalMessage||"",agentId:$,verificationCommands:[...o],verificationVerdict:Z.name===a$?B2(H0.metadata?.structuredOutput):q$(Z.name)?E2(H0.finalMessage):void 0,modifiedFiles:[...w0],stats:{tokens:H0.metadata?.tokensUsed||0,toolCalls:H0.metadata?.toolCallsCount||0,duration:s0}}:{success:!1,message:"",agentId:$,error:H0.error?.message||"Unknown error",stats:{duration:s0}},o0=await T(r.success);if(o0?.preserved)r.worktreePath=o0.worktreePath,r.worktreeBranch=o0.worktreeBranch,r.worktree=o0.worktree;let x2=this.sessionStore.markCompleted($,{success:r.success,message:r.message,error:r.error,verificationCommands:r.verificationCommands,verificationVerdict:r.verificationVerdict,modifiedFiles:r.modifiedFiles},r.stats);if(x2)try{await b?.(x2)}catch(I0){N0.warn(`Subagent completion observer failed: ${$}`,I0)}return N0.info(`Background agent completed: ${$} (success=${r.success})`),r}catch(f){let M=Date.now()-D,h=f instanceof Error?f.message:String(f),p;try{p=await T(!1)}catch(o){N0.warn(`Failed to preserve worktree for background agent ${$}`,o)}let I=this.sessionStore.markCompleted($,{success:!1,message:"",error:h},{duration:M});if(I)try{await b?.(I)}catch(o){N0.warn(`Subagent completion observer failed: ${$}`,o)}return N0.warn(`Background agent failed: ${$}`,f),{success:!1,message:"",agentId:$,error:h,stats:{duration:M},worktreePath:p?.worktreePath,worktreeBranch:p?.worktreeBranch,worktree:p?.worktree}}finally{try{if(N&&typeof N.destroy==="function")await N.destroy()}finally{await L?.dispose()}}}getAgent($,Z){let J=this.sessionStore.loadSession($);if(!J||Z===void 0)return J;if(typeof Z==="string")return J.parentSessionId===Z?J:void 0;return r5(J,Z)?J:void 0}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000,J){if(J!==void 0&&!this.getAgent($,J))return;let U=this.runningAgents.get($);if(!U)return this.getAgent($,J);if(Z>0){let X=new Promise((H)=>setTimeout(()=>H("timeout"),Z));if(await Promise.race([U.promise,X])==="timeout")return this.getAgent($,J)}else await U.promise;return this.getAgent($,J)}resumeAgent($){let{agentId:Z,prompt:J,config:U,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,newAgentId:W=Y$("agent"),agentResources:B,modelResources:V,lspResources:E,onEvent:O,onCompleted:G}=$,K=n5($.owner),F=this.getAgent(Z,K);if(!F){N0.warn(`Cannot resume agent ${Z}: session not found`);return}if(F.subagentType!==U.name){N0.warn(`Cannot resume agent ${Z}: requested type ${U.name} does not match ${F.subagentType}`);return}if(this.isRunning(Z)||F.status==="running"){N0.warn(`Cannot resume agent ${Z}: still running`);return}if(W===Z){N0.warn(`Cannot resume agent ${Z}: new run must use a new ID`);return}let w=F.configSnapshot?{...F.configSnapshot}:U;return{agentId:this.startBackgroundAgent({config:w,description:F.description,prompt:J,parentSessionId:K.sessionId,parentProjectPath:K.projectPath,permissionMode:X,reasoningEffort:Y,serviceTier:H,responseVerbosity:z,communicationStyle:Q,agentId:W,existingMessages:F.messages,taskListId:F.taskListId,workspaceRoot:F.workspaceRoot,isolation:F.isolation,restoredWorktree:F.worktree,rootAgentId:F.rootAgentId,resumedFrom:F.id,resumeDepth:F.resumeDepth+1,agentResources:B,modelResources:V,lspResources:E,onEvent:O,onCompleted:G}),source:F}}killAgent($,Z){if(Z&&!this.getAgent($,Z))return!1;let J=this.runningAgents.get($);if(!J){let U=this.sessionStore.loadSession($);if(U&&U.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return J.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),N0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((Z)=>typeof $==="string"?Z.parentSessionId===$:r5(Z,$))}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,Z=604800000){let J=Date.now(),U=0;for(let X of this.listForSession($)){if(X.status==="running")continue;if(J-X.lastActiveAt<=Z)continue;if(this.sessionStore.deleteSession(X.id))U++}return U}}class E6{config;agentResources;modelResources;lspResources;constructor($,Z,J,U){this.config=$;this.agentResources=Z;this.modelResources=J;this.lspResources=U}async execute($){let Z=Date.now(),J=$.subagentSessionId??Y$("agent"),U,X,Y;try{let H=this.getAppendSystemPrompt(),z=$.workspaceRoot||A(),Q=this.config.model&&this.config.model!=="inherit"?this.config.model:$.modelId,W=this.config.permissionMode??$.permissionMode,B={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1,resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId??J,resumeDepth:$.resumeDepth??0};X=await w$.create({sessionId:J,workspaceRoot:z,modelId:Q,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentInfo:B,agentResources:this.agentResources,modelResources:this.modelResources,lspResources:this.lspResources,...($.existingMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}}),U=await L0.createWithRuntime(X,{sessionId:J,toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:Q,maxTurns:this.config.maxTurns,permissionMode:W,...H?{appendSystemPrompt:H}:{}});let V="",E=0,O=0,G=new Set,K=new Set;Y={messages:[...$.existingMessages??[]],userId:"subagent",sessionId:J,workspaceRoot:z,completionRequirements:H,worktreeActive:$.worktreeActive,permissionMode:W,subagentInfo:B,signal:$.signal};let F=async(D)=>{if(D.kind==="tool_result"&&"function"in D.toolCall)_2(K,D.toolCall.function.name,D.result,z),V2(G,D.toolCall.function.name,D.result,z);await $.onEvent?.(D)},w=this.config.name===a$?U.chatStream($.prompt,Y,{outputSchema:W2}):U.chatStream($.prompt,Y),q=await r0(w,F);if(q.success)V=q.finalMessage||"",E=q.metadata?.toolCallsCount||0,O=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let b=Date.now()-Z;return{success:!0,message:V,agentId:J,messages:Y.messages,verificationCommands:[...G],verificationVerdict:this.config.name===a$?B2(q.metadata?.structuredOutput):q$(this.config.name)?E2(V):void 0,modifiedFiles:[...K],stats:{tokens:O,toolCalls:E,duration:b}}}catch(H){let z=Date.now()-Z;return{success:!1,message:"",agentId:J,messages:Y?.messages??[...$.existingMessages??[]],error:H instanceof Error?H.message:String(H),stats:{duration:z}}}finally{if(U&&typeof U.destroy==="function")await U.destroy().catch(()=>{return});await X?.dispose().catch(()=>{return})}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{basename as D$}from"node:path";function _6($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?D$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?D$(J):"file"}`}case"ApplyPatch":{let J=Z.patch,U=J?(J.match(/^\*\*\* (?:Add|Delete|Update) File: /gm)??[]).length:0;return`Applying atomic patch${U>0?` to ${U} file(s)`:""}`}case"Read":{let J=Z.file_path;return`Reading ${J?D$(J):"file"}`}case"Bash":{let{command:J,description:U}=Z;if(U)return`${U}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"WriteStdin":return`Sending input to Shell: ${Z.shell_id||"unknown"}`;case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:U}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(U){let Y=D$(U);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:U}=Z;return J?`Updating task ${U||""}: ${J}`.trim():`Updating task ${U||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?D$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:U}=Z,X=Z.resume_from||Z.resume;if(X)return`Resuming ${U||"agent"} from ${X}`;if(J)return`${U||"Agent"}: ${J}`;return`Running ${U||"agent"}`}case"LSP":{let{operation:J,filePath:U}=Z,X=U?D$(U):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?D$(J):"notebook"}`}default:return`${$}`}}function aX($,Z){if(!Z?.success&&!Z?.metadata)return!1;switch($){case"Write":case"Edit":case"ApplyPatch":case"Read":case"Glob":case"Grep":case"Bash":case"TaskOutput":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!Z.metadata?.detail}}function sX($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!g8(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let U=5,X=J.slice(0,U).map((Y)=>Y.relative_path);if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
692
692
  `)}case"Grep":{let J=Z.llmContent;if(!Array.isArray(J)||!J.length)return null;let U=5,X=J.slice(0,U).map((Y)=>{let H=D$(Y.file_path);if(Y.line_number)return`${H}:${Y.line_number}`;return H});if(J.length>U)X.push(`... (+${J.length-U} more)`);return X.join(`
693
693
  `)}case"Read":{let J=Z.metadata?.content_preview||Z.llmContent;if(typeof J!=="string"||!J)return null;let U=J.split(`
694
694
  `),X=U.length,Y=3;if(X<=Y+1)return J;return`${U.slice(0,Y).join(`
@@ -745,7 +745,7 @@ Usage notes:
745
745
  - Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent
746
746
  - If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
747
747
  - If the user specifies that they want you to run agents "in parallel", you MUST send a single message with multiple Task tool use content blocks. For example, if you need to launch both a code-reviewer agent and a test-runner agent in parallel, send a single message with both tool calls.
748
- `.trim()}function G2($=L$(),Z,J,U,X,Y,H,z){return j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(Q)=>tX($,Q),(Q)=>`Invalid subagent type: "${Q}". Available: ${eX($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(m(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return $Y($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(Q,W){let{subagent_type:B,description:V,prompt:E,run_in_background:O=!1,isolation:G,resume:K,resume_from:F,subagent_session_id:w}=Q,q=F??K,b=JY(W);if(!b)return b$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let D=X?.(),L=Y?.(),N=H?.(),M=z?.(),R=s.getInstance(),T=q?R.getAgent(q,b):void 0;if(q&&!T)return b$(`Cannot resume agent ${q}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${q}`);if(T&&(R.isRunning(T.id)||T.status==="running"))return b$(`Cannot resume agent ${T.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${T.id}`);if(T&&B&&T.subagentType!==B)return b$(`Cannot resume with subagent_type "${B}": source agent used "${T.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let f=T?.subagentType??B;if(!f)return b$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let C=$.getSubagent(f),p=(T?.configSnapshot?{...T.configSnapshot}:void 0)??C;if(!p)return b$(`Unknown subagent type: ${f}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${f}`);let I={...p,model:p.model&&p.model!=="inherit"?p.model:W.modelId??p.model,permissionMode:p.permissionMode??W.permissionMode},o=typeof w==="string"&&w.length>0?w:Y$("agent"),q0=T?.isolation??G??I.isolation??"none",H0=T?.rootAgentId??o,s0=T?T.resumeDepth+1:0,r=UY({owner:b,subagentSessionId:o,type:I.name,description:V,resumedFrom:T?.id,rootAgentId:H0,resumeDepth:s0});if(O){let o0=T?R.resumeAgent({agentId:T.id,prompt:E,config:I,owner:b,permissionMode:W.permissionMode,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:M,newAgentId:o,agentResources:Z,modelResources:J,lspResources:U,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:R.startBackgroundAgent({config:I,description:V,prompt:E,parentSessionId:b.sessionId,parentProjectPath:b.projectPath,permissionMode:W.permissionMode,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:M,agentId:o,workspaceRoot:b.projectPath,isolation:q0,agentResources:Z,modelResources:J,lspResources:U,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!o0)return b$(`Failed to resume agent ${T?.id??o}`,"恢复 Agent 失败");return r.onStarted(),YY({sessionId:o0,config:I,description:V,isolation:q0,resumedFrom:T?.id,rootAgentId:H0,resumeDepth:s0})}return XY({config:I,description:V,prompt:E,context:W,owner:b,subagentSessionId:o,isolation:q0,source:T,eventBridge:r,agentResources:Z,modelResources:J,lspResources:U,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:M})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(Q)=>`${Q.subagent_type||"resume"}:${Q.resume_from||Q.resume||""}:${Q.description}`,abstractPermissionRule:()=>""})}var ZY=G2(r8);function JY($){if(!$.sessionId)return;let Z=$.workspaceRoot||A();if(!l8.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:l8.resolve(Z)}}function b$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function UY($){let Z=oX(8),J=!1,U={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{O2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Q0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...U})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let Y=X.toolCall,H="function"in Y?Y.function.name:"Unknown";if(O2.getState().app.actions.updateSubagentTool(Z,H),Q0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in Y)Q0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:H,arguments:Y.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let Y=X.toolCall;if(!("function"in Y))break;Q0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:c8(i8(Y.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let Y=X.toolCall;if(!("function"in Y))break;Q0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,...X.update});break}case"content_delta":Q0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":Q0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":Q0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(X)=>{if(J)return;J=!0,O2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed"),Q0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:X.result?.message?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...U})}}}async function XY($){let{config:Z,description:J,prompt:U,context:X,owner:Y,subagentSessionId:H,isolation:z,source:Q,eventBridge:W,agentResources:B,modelResources:V,lspResources:E}=$,O=i0.getInstance(),G=Q?.workspaceRoot??Y.projectPath,K=Q?.rootAgentId??H,F=Q?Q.resumeDepth+1:0,w,q=!1,b=!1,D=async(L)=>{if(!w||q)return;let N=await r$.finalize({agentId:H,lease:w,success:L});return q=!0,N};try{w=await r$.prepare({agentId:H,sourceWorkspaceRoot:G,isolation:z,restoredWorktree:Q?.worktree});let L=Date.now();O.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:U,messages:[...Q?.messages??[]],status:"running",createdAt:L,lastActiveAt:L,processId:process.pid,parentSessionId:Y.sessionId,parentProjectPath:Y.projectPath,rootAgentId:K,resumedFrom:Q?.id,resumeDepth:F,configSnapshot:$2(Z),workspaceRoot:G,isolation:z,worktree:w.worktree}),b=!0,W.onStarted(),X.updateOutput?.(`${Q?"恢复":"启动"} ${Z.name} subagent: ${J}`);let N=new E6(Z,B,V,E),M={prompt:U,parentSessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:Q?.id,rootAgentId:K,resumeDepth:F,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),existingMessages:Q?.messages,onEvent:W.onEvent},R=Date.now(),T=await N.execute(M);try{let h=await K0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:w.workspaceRoot,sessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:T.success,resultSummary:T.message.slice(0,500),error:T.error});if(!h.shouldStop&&h.continueReason)T=await N.execute({...M,prompt:h.continueReason,existingMessages:T.messages});if(h.warning)console.warn(`[Task] SubagentStop hook warning: ${h.warning}`)}catch(h){console.warn("[Task] SubagentStop hook execution failed:",h)}let f=await D(T.success);if(f?.preserved)T.worktreePath=f.worktreePath,T.worktreeBranch=f.worktreeBranch,T.worktree=f.worktree;O.updateSession(H,{messages:T.messages??[],worktree:f?.worktree});let C=O.markCompleted(H,{success:T.success,message:T.message,error:T.error,verificationCommands:T.verificationCommands,verificationVerdict:T.verificationVerdict,modifiedFiles:T.modifiedFiles},{...T.stats,duration:Date.now()-R});if(C)W.onCompleted(C);return HY({result:T,sessionId:H,config:Z,description:J,isolation:z,resumedFrom:Q?.id,rootAgentId:K,resumeDepth:F})}catch(L){let N=L,M;try{M=await D(!1)}catch(R){console.warn("[Task] Failed to preserve subagent worktree:",R)}if(b){let R=O.markCompleted(H,{success:!1,message:"",error:N.message});if(R)W.onCompleted(R)}return{...b$(`Subagent execution error: ${N.message}`,`Subagent 执行异常: ${n8(N)}`),metadata:{summary:`Subagent 执行异常: ${n8(N)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:Q?.id,subagentRootId:K,subagentResumeDepth:F,isolation:z,worktreePath:M?.worktreePath,worktreeBranch:M?.worktreeBranch}}}}function YY($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function HY($){let Z=$.result.worktreePath?`
748
+ `.trim()}function G2($=L$(),Z,J,U,X,Y,H,z){return j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,parallelism:"shared",schema:_.Object({subagent_type:_.Optional(_.Refine(_.String({description:"Subagent type to use. Required for a fresh run; optional for resume_from."}),(Q)=>tX($,Q),(Q)=>`Invalid subagent type: "${Q}". Available: ${eX($)}`)),description:_.String({minLength:3,maxLength:100,description:"Short task description (3-5 words)"}),prompt:_.String({minLength:10,description:"Detailed task instructions"}),run_in_background:S(_.Boolean({description:"Set true to run in the background. Use TaskOutput to read output later."}),!1),isolation:_.Optional(m(["none","worktree"],{description:"Filesystem isolation. Use worktree to prevent edits affecting the parent workspace."})),resume:_.Optional(_.String({description:"Deprecated alias for resume_from."})),resume_from:_.Optional(_.String({description:"Completed agent ID to resume. The source type, model, permissions, workspace, and transcript are inherited."})),subagent_session_id:_.Optional(_.String({description:"Internal subagent session id for tracking"}))}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return $Y($)},usageNotes:["subagent_type is required - choose from available agent types",'description should be 3-5 words (e.g., "Explore error handling")',"prompt should contain a highly detailed task description and specify exactly what information to return","Launch multiple agents concurrently when possible for better performance",'Use isolation="worktree" for parallel coding agents that may edit files'],examples:[{description:"Explore codebase for API endpoints",params:{subagent_type:"Explore",description:"Find API endpoints",prompt:"Search the codebase for all API endpoint definitions. Look for route handlers, REST endpoints, and GraphQL resolvers. Return a structured list with file paths, endpoint URLs, HTTP methods, and descriptions."}},{description:"Plan authentication feature",params:{subagent_type:"Plan",description:"Plan user auth",prompt:"Create a detailed implementation plan for adding user authentication to this project. Analyze the existing architecture, then provide step-by-step instructions including: 1) Database schema changes 2) API routes to create 3) Frontend components needed 4) Security considerations 5) Testing strategy. Be specific about file names and code locations."}}]},async execute(Q,W){let{subagent_type:B,description:V,prompt:E,run_in_background:O=!1,isolation:G,resume:K,resume_from:F,subagent_session_id:w}=Q,q=F??K,b=JY(W);if(!b)return b$("Task requires an active parent session and absolute workspace","Subagent 缺少 durable parent session owner");let D=X?.(),L=Y?.(),N=H?.(),C=z?.(),R=s.getInstance(),T=q?R.getAgent(q,b):void 0;if(q&&!T)return b$(`Cannot resume agent ${q}: session not found in this workspace`,`恢复 Agent 失败: 会话不存在 ${q}`);if(T&&(R.isRunning(T.id)||T.status==="running"))return b$(`Cannot resume agent ${T.id}: it is still running`,`恢复 Agent 失败: 仍在运行 ${T.id}`);if(T&&B&&T.subagentType!==B)return b$(`Cannot resume with subagent_type "${B}": source agent used "${T.subagentType}"`,"恢复 Agent 失败: subagent 类型与源运行不一致");let f=T?.subagentType??B;if(!f)return b$("subagent_type is required for a fresh Task run","启动 Agent 失败: 缺少 subagent_type");let M=$.getSubagent(f),p=(T?.configSnapshot?{...T.configSnapshot}:void 0)??M;if(!p)return b$(`Unknown subagent type: ${f}. Available types: ${$.getAllNames().join(", ")||"none"}`,`未知的 subagent 类型: ${f}`);let I={...p,model:p.model&&p.model!=="inherit"?p.model:W.modelId??p.model,permissionMode:p.permissionMode??W.permissionMode},o=typeof w==="string"&&w.length>0?w:Y$("agent"),w0=T?.isolation??G??I.isolation??"none",H0=T?.rootAgentId??o,s0=T?T.resumeDepth+1:0,r=UY({owner:b,subagentSessionId:o,type:I.name,description:V,resumedFrom:T?.id,rootAgentId:H0,resumeDepth:s0});if(O){let o0=T?R.resumeAgent({agentId:T.id,prompt:E,config:I,owner:b,permissionMode:W.permissionMode,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:C,newAgentId:o,agentResources:Z,modelResources:J,lspResources:U,onEvent:r.onEvent,onCompleted:r.onCompleted})?.agentId:R.startBackgroundAgent({config:I,description:V,prompt:E,parentSessionId:b.sessionId,parentProjectPath:b.projectPath,permissionMode:W.permissionMode,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:C,agentId:o,workspaceRoot:b.projectPath,isolation:w0,agentResources:Z,modelResources:J,lspResources:U,onEvent:r.onEvent,onCompleted:r.onCompleted});if(!o0)return b$(`Failed to resume agent ${T?.id??o}`,"恢复 Agent 失败");return r.onStarted(),YY({sessionId:o0,config:I,description:V,isolation:w0,resumedFrom:T?.id,rootAgentId:H0,resumeDepth:s0})}return XY({config:I,description:V,prompt:E,context:W,owner:b,subagentSessionId:o,isolation:w0,source:T,eventBridge:r,agentResources:Z,modelResources:J,lspResources:U,reasoningEffort:D,serviceTier:L,responseVerbosity:N,communicationStyle:C})},version:"5.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:(Q)=>`${Q.subagent_type||"resume"}:${Q.resume_from||Q.resume||""}:${Q.description}`,abstractPermissionRule:()=>""})}var ZY=G2(r8);function JY($){if(!$.sessionId)return;let Z=$.workspaceRoot||A();if(!l8.isAbsolute(Z))return;return{sessionId:$.sessionId,projectPath:l8.resolve(Z)}}function b$($,Z){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:Z}}}function UY($){let Z=oX(8),J=!1,U={resumedFrom:$.resumedFrom,rootAgentId:$.rootAgentId,resumeDepth:$.resumeDepth};return{onStarted:()=>{O2.getState().app.actions.startSubagentProgress(Z,$.type,$.description),Q0.publish($.owner,"subagent.start",{subagentId:Z,subagentSessionId:$.subagentSessionId,type:$.type,description:$.description,...U})},onEvent:(X)=>{switch(X.kind){case"tool_start":{let Y=X.toolCall,H="function"in Y?Y.function.name:"Unknown";if(O2.getState().app.actions.updateSubagentTool(Z,H),Q0.publish($.owner,"subagent.update",{subagentSessionId:$.subagentSessionId,toolName:H}),"function"in Y)Q0.publish($.owner,"subagent.tool.start",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:H,arguments:Y.function.arguments,toolKind:X.toolKind});break}case"tool_result":{let Y=X.toolCall;if(!("function"in Y))break;Q0.publish($.owner,"subagent.tool.result",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,success:!X.result.error,summary:X.result.metadata?.summary,output:c8(i8(Y.function.name,X.result)),metadata:X.result.metadata});break}case"tool_progress":{let Y=X.toolCall;if(!("function"in Y))break;Q0.publish($.owner,"subagent.tool.progress",{subagentSessionId:$.subagentSessionId,toolCallId:Y.id,toolName:Y.function.name,...X.update});break}case"content_delta":Q0.publish($.owner,"subagent.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"thinking_delta":Q0.publish($.owner,"subagent.thinking.delta",{subagentSessionId:$.subagentSessionId,delta:X.delta});break;case"stream_end":Q0.publish($.owner,"subagent.stream.end",{subagentSessionId:$.subagentSessionId});break;default:break}},onCompleted:(X)=>{if(J)return;J=!0,O2.getState().app.actions.completeSubagentProgress(Z,X.status==="completed"),Q0.publish($.owner,"subagent.complete",{subagentSessionId:$.subagentSessionId,success:X.status==="completed",status:X.status,summary:X.result?.message?.slice(0,500),type:X.subagentType,verificationVerdict:X.result?.verificationVerdict,...U})}}}async function XY($){let{config:Z,description:J,prompt:U,context:X,owner:Y,subagentSessionId:H,isolation:z,source:Q,eventBridge:W,agentResources:B,modelResources:V,lspResources:E}=$,O=i0.getInstance(),G=Q?.workspaceRoot??Y.projectPath,K=Q?.rootAgentId??H,F=Q?Q.resumeDepth+1:0,w,q=!1,b=!1,D=async(L)=>{if(!w||q)return;let N=await r$.finalize({agentId:H,lease:w,success:L});return q=!0,N};try{w=await r$.prepare({agentId:H,sourceWorkspaceRoot:G,isolation:z,restoredWorktree:Q?.worktree});let L=Date.now();O.saveSession({schemaVersion:2,id:H,subagentType:Z.name,description:J,prompt:U,messages:[...Q?.messages??[]],status:"running",createdAt:L,lastActiveAt:L,processId:process.pid,parentSessionId:Y.sessionId,parentProjectPath:Y.projectPath,rootAgentId:K,resumedFrom:Q?.id,resumeDepth:F,configSnapshot:$2(Z),workspaceRoot:G,isolation:z,worktree:w.worktree}),b=!0,W.onStarted(),X.updateOutput?.(`${Q?"恢复":"启动"} ${Z.name} subagent: ${J}`);let N=new E6(Z,B,V,E),C={prompt:U,parentSessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,subagentSessionId:H,resumedFrom:Q?.id,rootAgentId:K,resumeDepth:F,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),existingMessages:Q?.messages,onEvent:W.onEvent},R=Date.now(),T=await N.execute(C);try{let h=await K0.getInstance().executeSubagentStopHooks(Z.name,{projectDir:w.workspaceRoot,sessionId:Y.sessionId,permissionMode:Z.permissionMode??X.permissionMode??"default",taskDescription:J,success:T.success,resultSummary:T.message.slice(0,500),error:T.error});if(!h.shouldStop&&h.continueReason)T=await N.execute({...C,prompt:h.continueReason,existingMessages:T.messages});if(h.warning)console.warn(`[Task] SubagentStop hook warning: ${h.warning}`)}catch(h){console.warn("[Task] SubagentStop hook execution failed:",h)}let f=await D(T.success);if(f?.preserved)T.worktreePath=f.worktreePath,T.worktreeBranch=f.worktreeBranch,T.worktree=f.worktree;O.updateSession(H,{messages:T.messages??[],worktree:f?.worktree});let M=O.markCompleted(H,{success:T.success,message:T.message,error:T.error,verificationCommands:T.verificationCommands,verificationVerdict:T.verificationVerdict,modifiedFiles:T.modifiedFiles},{...T.stats,duration:Date.now()-R});if(M)W.onCompleted(M);return HY({result:T,sessionId:H,config:Z,description:J,isolation:z,resumedFrom:Q?.id,rootAgentId:K,resumeDepth:F})}catch(L){let N=L,C;try{C=await D(!1)}catch(R){console.warn("[Task] Failed to preserve subagent worktree:",R)}if(b){let R=O.markCompleted(H,{success:!1,message:"",error:N.message});if(R)W.onCompleted(R)}return{...b$(`Subagent execution error: ${N.message}`,`Subagent 执行异常: ${n8(N)}`),metadata:{summary:`Subagent 执行异常: ${n8(N)}`,subagentSessionId:H,subagentType:Z.name,subagentStatus:"failed",subagentResumedFrom:Q?.id,subagentRootId:K,subagentResumeDepth:F,isolation:z,worktreePath:C?.worktreePath,worktreeBranch:C?.worktreeBranch}}}}function YY($){return{success:!0,llmContent:{agent_id:$.sessionId,status:"running",resumed_from:$.resumedFrom,resume_from_hint:$.sessionId,message:`Agent ${$.resumedFrom?"resumed":"started"} in background. Use TaskOutput(task_id: "${$.sessionId}") to retrieve results.`},metadata:{summary:`${$.resumedFrom?"恢复":"启动"}后台 Agent: ${$.sessionId}`,agent_id:$.sessionId,resume_from_hint:$.sessionId,resumed_from:$.resumedFrom,subagent_type:$.config.name,description:$.description,background:!0,isolation:$.isolation,subagentSessionId:$.sessionId,subagentType:$.config.name,subagentStatus:"running",subagentResumedFrom:$.resumedFrom,subagentRootId:$.rootAgentId,subagentResumeDepth:$.resumeDepth}}}function HY($){let Z=$.result.worktreePath?`
749
749
 
750
750
  Worktree preserved at ${$.result.worktreePath}${$.result.worktreeBranch?` on branch ${$.result.worktreeBranch}`:""}.`:"",J=`
751
751
 
@@ -802,7 +802,7 @@ Use deleted to permanently remove a task. Read the latest state with TaskGet bef
802
802
  - Use block=false for non-blocking check of current status
803
803
  - Task IDs can be found using the /tasks command
804
804
  - Works with all task types: background shells, async agents, and remote sessions
805
- `.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:U,timeout:X}=$,Y=Z.sessionId??"",H=Z.sessionId?{sessionId:Z.sessionId,projectPath:KY.resolve(Z.workspaceRoot||A())}:void 0;if(H){let W=x0.getInstance().get(J,H);if(J.startsWith("mcp_task_")||W)return FY(J,U,X,H,Z.signal)}if(J.startsWith("bash_"))return o8(J,U,X,Y);let z=t.getInstance(),Q=s.getInstance();if(z.getProcess(J,Y))return o8(J,U,X,Y);if(H&&Q.getAgent(J,H))return qY(J,U,X,H);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function FY($,Z,J,U,X){let Y=x0.getInstance(),H=Z?await Y.wait($,U,J,X):Y.get($,U);if(!H)return{success:!1,llmContent:`MCP task not found: ${$}`,error:{type:"validation_error",message:"MCP task does not exist in this Session"},metadata:{summary:`获取 MCP 任务输出: ${$} (未找到)`}};let z={task_id:H.taskId,type:"mcp",server:H.serverName,tool:H.toolName,status:H.status,status_message:H.statusMessage,created_at:new Date(H.createdAt).toISOString(),updated_at:new Date(H.updatedAt).toISOString(),completed_at:H.completedAt?new Date(H.completedAt).toISOString():void 0,result:H.result?.llmContent,error:H.error};return{success:!0,llmContent:z,metadata:{summary:`获取 MCP 任务输出: ${$} (${H.status})`,...z,taskType:"mcp",taskStatus:H.status,...H.result?{mcpResult:{isError:H.result.isError,...H.result.metadata}}:{}}}}async function o8($,Z,J,U){let X=t.getInstance(),Y=X.getProcess($,U);if(!Y)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&Y.status==="running")await wY($,J,U);let H=X.consumeOutput($,U);if(!H)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let z=c$.truncateForLLM(H.stdout,H.stderr,H.command),Q=H.stdoutOmittedBytes??0,W=H.stderrOmittedBytes??0,B={task_id:H.id,type:"shell",status:H.status,command:H.command,pid:H.pid,exit_code:H.exitCode,signal:H.signal,sandboxed:H.sandboxed,started_at:new Date(H.startedAt).toISOString(),finished_at:H.endedAt?new Date(H.endedAt).toISOString():void 0,stdout:z.stdout,stderr:z.stderr,output_truncated:Q>0||W>0||Boolean(z.truncationInfo),stdout_omitted_bytes:Q,stderr_omitted_bytes:W,truncation_info:z.truncationInfo};return{success:!0,llmContent:B,metadata:{summary:`获取任务输出: ${$}`,...B}}}async function qY($,Z,J,U){let X=s.getInstance(),Y=X.getAgent($,U);if(!Y)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&Y.status==="running"){if(Y=await X.waitForCompletion($,J,U),!Y)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let H={task_id:Y.id,type:"agent",status:Y.status,subagent_type:Y.subagentType,description:Y.description,created_at:new Date(Y.createdAt).toISOString(),last_active_at:new Date(Y.lastActiveAt).toISOString(),completed_at:Y.completedAt?new Date(Y.completedAt).toISOString():void 0,result:Y.result,stats:Y.stats,isolation:Y.isolation,worktree_path:Y.worktree?.worktreeRoot,worktree_branch:Y.worktree?.branch,resumed_from:Y.resumedFrom,root_agent_id:Y.rootAgentId,resume_depth:Y.resumeDepth,resume_from_hint:Y.id},z=Y.status==="completed"?"completed":Y.status==="failed"?"failed":"running";return{success:!0,llmContent:H,metadata:{summary:`获取任务输出: ${$}`,...H,subagentSessionId:Y.id,subagentType:Y.subagentType,subagentStatus:z,subagentResumedFrom:Y.resumedFrom,subagentRootId:Y.rootAgentId,subagentResumeDepth:Y.resumeDepth,subagentSummary:typeof Y.result?.message==="string"?Y.result.message.slice(0,500):void 0,verificationCommands:Y.result?.verificationCommands,verificationVerdict:Y.result?.verificationVerdict,modifiedFiles:Y.result?.modifiedFiles,verificationAgentBuiltin:q$(Y.subagentType)&&Y.configSnapshot?.source==="builtin"}}}async function wY($,Z,J){let U=t.getInstance(),X=Date.now();return new Promise((Y)=>{let H=setInterval(()=>{let z=U.getProcess($,J);if(!z||z.status!=="running"){clearInterval(H),Y();return}if(Date.now()-X>=Z){clearInterval(H),Y();return}},100)})}import*as t8 from"os";import*as e8 from"path";import*as A$ from"fs/promises";import*as b1 from"path";class N0{static instances=new Map;teamsDir;constructor($){this.teamsDir=b1.join($,"teams")}static getInstance($){if(!N0.instances.has($))N0.instances.set($,new N0($));return N0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return b1.join(this.teamsDir,N0.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),U=this.getTeamFilePath(Z),X={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead-${Z}`,leadSessionId:$.leadSessionId,teamFilePath:U,members:[{id:`team-lead-${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(X),X}async loadTeam($){try{let Z=await A$.readFile(this.getTeamFilePath($),"utf-8");return DY(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await A$.mkdir(b1.dirname(Z),{recursive:!0,mode:493}),await A$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await A$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let U=await this.loadTeam(J.name);if(U)Z.push(U)}return Z.sort((J,U)=>U.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),U={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((X)=>X.status==="running"?{...X,status:"cancelled",completedAt:X.completedAt||J}:X)};return await this.saveTeam(U),U}async getUniqueTeamName($){let Z=N0.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,U=2;while(await this.loadTeam(J))J=`${Z}-${U}`,U+=1;return J}}function DY($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var bY=_.Object({name:_.String({minLength:1,description:"Human-readable teammate name, e.g. researcher or test-runner"}),subagent_type:_.String({minLength:1,description:"Registered subagent type to launch for this teammate"}),description:_.Optional(_.String({minLength:3,maxLength:100})),prompt:_.String({minLength:10,description:"Detailed assignment for this teammate"})});function q6($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||e8.join(t8.homedir(),".blade"),U=$?.subagentRegistry??L$();return[LY({sessionId:Z,configDir:J,subagentRegistry:U,agentResources:$?.agentResources,modelResources:$?.modelResources,lspResources:$?.lspResources,getReasoningEffort:$?.getReasoningEffort,getServiceTier:$?.getServiceTier,getResponseVerbosity:$?.getResponseVerbosity,getCommunicationStyle:$?.getCommunicationStyle}),AY({configDir:J}),NY({configDir:J})]}function LY($){return j({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Name for the new agent team"}),description:_.Optional(_.String({description:"Team description or purpose"})),agent_type:_.Optional(_.String({description:"Optional role/type label for the team lead"})),members:S(_.Array(bY,{description:"Initial teammates to launch as background agents"}),[])}),description:{short:"Create an agent team and optionally launch teammate subagents",long:CY(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{jY($.subagentRegistry);let U=MY(Z.members.map((E)=>E.name));if(U)return b2(`Duplicate teammate name: ${U}`,"创建团队失败");let X=Z.members.map((E)=>E.subagent_type).filter((E)=>!$.subagentRegistry.getSubagent(E));if(X.length>0)return b2(`Invalid subagent type(s): ${[...new Set(X)].join(", ")}. Available: ${$.subagentRegistry.getAllNames().join(", ")||"none"}`,"创建团队失败");let Y=s.getInstance(),H=N0.getInstance($.configDir),z=await H.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),Q=Date.now(),W=[];for(let E of Z.members){let O=$.subagentRegistry.getSubagent(E.subagent_type);if(!O)continue;let G={...O,model:O.model&&O.model!=="inherit"?O.model:J.modelId??O.model,permissionMode:O.permissionMode??J.permissionMode},K=`team-${N0.sanitizeName(E.name)}-${z.name}`,F=TY({teamName:z.name,teamDescription:Z.description,memberName:E.name,memberPrompt:E.prompt,teamFileHint:z.teamFilePath}),w=Y.startBackgroundAgent({config:G,description:E.description||E.name,prompt:F,parentSessionId:J.sessionId||$.sessionId,parentProjectPath:J.workspaceRoot||A(),permissionMode:J.permissionMode,reasoningEffort:$.getReasoningEffort?.(),serviceTier:$.getServiceTier?.(),responseVerbosity:$.getResponseVerbosity?.(),communicationStyle:$.getCommunicationStyle?.(),agentId:K,taskListId:z.name,workspaceRoot:J.workspaceRoot||A(),isolation:G.isolation,agentResources:$.agentResources,modelResources:$.modelResources,lspResources:$.lspResources});W.push({id:K,name:E.name,subagentType:E.subagent_type,description:E.description||E.name,prompt:E.prompt,agentId:w,status:"running",joinedAt:Q})}let B={...z,members:[...z.members,...W],updatedAt:Date.now()};await H.saveTeam(B);let V=await F6(H,B);return{success:!0,llmContent:{team:o$(V),message:W.length>0?`Team created with ${W.length} teammate(s). Use TeamStatus(team_name: "${V.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${V.name}".`},metadata:{summary:`创建 Agent Team: ${V.name} (${W.length} teammates)`,team_name:V.name,team_file_path:V.teamFilePath,lead_agent_id:V.leadAgentId,member_agent_ids:W.map((E)=>E.agentId).filter(Boolean)}}}catch(U){return w6(U,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function AY($){return j({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({team_name:_.Optional(_.String({description:"Team name to inspect. Omit to list all teams."}))}),description:{short:"List agent teams or inspect one team with teammate statuses",long:"Use this after TeamCreate to monitor teammate background agents and find their TaskOutput IDs."},async execute(Z){try{let J=N0.getInstance($.configDir);if(!Z.team_name){let Y=await Promise.all((await J.listTeams()).map((H)=>F6(J,H)));return{success:!0,llmContent:{teams:Y.map(o$)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(o$)}}}let U=await J.loadTeam(Z.team_name);if(!U)return b2(`Team not found: ${Z.team_name}`,"读取团队失败");let X=await F6(J,U);return{success:!0,llmContent:{team:o$(X)},metadata:{summary:`Agent Team ${X.name}: ${$9(X)}`,team:o$(X)}}}catch(J){return w6(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function NY($){return j({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Team name to delete"}),kill_running:S(_.Boolean({description:"Whether to cancel running teammate agents"}),!0)}),description:{short:"Mark an agent team deleted and optionally cancel running teammates",long:"Use this when coordinated team work is finished or should be stopped."},async execute(Z){try{let J=N0.getInstance($.configDir),U=await J.loadTeam(Z.team_name);if(!U)return b2(`Team not found: ${Z.team_name}`,"删除团队失败");let X=s.getInstance(),Y=[];if(Z.kill_running){for(let z of U.members)if(z.agentId&&X.killAgent(z.agentId))Y.push(z.agentId)}let H=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:H?o$(H):null,killed_agent_ids:Y},metadata:{summary:`删除 Agent Team: ${U.name}`,team_name:U.name,killed_agent_ids:Y}}}catch(J){return w6(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function jY($){if($.getAllNames().length===0)$.loadFromStandardLocations()}function TY($){return`
805
+ `.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:U,timeout:X}=$,Y=Z.sessionId??"",H=Z.sessionId?{sessionId:Z.sessionId,projectPath:KY.resolve(Z.workspaceRoot||A())}:void 0;if(H){let W=x0.getInstance().get(J,H);if(J.startsWith("mcp_task_")||W)return FY(J,U,X,H,Z.signal)}if(J.startsWith("bash_"))return o8(J,U,X,Y);let z=t.getInstance(),Q=s.getInstance();if(z.getProcess(J,Y))return o8(J,U,X,Y);if(H&&Q.getAgent(J,H))return qY(J,U,X,H);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function FY($,Z,J,U,X){let Y=x0.getInstance(),H=Z?await Y.wait($,U,J,X):Y.get($,U);if(!H)return{success:!1,llmContent:`MCP task not found: ${$}`,error:{type:"validation_error",message:"MCP task does not exist in this Session"},metadata:{summary:`获取 MCP 任务输出: ${$} (未找到)`}};let z={task_id:H.taskId,type:"mcp",server:H.serverName,tool:H.toolName,status:H.status,status_message:H.statusMessage,created_at:new Date(H.createdAt).toISOString(),updated_at:new Date(H.updatedAt).toISOString(),completed_at:H.completedAt?new Date(H.completedAt).toISOString():void 0,result:H.result?.llmContent,error:H.error};return{success:!0,llmContent:z,metadata:{summary:`获取 MCP 任务输出: ${$} (${H.status})`,...z,taskType:"mcp",taskStatus:H.status,...H.result?{mcpResult:{isError:H.result.isError,...H.result.metadata}}:{}}}}async function o8($,Z,J,U){let X=t.getInstance(),Y=X.getProcess($,U);if(!Y)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&Y.status==="running")await wY($,J,U);let H=X.consumeOutput($,U);if(!H)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let z=c$.truncateForLLM(H.stdout,H.stderr,H.command),Q=H.stdoutOmittedBytes??0,W=H.stderrOmittedBytes??0,B={task_id:H.id,type:"shell",status:H.status,command:H.command,pid:H.pid,exit_code:H.exitCode,signal:H.signal,sandboxed:H.sandboxed,started_at:new Date(H.startedAt).toISOString(),finished_at:H.endedAt?new Date(H.endedAt).toISOString():void 0,stdout:z.stdout,stderr:z.stderr,output_truncated:Q>0||W>0||Boolean(z.truncationInfo),stdout_omitted_bytes:Q,stderr_omitted_bytes:W,truncation_info:z.truncationInfo};return{success:!0,llmContent:B,metadata:{summary:`获取任务输出: ${$}`,...B}}}async function qY($,Z,J,U){let X=s.getInstance(),Y=X.getAgent($,U);if(!Y)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&Y.status==="running"){if(Y=await X.waitForCompletion($,J,U),!Y)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let H={task_id:Y.id,type:"agent",status:Y.status,subagent_type:Y.subagentType,description:Y.description,created_at:new Date(Y.createdAt).toISOString(),last_active_at:new Date(Y.lastActiveAt).toISOString(),completed_at:Y.completedAt?new Date(Y.completedAt).toISOString():void 0,result:Y.result,stats:Y.stats,isolation:Y.isolation,worktree_path:Y.worktree?.worktreeRoot,worktree_branch:Y.worktree?.branch,resumed_from:Y.resumedFrom,root_agent_id:Y.rootAgentId,resume_depth:Y.resumeDepth,resume_from_hint:Y.id},z=Y.status==="completed"?"completed":Y.status==="failed"?"failed":"running";return{success:!0,llmContent:H,metadata:{summary:`获取任务输出: ${$}`,...H,subagentSessionId:Y.id,subagentType:Y.subagentType,subagentStatus:z,subagentResumedFrom:Y.resumedFrom,subagentRootId:Y.rootAgentId,subagentResumeDepth:Y.resumeDepth,subagentSummary:typeof Y.result?.message==="string"?Y.result.message.slice(0,500):void 0,verificationCommands:Y.result?.verificationCommands,verificationVerdict:Y.result?.verificationVerdict,modifiedFiles:Y.result?.modifiedFiles,verificationAgentBuiltin:q$(Y.subagentType)&&Y.configSnapshot?.source==="builtin"}}}async function wY($,Z,J){let U=t.getInstance(),X=Date.now();return new Promise((Y)=>{let H=setInterval(()=>{let z=U.getProcess($,J);if(!z||z.status!=="running"){clearInterval(H),Y();return}if(Date.now()-X>=Z){clearInterval(H),Y();return}},100)})}import*as t8 from"os";import*as e8 from"path";import*as A$ from"fs/promises";import*as b1 from"path";class j0{static instances=new Map;teamsDir;constructor($){this.teamsDir=b1.join($,"teams")}static getInstance($){if(!j0.instances.has($))j0.instances.set($,new j0($));return j0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return b1.join(this.teamsDir,j0.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),U=this.getTeamFilePath(Z),X={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead-${Z}`,leadSessionId:$.leadSessionId,teamFilePath:U,members:[{id:`team-lead-${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(X),X}async loadTeam($){try{let Z=await A$.readFile(this.getTeamFilePath($),"utf-8");return DY(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await A$.mkdir(b1.dirname(Z),{recursive:!0,mode:493}),await A$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await A$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let U=await this.loadTeam(J.name);if(U)Z.push(U)}return Z.sort((J,U)=>U.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),U={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((X)=>X.status==="running"?{...X,status:"cancelled",completedAt:X.completedAt||J}:X)};return await this.saveTeam(U),U}async getUniqueTeamName($){let Z=j0.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,U=2;while(await this.loadTeam(J))J=`${Z}-${U}`,U+=1;return J}}function DY($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var bY=_.Object({name:_.String({minLength:1,description:"Human-readable teammate name, e.g. researcher or test-runner"}),subagent_type:_.String({minLength:1,description:"Registered subagent type to launch for this teammate"}),description:_.Optional(_.String({minLength:3,maxLength:100})),prompt:_.String({minLength:10,description:"Detailed assignment for this teammate"})});function q6($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||e8.join(t8.homedir(),".blade"),U=$?.subagentRegistry??L$();return[LY({sessionId:Z,configDir:J,subagentRegistry:U,agentResources:$?.agentResources,modelResources:$?.modelResources,lspResources:$?.lspResources,getReasoningEffort:$?.getReasoningEffort,getServiceTier:$?.getServiceTier,getResponseVerbosity:$?.getResponseVerbosity,getCommunicationStyle:$?.getCommunicationStyle}),AY({configDir:J}),NY({configDir:J})]}function LY($){return j({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Name for the new agent team"}),description:_.Optional(_.String({description:"Team description or purpose"})),agent_type:_.Optional(_.String({description:"Optional role/type label for the team lead"})),members:S(_.Array(bY,{description:"Initial teammates to launch as background agents"}),[])}),description:{short:"Create an agent team and optionally launch teammate subagents",long:CY(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{jY($.subagentRegistry);let U=MY(Z.members.map((E)=>E.name));if(U)return b2(`Duplicate teammate name: ${U}`,"创建团队失败");let X=Z.members.map((E)=>E.subagent_type).filter((E)=>!$.subagentRegistry.getSubagent(E));if(X.length>0)return b2(`Invalid subagent type(s): ${[...new Set(X)].join(", ")}. Available: ${$.subagentRegistry.getAllNames().join(", ")||"none"}`,"创建团队失败");let Y=s.getInstance(),H=j0.getInstance($.configDir),z=await H.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),Q=Date.now(),W=[];for(let E of Z.members){let O=$.subagentRegistry.getSubagent(E.subagent_type);if(!O)continue;let G={...O,model:O.model&&O.model!=="inherit"?O.model:J.modelId??O.model,permissionMode:O.permissionMode??J.permissionMode},K=`team-${j0.sanitizeName(E.name)}-${z.name}`,F=TY({teamName:z.name,teamDescription:Z.description,memberName:E.name,memberPrompt:E.prompt,teamFileHint:z.teamFilePath}),w=Y.startBackgroundAgent({config:G,description:E.description||E.name,prompt:F,parentSessionId:J.sessionId||$.sessionId,parentProjectPath:J.workspaceRoot||A(),permissionMode:J.permissionMode,reasoningEffort:$.getReasoningEffort?.(),serviceTier:$.getServiceTier?.(),responseVerbosity:$.getResponseVerbosity?.(),communicationStyle:$.getCommunicationStyle?.(),agentId:K,taskListId:z.name,workspaceRoot:J.workspaceRoot||A(),isolation:G.isolation,agentResources:$.agentResources,modelResources:$.modelResources,lspResources:$.lspResources});W.push({id:K,name:E.name,subagentType:E.subagent_type,description:E.description||E.name,prompt:E.prompt,agentId:w,status:"running",joinedAt:Q})}let B={...z,members:[...z.members,...W],updatedAt:Date.now()};await H.saveTeam(B);let V=await F6(H,B);return{success:!0,llmContent:{team:o$(V),message:W.length>0?`Team created with ${W.length} teammate(s). Use TeamStatus(team_name: "${V.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${V.name}".`},metadata:{summary:`创建 Agent Team: ${V.name} (${W.length} teammates)`,team_name:V.name,team_file_path:V.teamFilePath,lead_agent_id:V.leadAgentId,member_agent_ids:W.map((E)=>E.agentId).filter(Boolean)}}}catch(U){return w6(U,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function AY($){return j({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:_.Object({team_name:_.Optional(_.String({description:"Team name to inspect. Omit to list all teams."}))}),description:{short:"List agent teams or inspect one team with teammate statuses",long:"Use this after TeamCreate to monitor teammate background agents and find their TaskOutput IDs."},async execute(Z){try{let J=j0.getInstance($.configDir);if(!Z.team_name){let Y=await Promise.all((await J.listTeams()).map((H)=>F6(J,H)));return{success:!0,llmContent:{teams:Y.map(o$)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(o$)}}}let U=await J.loadTeam(Z.team_name);if(!U)return b2(`Team not found: ${Z.team_name}`,"读取团队失败");let X=await F6(J,U);return{success:!0,llmContent:{team:o$(X)},metadata:{summary:`Agent Team ${X.name}: ${$9(X)}`,team:o$(X)}}}catch(J){return w6(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function NY($){return j({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:_.Object({team_name:_.String({minLength:1,description:"Team name to delete"}),kill_running:S(_.Boolean({description:"Whether to cancel running teammate agents"}),!0)}),description:{short:"Mark an agent team deleted and optionally cancel running teammates",long:"Use this when coordinated team work is finished or should be stopped."},async execute(Z){try{let J=j0.getInstance($.configDir),U=await J.loadTeam(Z.team_name);if(!U)return b2(`Team not found: ${Z.team_name}`,"删除团队失败");let X=s.getInstance(),Y=[];if(Z.kill_running){for(let z of U.members)if(z.agentId&&X.killAgent(z.agentId))Y.push(z.agentId)}let H=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:H?o$(H):null,killed_agent_ids:Y},metadata:{summary:`删除 Agent Team: ${U.name}`,team_name:U.name,killed_agent_ids:Y}}}catch(J){return w6(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function jY($){if($.getAllNames().length===0)$.loadFromStandardLocations()}function TY($){return`
806
806
  You are ${$.memberName}, a teammate in Blade agent team "${$.teamName}".
807
807
 
808
808
  Team purpose: ${$.teamDescription||"Coordinate parallel agent work"}.
@@ -814,7 +814,7 @@ Work independently on your assignment and return a concise final result for the
814
814
 
815
815
  Assignment:
816
816
  ${$.memberPrompt}
817
- `.trim()}async function F6($,Z){let J=s.getInstance(),U=!1,X=Z.members.map((H)=>{if(!H.agentId)return H;let z=J.getAgent(H.agentId);if(!z)return{...H,status:"unknown"};let Q=fY(z);if(Q!==H.status||z.completedAt!==H.completedAt)return U=!0,{...H,status:Q,completedAt:z.completedAt};return H}),Y={...Z,members:X};if(U)await $.saveTeam(Y);return Y}function fY($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function o$($){let Z=s.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":$9($),team_file_path:$.teamFilePath,lead_agent_id:$.leadAgentId,lead_session_id:$.leadSessionId,created_at:new Date($.createdAt).toISOString(),updated_at:new Date($.updatedAt).toISOString(),deleted_at:$.deletedAt?new Date($.deletedAt).toISOString():void 0,members:$.members.map((J)=>{let U=J.agentId?Z.getAgent(J.agentId):void 0;return{id:J.id,name:J.name,subagent_type:J.subagentType,description:J.description,agent_id:J.agentId,status:J.status,task_output_id:J.agentId,result:U?.result,stats:U?.stats}})}}function $9($){let Z=$.members.reduce((J,U)=>{return J[U.status]=(J[U.status]||0)+1,J},{});return Object.entries(Z).map(([J,U])=>`${U} ${J}`).join(", ")}function MY($){let Z=new Set;for(let J of $){let U=N0.sanitizeName(J);if(Z.has(U))return J;Z.add(U)}return}function b2($,Z){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:Z}}}function w6($,Z){let J=$;return{success:!1,llmContent:`Team operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function CY(){return`
817
+ `.trim()}async function F6($,Z){let J=s.getInstance(),U=!1,X=Z.members.map((H)=>{if(!H.agentId)return H;let z=J.getAgent(H.agentId);if(!z)return{...H,status:"unknown"};let Q=fY(z);if(Q!==H.status||z.completedAt!==H.completedAt)return U=!0,{...H,status:Q,completedAt:z.completedAt};return H}),Y={...Z,members:X};if(U)await $.saveTeam(Y);return Y}function fY($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function o$($){let Z=s.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":$9($),team_file_path:$.teamFilePath,lead_agent_id:$.leadAgentId,lead_session_id:$.leadSessionId,created_at:new Date($.createdAt).toISOString(),updated_at:new Date($.updatedAt).toISOString(),deleted_at:$.deletedAt?new Date($.deletedAt).toISOString():void 0,members:$.members.map((J)=>{let U=J.agentId?Z.getAgent(J.agentId):void 0;return{id:J.id,name:J.name,subagent_type:J.subagentType,description:J.description,agent_id:J.agentId,status:J.status,task_output_id:J.agentId,result:U?.result,stats:U?.stats}})}}function $9($){let Z=$.members.reduce((J,U)=>{return J[U.status]=(J[U.status]||0)+1,J},{});return Object.entries(Z).map(([J,U])=>`${U} ${J}`).join(", ")}function MY($){let Z=new Set;for(let J of $){let U=j0.sanitizeName(J);if(Z.has(U))return J;Z.add(U)}return}function b2($,Z){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:Z}}}function w6($,Z){let J=$;return{success:!1,llmContent:`Team operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function CY(){return`
818
818
  Create a named team for coordinated parallel agent work. This is Blade's team layer over the existing Task background-agent system, inspired by Claude Code's TeamCreate workflow.
819
819
 
820
820
  When to use:
@@ -846,7 +846,7 @@ Usage notes:
846
846
  - Results may be summarized if the content is very large
847
847
  - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
848
848
  - When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
849
- `},async execute($,Z){let{url:J,method:U="GET",extract_content:X=!1,jina_options:Y,headers:H={},body:z,timeout:Q=30000,follow_redirects:W=!0,max_redirects:B=5,return_headers:V=!1}=$,{updateOutput:E}=Z,O=Z.signal??new AbortController().signal;try{if(X)try{let b=Date.now(),D=await kY({url:J,jinaOptions:Y,timeout:Q,signal:O,updateOutput:E}),L=Date.now()-b;if(D.response_time=L,!V)delete D.headers;let N={url:J,method:"GET",status:D.status,response_time:L,content_length:Buffer.byteLength(D.body||"","utf8"),redirected:D.redirected||!1,redirect_count:D.redirect_count??0,final_url:D.url,content_type:D.content_type,redirect_chain:D.redirect_chain},M=Z9(J);return{success:!0,llmContent:D,metadata:{...N,summary:`GET ${M} - ${D.status}`}}}catch{E?.("[WARN] Jina Reader 失败,使用标准方式获取")}E?.(`发送 ${U} 请求到: ${J}`);let G=Date.now(),K=await SY({url:J,method:U,headers:H,body:z,timeout:Q,follow_redirects:W,max_redirects:B,signal:O}),F=Date.now()-G;if(K.response_time=F,!V)delete K.headers;let w={url:J,method:U,status:K.status,response_time:F,content_length:Buffer.byteLength(K.body||"","utf8"),redirected:K.redirected||!1,redirect_count:K.redirect_count??0,final_url:K.url,content_type:K.content_type,redirect_chain:K.redirect_chain},q=Z9(J);if(K.status>=400)return{success:!1,llmContent:`HTTP error ${K.status}: ${K.status_text}`,error:{type:"execution_error",message:`HTTP error ${K.status}: ${K.status_text}`,details:{...w,response_body:K.body}},metadata:{...w,summary:`请求失败: HTTP ${K.status} ${K.status_text}`}};return{success:!0,llmContent:K,metadata:{...w,summary:`${U} ${q} - ${K.status}`}}}catch(G){if(U9(G)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let K=RY(G);return{success:!1,llmContent:`Network request failed: ${K}`,error:{type:"execution_error",message:K,details:G},metadata:{summary:`请求失败: ${K}`}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}});async function SY($){let{url:Z,method:J,headers:U,body:X,timeout:Y,follow_redirects:H,max_redirects:z,signal:Q}=$,W={"User-Agent":"Blade-AI/1.0",...U},B=Z,V=J,E=X,O=0,G=[];while(!0){let K={...W};if(E&&V!=="GET"&&V!=="HEAD"&&!IY(K,"content-type"))K["Content-Type"]="application/json";let F=await X9(B,{method:V,headers:K,body:E&&V!=="GET"&&V!=="HEAD"?E:void 0,redirect:"manual"},Y,Q),w=F.headers.get("location"),q=F.status>=300&&F.status<400,b=H&&q&&w&&O<z;if(q&&H&&!w)throw Error(`收到状态码 ${F.status} 但响应缺少 Location 头`);if(q&&H&&O>=z)throw Error(`超过最大重定向次数 (${z})`);if(b&&w){O++;let N=PY(w,B);if(G.push(`${F.status} -> ${N}`),F.status===303||(F.status===301||F.status===302)&&V!=="GET"&&V!=="HEAD")V="GET",E=void 0;B=N;continue}let D=await F.text(),L=Y9(F.headers);return{status:F.status,status_text:F.statusText,headers:L,body:D,url:F.url||B,redirected:O>0,redirect_count:O,redirect_chain:G,content_type:L["content-type"],response_time:0}}}function Z9($){try{return new URL($).hostname}catch{return $}}async function X9($,Z,J,U){let X=new AbortController,Y=setTimeout(()=>X.abort(),J),H=()=>X.abort();U?.addEventListener("abort",H);try{return await fetch($,{...Z,signal:X.signal})}catch(z){if(U9(z)==="AbortError"){if(z instanceof Error)throw z.message="请求被中止或超时",z;let Q=Error("请求被中止或超时");throw Q.name="AbortError",Q}throw z}finally{clearTimeout(Y),U?.removeEventListener("abort",H)}}function PY($,Z){try{return new URL($,Z).toString()}catch{return $}}function Y9($){let Z={};return $.forEach((J,U)=>{Z[U.toLowerCase()]=J}),Z}function IY($,Z){let J=Z.toLowerCase();return Object.keys($).some((U)=>U.toLowerCase()===J)}async function kY($){let{url:Z,jinaOptions:J,timeout:U,signal:X,updateOutput:Y}=$,H=`https://r.jina.ai/${encodeURIComponent(Z)}`;Y?.(`使用 Jina Reader 提取内容: ${Z}`);let z={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(J?.with_generated_alt)z["X-With-Generated-Alt"]="true";if(J?.with_links_summary)z["X-With-Links-Summary"]="true";if(J?.wait_for_selector)z["X-Wait-For-Selector"]=J.wait_for_selector;try{let Q=await X9(H,{method:"GET",headers:z},U,X);if(!Q.ok)throw Error(`Jina Reader error: ${Q.status} ${Q.statusText}`);let W=await Q.text(),B=vY(W);return Y?.(`[OK] Jina Reader 成功提取内容 (${B.content.length} 字符)`),{status:Q.status,status_text:Q.statusText,headers:Y9(Q.headers),body:yY(B),url:B.sourceUrl||Z,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(Q){throw Y?.("[WARN] Jina Reader 失败,回退到直接获取"),Q}}function vY($){let Z=$.split(`
849
+ `},async execute($,Z){let{url:J,method:U="GET",extract_content:X=!1,jina_options:Y,headers:H={},body:z,timeout:Q=30000,follow_redirects:W=!0,max_redirects:B=5,return_headers:V=!1}=$,{updateOutput:E}=Z,O=Z.signal??new AbortController().signal;try{if(X)try{let b=Date.now(),D=await kY({url:J,jinaOptions:Y,timeout:Q,signal:O,updateOutput:E}),L=Date.now()-b;if(D.response_time=L,!V)delete D.headers;let N={url:J,method:"GET",status:D.status,response_time:L,content_length:Buffer.byteLength(D.body||"","utf8"),redirected:D.redirected||!1,redirect_count:D.redirect_count??0,final_url:D.url,content_type:D.content_type,redirect_chain:D.redirect_chain},C=Z9(J);return{success:!0,llmContent:D,metadata:{...N,summary:`GET ${C} - ${D.status}`}}}catch{E?.("[WARN] Jina Reader 失败,使用标准方式获取")}E?.(`发送 ${U} 请求到: ${J}`);let G=Date.now(),K=await SY({url:J,method:U,headers:H,body:z,timeout:Q,follow_redirects:W,max_redirects:B,signal:O}),F=Date.now()-G;if(K.response_time=F,!V)delete K.headers;let w={url:J,method:U,status:K.status,response_time:F,content_length:Buffer.byteLength(K.body||"","utf8"),redirected:K.redirected||!1,redirect_count:K.redirect_count??0,final_url:K.url,content_type:K.content_type,redirect_chain:K.redirect_chain},q=Z9(J);if(K.status>=400)return{success:!1,llmContent:`HTTP error ${K.status}: ${K.status_text}`,error:{type:"execution_error",message:`HTTP error ${K.status}: ${K.status_text}`,details:{...w,response_body:K.body}},metadata:{...w,summary:`请求失败: HTTP ${K.status} ${K.status_text}`}};return{success:!0,llmContent:K,metadata:{...w,summary:`${U} ${q} - ${K.status}`}}}catch(G){if(U9(G)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let K=RY(G);return{success:!1,llmContent:`Network request failed: ${K}`,error:{type:"execution_error",message:K,details:G},metadata:{summary:`请求失败: ${K}`}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}});async function SY($){let{url:Z,method:J,headers:U,body:X,timeout:Y,follow_redirects:H,max_redirects:z,signal:Q}=$,W={"User-Agent":"Blade-AI/1.0",...U},B=Z,V=J,E=X,O=0,G=[];while(!0){let K={...W};if(E&&V!=="GET"&&V!=="HEAD"&&!IY(K,"content-type"))K["Content-Type"]="application/json";let F=await X9(B,{method:V,headers:K,body:E&&V!=="GET"&&V!=="HEAD"?E:void 0,redirect:"manual"},Y,Q),w=F.headers.get("location"),q=F.status>=300&&F.status<400,b=H&&q&&w&&O<z;if(q&&H&&!w)throw Error(`收到状态码 ${F.status} 但响应缺少 Location 头`);if(q&&H&&O>=z)throw Error(`超过最大重定向次数 (${z})`);if(b&&w){O++;let N=PY(w,B);if(G.push(`${F.status} -> ${N}`),F.status===303||(F.status===301||F.status===302)&&V!=="GET"&&V!=="HEAD")V="GET",E=void 0;B=N;continue}let D=await F.text(),L=Y9(F.headers);return{status:F.status,status_text:F.statusText,headers:L,body:D,url:F.url||B,redirected:O>0,redirect_count:O,redirect_chain:G,content_type:L["content-type"],response_time:0}}}function Z9($){try{return new URL($).hostname}catch{return $}}async function X9($,Z,J,U){let X=new AbortController,Y=setTimeout(()=>X.abort(),J),H=()=>X.abort();U?.addEventListener("abort",H);try{return await fetch($,{...Z,signal:X.signal})}catch(z){if(U9(z)==="AbortError"){if(z instanceof Error)throw z.message="请求被中止或超时",z;let Q=Error("请求被中止或超时");throw Q.name="AbortError",Q}throw z}finally{clearTimeout(Y),U?.removeEventListener("abort",H)}}function PY($,Z){try{return new URL($,Z).toString()}catch{return $}}function Y9($){let Z={};return $.forEach((J,U)=>{Z[U.toLowerCase()]=J}),Z}function IY($,Z){let J=Z.toLowerCase();return Object.keys($).some((U)=>U.toLowerCase()===J)}async function kY($){let{url:Z,jinaOptions:J,timeout:U,signal:X,updateOutput:Y}=$,H=`https://r.jina.ai/${encodeURIComponent(Z)}`;Y?.(`使用 Jina Reader 提取内容: ${Z}`);let z={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(J?.with_generated_alt)z["X-With-Generated-Alt"]="true";if(J?.with_links_summary)z["X-With-Links-Summary"]="true";if(J?.wait_for_selector)z["X-Wait-For-Selector"]=J.wait_for_selector;try{let Q=await X9(H,{method:"GET",headers:z},U,X);if(!Q.ok)throw Error(`Jina Reader error: ${Q.status} ${Q.statusText}`);let W=await Q.text(),B=vY(W);return Y?.(`[OK] Jina Reader 成功提取内容 (${B.content.length} 字符)`),{status:Q.status,status_text:Q.statusText,headers:Y9(Q.headers),body:yY(B),url:B.sourceUrl||Z,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(Q){throw Y?.("[WARN] Jina Reader 失败,回退到直接获取"),Q}}function vY($){let Z=$.split(`
850
850
  `),J="",U="",X=0;for(let H=0;H<Z.length;H++){let z=Z[H];if(z.startsWith("Title: "))J=z.substring(7).trim();else if(z.startsWith("URL Source: "))U=z.substring(12).trim();else if(z.startsWith("Markdown Content:")){X=H+1;break}}let Y=Z.slice(X).join(`
851
851
  `).trim();return{title:J||"Untitled",sourceUrl:U||"",content:Y||$}}function yY($){let Z="";if($.title)Z+=`# ${$.title}
852
852
 
@@ -897,13 +897,13 @@ ${z.slice(0,j6).join(`
897
897
  **Auto-Verify: issues after ${Y.length===1?H$.basename(Y[0]):`${Y.length} patched files`}:**
898
898
  \`\`\`
899
899
  ${W}
900
- \`\`\``,D9.info(`[AutoVerify] injected type diagnostics (${Y.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await f0.getInstance().getStatus(this.options.projectRoot)).state==="trusted"}runOwnedCommand($,Z,J,U,X){if(this.disposed||X?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:1,timedOut:!1});let{child:Y,processTree:H}=u0($,Z,{cwd:J,env:{...this.options.environment,PATH:this.options.environment.PATH??process.env.PATH??"",HOME:this.options.environment.HOME??process.env.HOME??"",USER:this.options.environment.USER??process.env.USER??"",SHELL:this.options.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1",BLADE_SESSION_ID:this.options.sessionId},stdio:["ignore","pipe","pipe"]}),z,Q=new Promise((B)=>{z=B}),W={processTree:H,settled:Q};return this.activeCommands.add(W),new Promise((B,V)=>{let E="",O="",G=!1,K=!1,F,w=()=>{return F??=H.terminate(),F};Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(L)=>{E=L9(E,L)}),Y.stderr?.on("data",(L)=>{O=L9(O,L)});let q=()=>{clearTimeout(D),X?.removeEventListener("abort",b),this.disposeController.signal.removeEventListener("abort",b),this.activeCommands.delete(W),z()},b=()=>{w()},D=setTimeout(()=>{G=!0,w()},U);if(X?.addEventListener("abort",b,{once:!0}),this.disposeController.signal.addEventListener("abort",b,{once:!0}),X?.aborted||this.disposeController.signal.aborted)b();Y.once("error",(L)=>{if(K)return;K=!0,q(),V(L)}),Y.once("close",async(L)=>{if(K)return;if(K=!0,G||X?.aborted||this.disposeController.signal.aborted)await w();q(),B({stdout:E,stderr:O,exitCode:L??1,timedOut:G})})})}}import{Mutex as GH}from"async-mutex";import{nanoid as A9}from"nanoid";var KH=20,FH=T9+f9;function N9($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}function j9($){return $?Buffer.byteLength(JSON.stringify($)):0}class j1{inbox;transitionMutex=new GH;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new j1(await M9.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let J=this.inbox.count()>0,U=await this.enqueueDurably($,"next_turn",Z);if(!U.accepted||!U.messageId)return{accepted:!1,queued:U.queued,reason:"queue_full"};let X=this.createTurn();if(!J){let Y=this.inbox.list().find((H)=>H.id===U.messageId);if(!Y)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${U.messageId}`);this.claimed.set(Y.id,Y)}return{accepted:!0,handle:X,messageId:U.messageId,queued:U.queued,mode:J?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let U={id:J.messageId??A9(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{},...J.outputSchema?{outputSchema:J.outputSchema}:{}};if(!await this.inbox.enqueue(U,(Y)=>{if(Y.length>=KH)return!1;let H=Y.reduce((Q,W)=>Q+N9(W.content),0),z=Y.reduce((Q,W)=>Q+j9(W.outputSchema),0);return H+z+N9($)+j9(J.outputSchema)<=FH}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:U.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:A9(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var j0=g("Agent"),C9=new Map;async function R9($){let Z=C9.get($);if(!Z)Z=(async()=>{try{let J=await n0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)j0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)j0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){j0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),C9.set($,Z);await Z}class w${config;options;approvalStore=new K1;baseRegistry=new K$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new wH;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new I9(k9().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:U0.resolve(Z.workspaceRoot??A()),config:y9($),catalog:J}}this.lspResources=H1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new T0(this.workspaceRoot,this.sessionId),this.attachmentCollector=new B1({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){let Z=$.workspaceRoot??A(),J=$.taskWorktree,U=$.taskIsolation,X=$.modelId,Y=$.permissionMode,H=$.reasoningEffort,z=$.serviceTier,Q=$.responseVerbosity,W=$.communicationStyle,B=$.communicationStyleDigest,V=$.projectInstructionsDigest,E=X!==void 0,O=W!==void 0;try{await X2();let G=await c.findSessionMetadata($.sessionId,Z);if(G?.archivedAt)throw new l9($.sessionId,G.archivedBySessionId??$.sessionId);if(Y??=G?.permissionMode,H??=G?.reasoningEffort??"off",z??=G?.serviceTier??"auto",Q??=G?.responseVerbosity??"auto",W??=G?.communicationStyle??"auto",!O||W===G?.communicationStyle)B??=G?.communicationStyleDigest;if(await R9(Z),V??=G?.projectInstructionsDigest,await R9(Z),!$.subagentInfo&&(!J||!U||!X)){let R=await(J?Promise.resolve(void 0):c.findSessionTaskWorktree($.sessionId,Z));J??=R,U??=G?.taskIsolation,X??=G?.selectedModelId??G?.taskModelId}if(J){if(U0.resolve(J.workspaceRoot)!==U0.resolve(Z))throw Error("Task worktree workspace does not match runtime workspace");await n0.restoreSession(J)}let K=W0();if(!K)throw Error("配置未初始化,请确保应用已正确启动");l$.configure(K.maxConcurrentTasks,K.maxQueuedTasks);let F=e.getInstance(),w=$.modelResources?.projectRoot??$.lspResources?.projectRoot??$.agentResources?.projectRoot??J?.originalWorkspaceRoot??Z,q=$.modelResources?h9($.modelResources):await x9(w,K),b=q.config.models,D=$.lspResources?H1($.lspResources):await q4(w,q.config.lspServers);if(b.length===0)throw Error(`没有可用的模型配置
900
+ \`\`\``,D9.info(`[AutoVerify] injected type diagnostics (${Y.length} files)`)}isRemoteSession(){return this.options.isRemoteSession?.()??a(this.options.sessionId)}async isProjectExplicitlyTrusted(){if(this.options.resolveTrust)return this.options.resolveTrust();return(await f0.getInstance().getStatus(this.options.projectRoot)).state==="trusted"}runOwnedCommand($,Z,J,U,X){if(this.disposed||X?.aborted)return Promise.resolve({stdout:"",stderr:"",exitCode:1,timedOut:!1});let{child:Y,processTree:H}=u0($,Z,{cwd:J,env:{...this.options.environment,PATH:this.options.environment.PATH??process.env.PATH??"",HOME:this.options.environment.HOME??process.env.HOME??"",USER:this.options.environment.USER??process.env.USER??"",SHELL:this.options.environment.SHELL??process.env.SHELL??"/bin/sh",BLADE_CLI:"1",BLADE_SESSION_ID:this.options.sessionId},stdio:["ignore","pipe","pipe"]}),z,Q=new Promise((B)=>{z=B}),W={processTree:H,settled:Q};return this.activeCommands.add(W),new Promise((B,V)=>{let E="",O="",G=!1,K=!1,F,w=()=>{return F??=H.terminate(),F};Y.stdout?.setEncoding("utf8"),Y.stderr?.setEncoding("utf8"),Y.stdout?.on("data",(L)=>{E=L9(E,L)}),Y.stderr?.on("data",(L)=>{O=L9(O,L)});let q=()=>{clearTimeout(D),X?.removeEventListener("abort",b),this.disposeController.signal.removeEventListener("abort",b),this.activeCommands.delete(W),z()},b=()=>{w()},D=setTimeout(()=>{G=!0,w()},U);if(X?.addEventListener("abort",b,{once:!0}),this.disposeController.signal.addEventListener("abort",b,{once:!0}),X?.aborted||this.disposeController.signal.aborted)b();Y.once("error",(L)=>{if(K)return;K=!0,q(),V(L)}),Y.once("close",async(L)=>{if(K)return;if(K=!0,G||X?.aborted||this.disposeController.signal.aborted)await w();q(),B({stdout:E,stderr:O,exitCode:L??1,timedOut:G})})})}}import{Mutex as GH}from"async-mutex";import{nanoid as A9}from"nanoid";var KH=20,FH=T9+f9;function N9($){if(typeof $==="string")return $.length;return $.reduce((Z,J)=>{if(J.type==="text")return Z+J.text.length;return Z+J.image_url.url.length},0)}function j9($){return $?Buffer.byteLength(JSON.stringify($)):0}class j1{inbox;transitionMutex=new GH;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,Z){return new j1(await M9.open($,Z))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!Z.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let J=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,J,Z)})}async prepareInputTurn($,Z={}){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let J=this.inbox.count()>0,U=await this.enqueueDurably($,"next_turn",Z);if(!U.accepted||!U.messageId)return{accepted:!1,queued:U.queued,reason:"queue_full"};let X=this.createTurn();if(!J){let Y=this.inbox.list().find((H)=>H.id===U.messageId);if(!Y)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${U.messageId}`);this.claimed.set(Y.id,Y)}return{accepted:!0,handle:X,messageId:U.messageId,queued:U.queued,mode:J?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return Z})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let Z=this.inbox.list().filter((J)=>!this.claimed.has(J.id));for(let J of Z)this.claimed.set(J.id,J);return{messages:Z,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let Z of $)this.claimed.delete(Z)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,Z={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!Z.continuePending||this.inbox.count()===0)return;return this.createTurn()})}async beginPendingTurn(){return this.transitionMutex.runExclusive(()=>{if(this.activeTurn||this.inbox.count()===0)return;return this.createTurn()})}isActive(){return Boolean(this.activeTurn&&!this.activeTurn.sealed)}hasTurnOwner(){return Boolean(this.activeTurn)}pendingCount(){return this.inbox.count()}pendingMessages(){return this.inbox.list()}recoveredCount(){return this.inbox.recoveredCount()}assertOwner($){if(!this.activeTurn||this.activeTurn.id!==$.id)throw Error(`Turn ${$.id} does not own this session mailbox`)}async enqueueDurably($,Z,J={}){let U={id:J.messageId??A9(12),content:$,queuedAt:Date.now(),...J.persisted?{persisted:!0}:{},...J.outputSchema?{outputSchema:J.outputSchema}:{}};if(!await this.inbox.enqueue(U,(Y)=>{if(Y.length>=KH)return!1;let H=Y.reduce((Q,W)=>Q+N9(W.content),0),z=Y.reduce((Q,W)=>Q+j9(W.outputSchema),0);return H+z+N9($)+j9(J.outputSchema)<=FH}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:U.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}}createTurn(){let $={id:A9(12)};return this.activeTurn={id:$.id,sealed:!1},$}}var q0=g("Agent"),C9=new Map;async function R9($){let Z=C9.get($);if(!Z)Z=(async()=>{try{let J=await n0.cleanupStaleAgentWorktrees({workspaceRoot:$});if(J.removed>0)q0.info(`[WorktreeGC] removed ${J.removed} stale agent worktree(s)`);if(J.errors.length>0)q0.warn(`[WorktreeGC] completed with ${J.errors.length} error(s): ${J.errors.join("; ")}`)}catch(J){q0.warn(`[WorktreeGC] cleanup failed: ${J instanceof Error?J.message:String(J)}`)}})(),C9.set($,Z);await Z}class w${config;options;approvalStore=new K1;baseRegistry=new K$;attachmentCollector;goalStore;activeTurnMailbox;chatService;executionEngine;selectedModelId;selectedReasoningEffort;currentReasoning;selectedServiceTier;currentServiceTier;selectedResponseVerbosity;currentResponseVerbosity;selectedCommunicationStyle;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;mcpCatalogListener;mcpContentCatalogListener;mcpResourceUpdatedListener;mcpConnectionListener;mcpLogListener;mcpInstructionsListener;mcpTaskListener;mcpCatalogBarrier=async()=>{return};executorCatalogs=new Map;agentResources;modelResources;lspResources;sessionEnvironment;subagentRegistry;autoVerifyRuntime;lspManager;userShellMutex=new wH;constructor($,Z){this.config=$;this.options=Z;if(this.selectedModelId=Z.modelId&&Z.modelId!=="inherit"?Z.modelId:void 0,this.selectedReasoningEffort=Z.reasoningEffort??"off",this.selectedServiceTier=Z.serviceTier??"auto",this.selectedResponseVerbosity=Z.responseVerbosity??"auto",this.selectedCommunicationStyle=Z.communicationStyle??"auto",Z.modelResources)this.modelResources=Z.modelResources;else{let J=new I9(k9().credentials);if($.modelProviders&&$.models)J.configureModelProviders($.modelProviders,$.models);this.modelResources={projectRoot:U0.resolve(Z.workspaceRoot??A()),config:y9($),catalog:J}}this.lspResources=H1(Z.lspResources??{projectRoot:this.modelResources.projectRoot,servers:$.lspServers}),this.sessionEnvironment=Object.freeze({...$.env}),this.goalStore=new T0(this.workspaceRoot,this.sessionId),this.attachmentCollector=new B1({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){let Z=$.workspaceRoot??A(),J=$.taskWorktree,U=$.taskIsolation,X=$.modelId,Y=$.permissionMode,H=$.reasoningEffort,z=$.serviceTier,Q=$.responseVerbosity,W=$.communicationStyle,B=$.communicationStyleDigest,V=$.projectInstructionsDigest,E=X!==void 0,O=W!==void 0;try{await X2();let G=await c.findSessionMetadata($.sessionId,Z);if(G?.archivedAt)throw new l9($.sessionId,G.archivedBySessionId??$.sessionId);if(Y??=G?.permissionMode,H??=G?.reasoningEffort??"off",z??=G?.serviceTier??"auto",Q??=G?.responseVerbosity??"auto",W??=G?.communicationStyle??"auto",!O||W===G?.communicationStyle)B??=G?.communicationStyleDigest;if(await R9(Z),V??=G?.projectInstructionsDigest,await R9(Z),!$.subagentInfo&&(!J||!U||!X)){let R=await(J?Promise.resolve(void 0):c.findSessionTaskWorktree($.sessionId,Z));J??=R,U??=G?.taskIsolation,X??=G?.selectedModelId??G?.taskModelId}if(J){if(U0.resolve(J.workspaceRoot)!==U0.resolve(Z))throw Error("Task worktree workspace does not match runtime workspace");await n0.restoreSession(J)}let K=W0();if(!K)throw Error("配置未初始化,请确保应用已正确启动");l$.configure(K.maxConcurrentTasks,K.maxQueuedTasks);let F=e.getInstance(),w=$.modelResources?.projectRoot??$.lspResources?.projectRoot??$.agentResources?.projectRoot??J?.originalWorkspaceRoot??Z,q=$.modelResources?h9($.modelResources):await x9(w,K),b=q.config.models,D=$.lspResources?H1($.lspResources):await q4(w,q.config.lspServers);if(b.length===0)throw Error(`没有可用的模型配置
901
901
 
902
902
  `+`请先使用以下命令添加模型:
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 M=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 M.initialize(),M}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")j0.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 L0(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 L0(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 L0(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}}beginTurn(){return this.getActiveTurnMailbox().beginTurn()}async prepareInputTurn($,Z){return this.getActiveTurnMailbox().prepareInputTurn($,Z)}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){return this.getActiveTurnMailbox().finishTurn($,Z)}async beginPendingTurn(){return this.getActiveTurnMailbox().beginPendingTurn()}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)j0.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),this.initialized=!0,j0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.dispose()}catch(Z){j0.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,j0.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}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=L0($,this.config,J,this.modelResources.catalog,U,X);j0.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){j0.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){j0.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){j0.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($){j0.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=L0($,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 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}
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
 
@@ -950,7 +950,7 @@ ${W}
950
950
  `+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
951
951
  `+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"**提示:** 创建文件后,重启 Blade 使配置生效";return U.sendMessage(z),{success:!0,message:"Help displayed"}}if(J==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let H=`未知子命令: \`${J}\`
952
952
 
953
- `+"使用 `/agents help` 查看可用命令";return U.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function ZJ($,Z){let J=(await c.listSessions({includeSubagents:!1,archived:Z})).filter((U)=>U.sessionId===$);if(J.length===0)return{success:!1,error:`${Z?"Archived session":"Session"} not found: ${$}`};if(J.length>1)return{success:!1,error:`Multiple workspaces contain session ${$}`};return{projectPath:J[0].projectPath}}var JJ={name:"archive",description:"Move an inactive session tree out of the active catalog",fullDescription:"归档一个已停止的会话及其 fork/subagent 后代。Transcript、任务证据和 worktree 元数据都会保留,可通过 /unarchive 恢复。",usage:"/archive [sessionId]",category:"Session",examples:["/archive","/archive web-abc123"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /archive [sessionId]"};try{if($.length===0){if(!Z.lifecycle||!Z.sessionId)return{success:!1,error:"Current surface cannot archive its active session; provide a session ID"};let Y=await Z.lifecycle.archiveCurrent();return{success:!0,message:"session_archived",content:`Archived session \`${Y.sessionId}\`. Restore it with \`/unarchive ${Y.sessionId}\`.`,data:{session:Y}}}let J=$[0],U=await ZJ(J,!1);if("success"in U)return U;let X=await c.archiveSession(J,U.projectPath);return{success:!0,message:`Archived session ${J}`,content:`Archived session \`${J}\` and its inactive descendants. Restore it with \`/unarchive ${J}\`.`,data:{session:X}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to archive session"}}}},UJ={name:"unarchive",description:"Restore an archived session tree to the active catalog",fullDescription:"恢复一个归档根会话及其继承归档状态的 fork/subagent 后代。单独归档的后代保持归档。",usage:"/unarchive <sessionId>",category:"Session",examples:["/unarchive web-abc123"],async handler($){if($.length!==1)return{success:!1,error:"Usage: /unarchive <sessionId>"};try{let Z=$[0],J=await ZJ(Z,!0);if("success"in J)return J;let U=await c.unarchiveSession(Z,J.projectPath);return{success:!0,message:`Restored session ${Z}`,content:`Restored session \`${Z}\` to the active catalog.`,data:{session:U}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to restore session"}}}};import TH from"node:path";var fH={name:"branch",description:"Fork the current session into an independent branch",fullDescription:"将当前会话历史分支到一个独立会话",usage:"/branch",async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to branch"};let J=TH.resolve(Z.workspaceRoot??Z.cwd),U=await c.forkSession(Z.sessionId,{sourceProjectPath:J,targetProjectPath:J});return{success:!0,message:"session_forked",content:Z.acp?`Created session branch ${U.sessionId}. Load it with ACP session/load to continue independently.`:void 0,data:{action:"restore_forked_session",sessionId:U.sessionId,parentSessionId:U.parentSessionId,messages:U.messages,visibleMessages:c.toUISafeMessages(U.messages)}}}},XJ=fH;async function MH($,Z){let J=k(Z);try{let U=W0(),X=F$();if(!U||!X)return{success:!1,error:"配置未初始化"};let Y=z0().session,H=Z.messages??Y.messages,z=Z.sessionId??Y.sessionId;if(!H||H.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let Q=Z.messages?[...Z.messages]:H.map((G)=>({role:G.role,content:G.content})),W=M2.countTokens(Q,X.model),B=L0(X,U,"off"),V=B.model.contextWindow,E=(W/V*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
953
+ `+"使用 `/agents help` 查看可用命令";return U.sendMessage(H),{success:!1,error:`Unknown subcommand: ${J}`}}};async function ZJ($,Z){let J=(await c.listSessions({includeSubagents:!1,archived:Z})).filter((U)=>U.sessionId===$);if(J.length===0)return{success:!1,error:`${Z?"Archived session":"Session"} not found: ${$}`};if(J.length>1)return{success:!1,error:`Multiple workspaces contain session ${$}`};return{projectPath:J[0].projectPath}}var JJ={name:"archive",description:"Move an inactive session tree out of the active catalog",fullDescription:"归档一个已停止的会话及其 fork/subagent 后代。Transcript、任务证据和 worktree 元数据都会保留,可通过 /unarchive 恢复。",usage:"/archive [sessionId]",category:"Session",examples:["/archive","/archive web-abc123"],async handler($,Z){if($.length>1)return{success:!1,error:"Usage: /archive [sessionId]"};try{if($.length===0){if(!Z.lifecycle||!Z.sessionId)return{success:!1,error:"Current surface cannot archive its active session; provide a session ID"};let Y=await Z.lifecycle.archiveCurrent();return{success:!0,message:"session_archived",content:`Archived session \`${Y.sessionId}\`. Restore it with \`/unarchive ${Y.sessionId}\`.`,data:{session:Y}}}let J=$[0],U=await ZJ(J,!1);if("success"in U)return U;let X=await c.archiveSession(J,U.projectPath);return{success:!0,message:`Archived session ${J}`,content:`Archived session \`${J}\` and its inactive descendants. Restore it with \`/unarchive ${J}\`.`,data:{session:X}}}catch(J){return{success:!1,error:J instanceof Error?J.message:"Failed to archive session"}}}},UJ={name:"unarchive",description:"Restore an archived session tree to the active catalog",fullDescription:"恢复一个归档根会话及其继承归档状态的 fork/subagent 后代。单独归档的后代保持归档。",usage:"/unarchive <sessionId>",category:"Session",examples:["/unarchive web-abc123"],async handler($){if($.length!==1)return{success:!1,error:"Usage: /unarchive <sessionId>"};try{let Z=$[0],J=await ZJ(Z,!0);if("success"in J)return J;let U=await c.unarchiveSession(Z,J.projectPath);return{success:!0,message:`Restored session ${Z}`,content:`Restored session \`${Z}\` to the active catalog.`,data:{session:U}}}catch(Z){return{success:!1,error:Z instanceof Error?Z.message:"Failed to restore session"}}}};import TH from"node:path";var fH={name:"branch",description:"Fork the current session into an independent branch",fullDescription:"将当前会话历史分支到一个独立会话",usage:"/branch",async handler($,Z){if(!Z.sessionId)return{success:!1,error:"No active session to branch"};let J=TH.resolve(Z.workspaceRoot??Z.cwd),U=await c.forkSession(Z.sessionId,{sourceProjectPath:J,targetProjectPath:J});return{success:!0,message:"session_forked",content:Z.acp?`Created session branch ${U.sessionId}. Load it with ACP session/load to continue independently.`:void 0,data:{action:"restore_forked_session",sessionId:U.sessionId,parentSessionId:U.parentSessionId,messages:U.messages,visibleMessages:c.toUISafeMessages(U.messages)}}}},XJ=fH;async function MH($,Z){let J=k(Z);try{let U=W0(),X=F$();if(!U||!X)return{success:!1,error:"配置未初始化"};let Y=z0().session,H=Z.messages??Y.messages,z=Z.sessionId??Y.sessionId;if(!H||H.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let Q=Z.messages?[...Z.messages]:H.map((G)=>({role:G.role,content:G.content})),W=M2.countTokens(Q,X.model),B=A0(X,U,"off"),V=B.model.contextWindow,E=(W/V*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
954
954
  • 消息数量: ${Q.length}
955
955
  • Token 数量: ${W.toLocaleString()}
956
956
  • Token 限制: ${V.toLocaleString()}
@@ -1163,7 +1163,7 @@ Supported: ${J}`}function wz($){let Z=$.toLowerCase();return MJ(Z)?Z:void 0}var
1163
1163
  - 工作目录: ${A()} (process.cwd: ${process.cwd()})
1164
1164
  - Node.js: ${process.version}
1165
1165
 
1166
- ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(O),{success:!0,message:"状态信息已显示"}}catch(X){return{success:!1,error:`获取状态信息失败: ${X instanceof Error?X.message:"未知错误"}`}}}},jz={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},Tz={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=k(Z),U=W0(),X=F$(),H=z0().session.messages||[],z=H.map((F)=>({role:F.role,content:F.content})),Q=X?.model||"gpt-4",W=z.length>0?M2.countTokens(z,Q):0,B=X&&U?L0(X,U,"off").model.contextWindow:128000,V=B>0?(W/B*100).toFixed(1):"0",E=(100-parseFloat(V)).toFixed(1),O=parseFloat(V),G;if(O<50)G="[OK] 正常";else if(O<80)G="[WARN] 中等";else G="[CRITICAL] 高负载";let K=`**上下文使用情况**
1166
+ ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(O),{success:!0,message:"状态信息已显示"}}catch(X){return{success:!1,error:`获取状态信息失败: ${X instanceof Error?X.message:"未知错误"}`}}}},jz={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},Tz={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=k(Z),U=W0(),X=F$(),H=z0().session.messages||[],z=H.map((F)=>({role:F.role,content:F.content})),Q=X?.model||"gpt-4",W=z.length>0?M2.countTokens(z,Q):0,B=X&&U?A0(X,U,"off").model.contextWindow:128000,V=B>0?(W/B*100).toFixed(1):"0",E=(100-parseFloat(V)).toFixed(1),O=parseFloat(V),G;if(O<50)G="[OK] 正常";else if(O<80)G="[WARN] 中等";else G="[CRITICAL] 高负载";let K=`**上下文使用情况**
1167
1167
 
1168
1168
  **当前会话:**
1169
1169
  - 消息数量: ${H.length}
@@ -1220,7 +1220,7 @@ ${U}
1220
1220
  **Diff:**
1221
1221
  \`\`\`diff
1222
1222
  ${X||"(无差异)"}
1223
- \`\`\``;return Z.sendMessage(Y),{success:!0}}async function xz($){return I2.handler(["uncommitted"],$)}async function hz($){let Z=k($),{cwd:J,signal:U}=$;if(!await d6(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await m6(J);let X=await S2(J),Y=await P2(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let H=await R2(J,5),z=await b0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let Q=z0().session.sessionId,W=uJ(X,Y,H),E=((await r0(z.chatStream(W,{messages:[],userId:"cli-user",sessionId:Q||"git-pre-commit",workspaceRoot:J,signal:U}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return Z.sendMessage(`**生成的 Commit Message:**
1223
+ \`\`\``;return Z.sendMessage(Y),{success:!0}}async function xz($){return I2.handler(["uncommitted"],$)}async function hz($){let Z=k($),{cwd:J,signal:U}=$;if(!await d6(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await m6(J);let X=await S2(J),Y=await P2(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let H=await R2(J,5),z=await L0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let Q=z0().session.sessionId,W=uJ(X,Y,H),E=((await r0(z.chatStream(W,{messages:[],userId:"cli-user",sessionId:Q||"git-pre-commit",workspaceRoot:J,signal:U}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return Z.sendMessage(`**生成的 Commit Message:**
1224
1224
  \`\`\`
1225
1225
  ${E}
1226
1226
  \`\`\`
@@ -1229,7 +1229,7 @@ ${E}
1229
1229
  \`\`\`bash
1230
1230
  git commit -m "${E.split(`
1231
1231
  `)[0]}"
1232
- \`\`\``),{success:!0}}async function uz($){let Z=k($),{cwd:J,signal:U}=$;if(!await d6(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await m6(J);let X=await S2(J),Y=await P2(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let H=await R2(J,5),z=await b0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let Q=z0().session.sessionId,W=uJ(X,Y,H),E=((await r0(z.chatStream(W,{messages:[],userId:"cli-user",sessionId:Q||"git-commit",workspaceRoot:J,signal:U}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();Z.sendMessage(`**生成的 Commit Message:**
1232
+ \`\`\``),{success:!0}}async function uz($){let Z=k($),{cwd:J,signal:U}=$;if(!await d6(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await m6(J);let X=await S2(J),Y=await P2(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let H=await R2(J,5),z=await L0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let Q=z0().session.sessionId,W=uJ(X,Y,H),E=((await r0(z.chatStream(W,{messages:[],userId:"cli-user",sessionId:Q||"git-commit",workspaceRoot:J,signal:U}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();Z.sendMessage(`**生成的 Commit Message:**
1233
1233
  \`\`\`
1234
1234
  ${E}
1235
1235
  \`\`\``);try{await vJ(J,E),Z.sendMessage("[OK] 提交成功!")}catch(O){let G=O instanceof Error?O.message:"未知错误";return Z.sendMessage(`[FAIL] 提交失败: ${G}`),{success:!1,error:G}}return{success:!0}}function uJ($,Z,J){let U=J&&J.trim().length>0;return`请根据以下 Git 改动生成一条 commit message。
@@ -1300,7 +1300,7 @@ ${J}
1300
1300
  /ide status - 显示连接状态
1301
1301
  /ide connect - 连接到 IDE
1302
1302
  /ide install - 安装 VS Code 插件
1303
- /ide disconnect - 断开连接`}return{success:!0,message:U}}},nJ=HQ;import{promises as C1}from"fs";import*as rJ from"path";var $1=g("Agent"),zQ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:J,signal:U}=Z,X=k(Z),Y=(G)=>{X.sendMessage(`${G}`)},H=z0().session.sessionId,z=rJ.join(J,"BLADE.md"),Q=!1,W=!1;try{if(Q=(await C1.stat(z)).isFile(),Q)W=(await C1.readFile(z,"utf-8")).trim().length===0}catch{Q=!1}if(Q&&!W){X.sendMessage("[WARN] BLADE.md 已存在。"),X.sendMessage("正在分析现有文件并提供改进建议...");let G=await b0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let K=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1303
+ /ide disconnect - 断开连接`}return{success:!0,message:U}}},nJ=HQ;import{promises as C1}from"fs";import*as rJ from"path";var $1=g("Agent"),zQ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:J,signal:U}=Z,X=k(Z),Y=(G)=>{X.sendMessage(`${G}`)},H=z0().session.sessionId,z=rJ.join(J,"BLADE.md"),Q=!1,W=!1;try{if(Q=(await C1.stat(z)).isFile(),Q)W=(await C1.readFile(z,"utf-8")).trim().length===0}catch{Q=!1}if(Q&&!W){X.sendMessage("[WARN] BLADE.md 已存在。"),X.sendMessage("正在分析现有文件并提供改进建议...");let G=await L0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let K=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1304
1304
 
1305
1305
  **Important**:
1306
1306
  - After each step, briefly describe what you found before proceeding
@@ -1339,7 +1339,7 @@ ${J}
1339
1339
  - 具体的改进建议(附带示例)
1340
1340
  - 如果需要重大修改,提供完整的改进版本内容
1341
1341
 
1342
- **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;$1.info(`[/init] Starting agent.chatStream, signal.aborted: ${U?.aborted}`);let w=(await r0(G.chatStream(K,{messages:[],userId:"cli-user",sessionId:H||"init-session",workspaceRoot:J,signal:U}),async(q)=>{switch(q.kind){case"tool_start":{let b=q.toolCall;if(!("function"in b))return;try{let D=JSON.parse(b.function.arguments),L=_6(b.function.name,D);Y(L)}catch{}break}case"tool_result":{if(!("function"in q.toolCall))return;let D=q.result.metadata?.summary;if(D)Y(D);break}default:break}})).finalMessage||"";if($1.info(`[/init] agent.chatStream completed, signal.aborted: ${U?.aborted}`),U?.aborted)return $1.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return X.sendMessage(w),{success:!0,message:"[OK] 分析完成"}}if(W)X.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");X.sendMessage("正在分析项目结构...");let B=await b0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let V=`Please analyze this codebase and generate BLADE.md content.
1342
+ **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;$1.info(`[/init] Starting agent.chatStream, signal.aborted: ${U?.aborted}`);let w=(await r0(G.chatStream(K,{messages:[],userId:"cli-user",sessionId:H||"init-session",workspaceRoot:J,signal:U}),async(q)=>{switch(q.kind){case"tool_start":{let b=q.toolCall;if(!("function"in b))return;try{let D=JSON.parse(b.function.arguments),L=_6(b.function.name,D);Y(L)}catch{}break}case"tool_result":{if(!("function"in q.toolCall))return;let D=q.result.metadata?.summary;if(D)Y(D);break}default:break}})).finalMessage||"";if($1.info(`[/init] agent.chatStream completed, signal.aborted: ${U?.aborted}`),U?.aborted)return $1.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return X.sendMessage(w),{success:!0,message:"[OK] 分析完成"}}if(W)X.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");X.sendMessage("正在分析项目结构...");let B=await L0.create();if(U?.aborted)return{success:!1,message:"操作已取消"};let V=`Please analyze this codebase and generate BLADE.md content.
1343
1343
 
1344
1344
  **Important**: After each step, briefly describe what you found before proceeding.
1345
1345
 
@@ -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-b6gknm33.js"),Y=await z7();if(!Y)return null;let{SessionService:H}=await import("./chunk-ttncpgr6.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(`
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-h6w3ggx9.js"),Y=await z7();if(!Y)return null;let{SessionService:H}=await import("./chunk-cscm57tr.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=[`**后台任务列表**
@@ -1484,4 +1484,4 @@ ${r6(W.trigger)} · 下次运行: ${B}`),{success:!0,message:`Schedule ${W.id} c
1484
1484
 
1485
1485
  **When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,U)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function mQ($,Z){return C0({cwd:Z}).getUserInvocableSkills().find((X)=>X.name===$)}async function gQ($){await q7({cwd:$})}async function pQ($){let Z=S0.getInstance($),J=Z.getLastDiscoveryResult();if(Z.isInitialized()&&J)return J;return await Z.initialize($)}async function Aj($,Z){try{let{command:J,args:U}=uQ($),X=dQ(J);if(X)return await X.handler(U,Z);let Y=Z.workspaceRoot||Z.cwd||A();await $0(Y);let H=S0.getInstance(Y);if(!H.isInitialized())await pQ(Y);if(H.hasCommand(J)){let B=H.getCommand(J);if(B){let V=await H.executeCommand(J,{args:U,workspaceRoot:Y,signal:Z.signal});if(V)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:V,config:B.config}}}}let Q=$$(Y).findCommand(J);if(Q){let B=await H.executePluginCommand(Q.namespacedName,{args:U,workspaceRoot:Y,signal:Z.signal});if(B)return{success:!0,message:`执行插件命令: /${Q.namespacedName}`,data:{action:"invoke_plugin_command",commandName:Q.namespacedName,pluginName:Q.pluginName,processedContent:B,config:Q.config}}}await gQ(Y);let W=mQ(J,Y);if(W)return await w7(W).handler(U,Z);return{success:!1,error:`未知命令: /${J}
1486
1486
  使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function Nj($=A()){let Z=Object.values(R1),U=S0.getInstance($).getAllCommands().map((Q)=>({name:Q.name,description:Q.config.description||Q.content.slice(0,50),usage:Q.config.argumentHint?`/${Q.name} ${Q.config.argumentHint}`:`/${Q.name}`,category:"custom",handler:async()=>({success:!0})})),Y=$$($).getAllCommands().map((Q)=>({name:Q.namespacedName,description:Q.config.description||Q.content.slice(0,50),usage:Q.config.argumentHint?`/${Q.namespacedName} ${Q.config.argumentHint}`:`/${Q.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),z=C0({cwd:$}).getUserInvocableSkills().map(w7);return[...Z,...U,...Y,...z]}function jj($,Z=A()){let J=($.startsWith("/")?$.slice(1):$).trim(),U=Object.values(R1).map((G)=>({name:G.name,description:G.description,aliases:G.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),X=S0.getInstance(Z),Y=X.getAllCommands().map((G)=>({name:G.name,description:G.config.description||G.content.slice(0,50),aliases:[],label:X.getCommandLabel(G),argumentHint:G.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),z=$$(Z).getAllCommands().map((G)=>({name:G.namespacedName,description:G.config.description||G.content.slice(0,50),aliases:[G.originalName],label:`(plugin: ${G.pluginName})`,argumentHint:G.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),W=C0({cwd:Z}).getUserInvocableSkills().map((G)=>({name:G.name,description:G.description,aliases:[],label:"(skill)",argumentHint:G.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),B=[...U,...Y,...z,...W];if(!J)return B.map((G)=>({command:`/${G.name}`,description:G.label?`${G.description} ${G.label}`:G.description,argumentHint:G.argumentHint,matchScore:50}));return new hQ(B,{keys:[{name:"name",weight:3},{name:"aliases",weight:2.5},{name:"description",weight:0.5}],threshold:0.4,includeScore:!0,ignoreLocation:!0,minMatchCharLength:1}).search(J).map((G)=>{let K=G.score??1,F=Math.round((1-K)*100),w=G.item;return{command:`/${w.name}`,description:w.label?`${w.description} ${w.label}`:w.description,argumentHint:w.argumentHint,matchScore:F}}).filter((G)=>(G.matchScore||0)>=40)}
1487
- export{CB as t,V$ as u,y as v,T0 as w,S$ as x,F3 as y,t as z,GG as A,F0 as B,n0 as C,A8 as D,l$ as E,w$ as F,E6 as G,_6 as H,i8 as I,c8 as J,s8 as K,b0 as L,j2 as M,T2 as N,R6 as O,S6 as P,P6 as Q,I6 as R,k6 as S,v6 as T,y6 as U,f2 as V,u6 as W,vA as X,f6 as Y,Lj as Z,pQ as _,Aj as $,Nj as aa,jj as ba};
1487
+ export{CB as t,V$ as u,y as v,T0 as w,S$ as x,F3 as y,t as z,GG as A,F0 as B,n0 as C,A8 as D,l$ as E,w$ as F,E6 as G,_6 as H,i8 as I,c8 as J,s8 as K,L0 as L,j2 as M,T2 as N,R6 as O,S6 as P,P6 as Q,I6 as R,k6 as S,v6 as T,y6 as U,f2 as V,u6 as W,vA as X,f6 as Y,Lj as Z,pQ as _,Aj as $,Nj as aa,jj as ba};