blade-code 0.7.4 → 0.7.5

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.
@@ -1,5 +1,5 @@
1
- import{Y as RZ}from"./chunk-e21htmg4.js";import{Z as j,_ as G0}from"./chunk-7mnefph6.js";import{$ as yZ,aa as xZ}from"./chunk-rtn0rb16.js";import{ma as Q1,na as Z0,oa as L,ra as Y0,sa as n1,ta as W$,ua as j0,va as K1,wa as k0,xa as a1,ya as a0}from"./chunk-5smacbk0.js";import{Aa as r1}from"./chunk-rkhhzc4r.js";import{Ea as h$}from"./chunk-4e2fzyf2.js";import{Ja as l0,La as I8,Ma as Q0,Na as u$,Oa as n0,Ra as t1,Va as N0,db as z2,eb as g8,hb as S5}from"./chunk-3mhbped9.js";import{ib as i5,jb as r5,kb as AW}from"./chunk-cyxb6fxe.js";import{lb as HZ,mb as C$,nb as w0}from"./chunk-jf48kahn.js";import{pb as b1,tb as D}from"./chunk-63dzf6hr.js";import{Ab as o1}from"./chunk-98jpdmgc.js";import{Bb as t8,Cb as $$,Db as o,Eb as I$,Fb as i1,Gb as V0,Hb as C5,Lb as P,Mb as S}from"./chunk-w1zb8zac.js";import{Nb as U$}from"./chunk-kfg3vx5z.js";import{randomUUID as d6}from"crypto";import{mkdir as T1,realpath as M2}from"node:fs/promises";import K$ from"node:path";import{Mutex as f6}from"async-mutex";import*as B$ from"fs/promises";import*as d from"path";var wZ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class H$ extends Error{code;constructor($,W){super($);this.code=W;this.name="PathSecurityError"}}class P0{static normalize($,W){let Z=d.isAbsolute($)?$:d.resolve(W,$),Y=d.normalize(Z),J=d.normalize(W);if(!this.isWithinWorkspace(Y,J))throw new H$(`Path outside workspace: ${$} (resolved to ${Y}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return Y}static checkRestricted($){let W=$.split(d.sep);for(let Z of wZ)if(W.includes(Z))throw new H$(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new H$(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,W){this.checkTraversal($);let Z=this.normalize($,W);this.checkRestricted(Z);try{await B$.access(Z)}catch(Y){throw new H$(`Path not found: ${$}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink($,W){try{let Z=await B$.realpath($),Y=await B$.realpath(W);if(!this.isWithinWorkspace(Z,Y))throw new H$(`Symlink points outside workspace: ${$} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof H$)throw Z;return $}}static getRelativePath($,W){return d.relative(W,$)}static isWithinWorkspace($,W){let Z=d.resolve($),Y=d.resolve(W),J=d.relative(Y,Z);return J===""||J!==".."&&!J.startsWith(`..${d.sep}`)&&!d.isAbsolute(J)}static async isWithinWorkspaceResolved($,W){let Z=d.resolve(W),Y=d.isAbsolute($)?d.resolve($):d.resolve(Z,$);if(!this.isWithinWorkspace(Y,Z))return!1;let J;try{J=await B$.realpath(Z)}catch{return!1}let X=Y;while(!0){try{let H=await B$.realpath(X);return this.isWithinWorkspace(H,J)}catch(H){let B=H.code;if(B!=="ENOENT"&&B!=="ENOTDIR")return!1}let V=d.dirname(X);if(V===X)return!1;X=V}}static isRestricted($){let W=$.split(d.sep);return wZ.some((Z)=>W.includes(Z))}}var S6=new f6,v$,b2;function I6(){return import("@anthropic-ai/sandbox-runtime")}async function o$(){if(v$)return v$;if(!b2)b2=I6();return v$=await b2,v$}var h6={isSupportedPlatform:async()=>(await o$()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await o$()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await o$()).getDefaultWritePaths(),initialize:async($)=>(await o$()).SandboxManager.initialize($),wrapWithSandboxArgv:async($,W,Z,Y,J)=>(await o$()).SandboxManager.wrapWithSandboxArgv($,W,Z,Y,J),cleanupAfterCommand:()=>v$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await v$?.SandboxManager.reset()}};class Q$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class x$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class GZ{backend;constructor($){this.backend=$}async prepare($){let W=K$.resolve($.workspaceRoot),Z=K$.resolve($.cwd);if(!P0.isWithinWorkspace(Z,W))throw new x$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let Y,J;try{[Y,J]=await Promise.all([M2(W),M2(Z)])}catch(X){throw new x$(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!P0.isWithinWorkspace(J,Y))throw new x$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:J,workspaceRoot:Y})}}class EZ{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??h6,this.tempRoot=$.tempRoot??K$.join(V0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let W=await this.prepareTempRoot(),Z=K$.join(W,"tmp"),Y=K$.join(W,"cache"),J=K$.join(Y,"npm"),X=K$.join(Y,"bun");await Promise.all([T1(Z,{recursive:!0}),T1(J,{recursive:!0}),T1(X,{recursive:!0})]);let H=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((U)=>!U.startsWith("/dev/")),B=process.platform==="win32"?"bash":"/bin/bash",K;try{K=await S6.runExclusive(async()=>{let U=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=Z;try{return await this.runtime.wrapWithSandboxArgv($.command,B,{filesystem:{denyRead:[],allowRead:[],allowWrite:[$.workspaceRoot,W],denyWrite:H},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(U===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=U}})}catch(U){if(U instanceof Error&&U.name==="AbortError")throw U;throw new Q$(`Workspace sandbox failed to prepare the command: ${U instanceof Error?U.message:String(U)}`)}let Q=!1;return{executable:K.argv[0]??B,args:K.argv.slice(1),env:{...K.env,TMPDIR:Z,TMP:Z,TEMP:Z,XDG_CACHE_HOME:Y,npm_config_cache:J,BUN_INSTALL_CACHE_DIR:X},sandboxed:!0,cleanup:()=>{if(Q)return;Q=!0,this.runtime.cleanupAfterCommand()}}}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 Q$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new Q$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize({network:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0})}catch(W){throw new Q$(`Workspace sandbox failed to initialize: ${W instanceof Error?W.message:String(W)}`)}}async prepareTempRoot(){return await T1(this.tempRoot,{recursive:!0}),M2(this.tempRoot)}}function L1($,W){let Z=W.toLowerCase();return $===71&&Z.includes("sandbox-exec")||Z.includes("sandbox_apply: operation not permitted")||Z.includes("bwrap: creating new namespace failed")||Z.includes("failed to create new user namespace")||Z.includes("srt-win sandbox failed")}var u6=new EZ,p6={prepare:($)=>u6.prepare($)},FZ=new GZ(p6);class $0{static instance=null;processes=new Map;static getInstance(){if(!$0.instance)$0.instance=new $0;return $0.instance}startBackgroundProcess($){let W=`bash_${d6()}`,Z={};for(let[B,K]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(K!==void 0)Z[B]=K;let Y=$.sandboxedCommand?.executable??"bash",J=$.sandboxedCommand?.args??["-c",$.command],{child:X,processTree:V}=C$(Y,J,{cwd:$.cwd||D(),env:Z,stdio:["ignore","pipe","pipe"]}),H={id:W,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:X,processTree:V,pid:X.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:"",sandboxed:Boolean($.sandboxedCommand)};return X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(B)=>{H.pendingStdout+=B.toString()}),X.stderr?.on("data",(B)=>{H.pendingStderr+=B.toString()}),X.on("close",(B,K)=>{$.sandboxedCommand?.cleanup();let Q=H.sandboxed&&L1(B,H.pendingStderr);if(H.status=H.status==="killed"?"killed":Q?"error":"exited",H.exitCode=B,H.signal=K,Q)H.errorMessage="Workspace sandbox failed to start; command was not executed";H.endTime=Date.now(),H.process=void 0}),X.on("error",(B)=>{$.sandboxedCommand?.cleanup(),H.status="error",H.errorMessage=B.message,H.endTime=Date.now(),H.process=void 0,H.pendingStderr+=`
2
- [error] ${B.message}`}),this.processes.set(W,H),H}consumeOutput($,W){let Z=this.getProcess($,W);if(!Z)return;let Y={id:Z.id,command:Z.command,status:Z.status,stdout:Z.pendingStdout,stderr:Z.pendingStderr,exitCode:Z.exitCode,signal:Z.signal,pid:Z.pid,startedAt:Z.startTime,endedAt:Z.endTime,errorMessage:Z.errorMessage,sandboxed:Z.sandboxed};return Z.pendingStdout="",Z.pendingStderr="",Y}getProcess($,W){let Z=this.processes.get($);return Z?.sessionId===W?Z:void 0}listForSession($){return Array.from(this.processes.values()).filter((W)=>W.sessionId===$)}async kill($,W){let Z=this.getProcess($,W);if(!Z)return;return this.terminateProcess(Z)}async killSession($){let W=this.listForSession($);await Promise.all(W.map((Z)=>this.terminateProcess(Z)));for(let Z of W)this.processes.delete(Z.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 W=await $.processTree?.terminate();if(!W?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:W?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return{success:!0,alreadyExited:W.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 x2 from"node:fs";import k1 from"node:os";import f0 from"node:path";import g6 from"yaml";var zZ={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
1
+ import{Y as RZ}from"./chunk-e21htmg4.js";import{Z as N,_ as G0}from"./chunk-a8znntss.js";import{$ as yZ,aa as xZ}from"./chunk-rtn0rb16.js";import{ma as U1,na as Z0,oa as k,ra as Y0,sa as n1,ta as W$,ua as j0,va as K1,wa as k0,xa as a1,ya as a0}from"./chunk-5smacbk0.js";import{Aa as r1}from"./chunk-rkhhzc4r.js";import{Ea as h$}from"./chunk-jsn8476q.js";import{Ja as l0,La as I8,Ma as U0,Na as u$,Oa as n0,Ra as t1,Va as N0,db as z2,eb as g8,hb as S5}from"./chunk-7pcm8vy5.js";import{ib as i5,jb as r5,kb as AW}from"./chunk-cyxb6fxe.js";import{lb as HZ,mb as C$,nb as w0}from"./chunk-jf48kahn.js";import{pb as b1,tb as D}from"./chunk-63dzf6hr.js";import{Ab as o1}from"./chunk-98jpdmgc.js";import{Bb as t8,Cb as $$,Db as o,Eb as I$,Fb as i1,Gb as V0,Hb as C5,Lb as f,Mb as S}from"./chunk-w1zb8zac.js";import{Nb as Q$}from"./chunk-kfg3vx5z.js";import{randomUUID as d6}from"crypto";import{mkdir as T1,realpath as M2}from"node:fs/promises";import K$ from"node:path";import{Mutex as P6}from"async-mutex";import*as B$ from"fs/promises";import*as d from"path";var wZ=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class H$ extends Error{code;constructor($,W){super($);this.code=W;this.name="PathSecurityError"}}class f0{static normalize($,W){let Z=d.isAbsolute($)?$:d.resolve(W,$),Y=d.normalize(Z),J=d.normalize(W);if(!this.isWithinWorkspace(Y,J))throw new H$(`Path outside workspace: ${$} (resolved to ${Y}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return Y}static checkRestricted($){let W=$.split(d.sep);for(let Z of wZ)if(W.includes(Z))throw new H$(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new H$(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,W){this.checkTraversal($);let Z=this.normalize($,W);this.checkRestricted(Z);try{await B$.access(Z)}catch(Y){throw new H$(`Path not found: ${$}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink($,W){try{let Z=await B$.realpath($),Y=await B$.realpath(W);if(!this.isWithinWorkspace(Z,Y))throw new H$(`Symlink points outside workspace: ${$} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof H$)throw Z;return $}}static getRelativePath($,W){return d.relative(W,$)}static isWithinWorkspace($,W){let Z=d.resolve($),Y=d.resolve(W),J=d.relative(Y,Z);return J===""||J!==".."&&!J.startsWith(`..${d.sep}`)&&!d.isAbsolute(J)}static async isWithinWorkspaceResolved($,W){let Z=d.resolve(W),Y=d.isAbsolute($)?d.resolve($):d.resolve(Z,$);if(!this.isWithinWorkspace(Y,Z))return!1;let J;try{J=await B$.realpath(Z)}catch{return!1}let X=Y;while(!0){try{let H=await B$.realpath(X);return this.isWithinWorkspace(H,J)}catch(H){let K=H.code;if(K!=="ENOENT"&&K!=="ENOTDIR")return!1}let V=d.dirname(X);if(V===X)return!1;X=V}}static isRestricted($){let W=$.split(d.sep);return wZ.some((Z)=>W.includes(Z))}}var S6=new P6,v$,b2;function I6(){return import("@anthropic-ai/sandbox-runtime")}async function o$(){if(v$)return v$;if(!b2)b2=I6();return v$=await b2,v$}var h6={isSupportedPlatform:async()=>(await o$()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await o$()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await o$()).getDefaultWritePaths(),initialize:async($)=>(await o$()).SandboxManager.initialize($),wrapWithSandboxArgv:async($,W,Z,Y,J)=>(await o$()).SandboxManager.wrapWithSandboxArgv($,W,Z,Y,J),cleanupAfterCommand:()=>v$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await v$?.SandboxManager.reset()}};class U$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class x$ extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class GZ{backend;constructor($){this.backend=$}async prepare($){let W=K$.resolve($.workspaceRoot),Z=K$.resolve($.cwd);if(!f0.isWithinWorkspace(Z,W))throw new x$(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let Y,J;try{[Y,J]=await Promise.all([M2(W),M2(Z)])}catch(X){throw new x$(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!f0.isWithinWorkspace(J,Y))throw new x$(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:J,workspaceRoot:Y})}}class EZ{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??h6,this.tempRoot=$.tempRoot??K$.join(V0(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let W=await this.prepareTempRoot(),Z=K$.join(W,"tmp"),Y=K$.join(W,"cache"),J=K$.join(Y,"npm"),X=K$.join(Y,"bun");await Promise.all([T1(Z,{recursive:!0}),T1(J,{recursive:!0}),T1(X,{recursive:!0})]);let H=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((Q)=>!Q.startsWith("/dev/")),K=process.platform==="win32"?"bash":"/bin/bash",B;try{B=await S6.runExclusive(async()=>{let Q=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=Z;try{return await this.runtime.wrapWithSandboxArgv($.command,K,{filesystem:{denyRead:[],allowRead:[],allowWrite:[$.workspaceRoot,W],denyWrite:H},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(Q===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=Q}})}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")throw Q;throw new U$(`Workspace sandbox failed to prepare the command: ${Q instanceof Error?Q.message:String(Q)}`)}let U=!1;return{executable:B.argv[0]??K,args:B.argv.slice(1),env:{...B.env,TMPDIR:Z,TMP:Z,TEMP:Z,XDG_CACHE_HOME:Y,npm_config_cache:J,BUN_INSTALL_CACHE_DIR:X},sandboxed:!0,cleanup:()=>{if(U)return;U=!0,this.runtime.cleanupAfterCommand()}}}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 U$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new U$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize({network:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0})}catch(W){throw new U$(`Workspace sandbox failed to initialize: ${W instanceof Error?W.message:String(W)}`)}}async prepareTempRoot(){return await T1(this.tempRoot,{recursive:!0}),M2(this.tempRoot)}}function L1($,W){let Z=W.toLowerCase();return $===71&&Z.includes("sandbox-exec")||Z.includes("sandbox_apply: operation not permitted")||Z.includes("bwrap: creating new namespace failed")||Z.includes("failed to create new user namespace")||Z.includes("srt-win sandbox failed")}var u6=new EZ,p6={prepare:($)=>u6.prepare($)},FZ=new GZ(p6);class $0{static instance=null;processes=new Map;static getInstance(){if(!$0.instance)$0.instance=new $0;return $0.instance}startBackgroundProcess($){let W=`bash_${d6()}`,Z={};for(let[K,B]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(B!==void 0)Z[K]=B;let Y=$.sandboxedCommand?.executable??"bash",J=$.sandboxedCommand?.args??["-c",$.command],{child:X,processTree:V}=C$(Y,J,{cwd:$.cwd||D(),env:Z,stdio:["ignore","pipe","pipe"]}),H={id:W,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:X,processTree:V,pid:X.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:"",sandboxed:Boolean($.sandboxedCommand)};return X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(K)=>{H.pendingStdout+=K.toString()}),X.stderr?.on("data",(K)=>{H.pendingStderr+=K.toString()}),X.on("close",(K,B)=>{$.sandboxedCommand?.cleanup();let U=H.sandboxed&&L1(K,H.pendingStderr);if(H.status=H.status==="killed"?"killed":U?"error":"exited",H.exitCode=K,H.signal=B,U)H.errorMessage="Workspace sandbox failed to start; command was not executed";H.endTime=Date.now(),H.process=void 0}),X.on("error",(K)=>{$.sandboxedCommand?.cleanup(),H.status="error",H.errorMessage=K.message,H.endTime=Date.now(),H.process=void 0,H.pendingStderr+=`
2
+ [error] ${K.message}`}),this.processes.set(W,H),H}consumeOutput($,W){let Z=this.getProcess($,W);if(!Z)return;let Y={id:Z.id,command:Z.command,status:Z.status,stdout:Z.pendingStdout,stderr:Z.pendingStderr,exitCode:Z.exitCode,signal:Z.signal,pid:Z.pid,startedAt:Z.startTime,endedAt:Z.endTime,errorMessage:Z.errorMessage,sandboxed:Z.sandboxed};return Z.pendingStdout="",Z.pendingStderr="",Y}getProcess($,W){let Z=this.processes.get($);return Z?.sessionId===W?Z:void 0}listForSession($){return Array.from(this.processes.values()).filter((W)=>W.sessionId===$)}async kill($,W){let Z=this.getProcess($,W);if(!Z)return;return this.terminateProcess(Z)}async killSession($){let W=this.listForSession($);await Promise.all(W.map((Z)=>this.terminateProcess(Z)));for(let Z of W)this.processes.delete(Z.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 W=await $.processTree?.terminate();if(!W?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:W?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return{success:!0,alreadyExited:W.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 x2 from"node:fs";import k1 from"node:os";import P0 from"node:path";import g6 from"yaml";var zZ={name:"verification",description:"Independent verification agent that validates implementation by running builds, tests, linters, and adversarial"+" probes. Strictly read-only — cannot modify code. Use"+" after completing implementation to get an independent quality assessment.",tools:["Read","Glob","Grep","Bash"],systemPrompt:`# Verification Agent
3
3
 
4
4
  You are an **independent verification engineer**. Your sole purpose is to find problems — not to praise or reassure. You are the last line of defense before code ships.
5
5
 
@@ -157,9 +157,9 @@ You are a software architect specializing in implementation planning.
157
157
  **Risks**:
158
158
  - [Potential issue and mitigation]
159
159
 
160
- Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},zZ];var C2=P("Agent");class OZ{subagents=new Map;register($){if(this.subagents.has($.name))throw Error(`Subagent '${$.name}' already registered`);this.subagents.set($.name,$)}applyOverrides($){for(let W of $)this.subagents.set(W.name,W)}getSubagent($){return this.subagents.get($)}getAllNames(){return Array.from(this.subagents.keys())}getAllSubagents(){return Array.from(this.subagents.values())}getDescriptionsForPrompt(){let $=this.getAllSubagents();if($.length===0)return"No subagents available.";return`Available agent types and the tools they have access to:
160
+ Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},zZ];var C2=f("Agent");class OZ{subagents=new Map;register($){if(this.subagents.has($.name))throw Error(`Subagent '${$.name}' already registered`);this.subagents.set($.name,$)}applyOverrides($){for(let W of $)this.subagents.set(W.name,W)}getSubagent($){return this.subagents.get($)}getAllNames(){return Array.from(this.subagents.keys())}getAllSubagents(){return Array.from(this.subagents.values())}getDescriptionsForPrompt(){let $=this.getAllSubagents();if($.length===0)return"No subagents available.";return`Available agent types and the tools they have access to:
161
161
  ${$.map((Z)=>{let Y=!Z.tools||Z.tools.length===0?"All tools":Z.tools.join(", ");return`- ${Z.name}: ${Z.description} (Tools: ${Y})`}).join(`
162
- `)}`}loadFromDirectory($,W){if(!x2.existsSync($))return;let Z=x2.readdirSync($);for(let Y of Z){if(!Y.endsWith(".md"))continue;let J=f0.join($,Y);try{let X=this.parseConfigFile(J,W);this.subagents.set(X.name,X)}catch(X){C2.warn(`Failed to load subagent config from ${J}:`,X)}}}parseConfigFile($,W){let Y=x2.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!Y)throw Error(`No YAML frontmatter found in ${$}`);let[,J,X]=Y,V=g6.parse(J);if(!V.name||!V.description)throw Error(`Missing required fields (name, description) in ${$}`);if(V.isolation!==void 0&&V.isolation!=="none"&&V.isolation!=="worktree")throw Error(`Invalid isolation mode "${String(V.isolation)}" in ${$}`);let H=X.trim(),B=this.parseStringOrArray(V.tools),K=this.parseStringOrArray(V.skills),Q=RZ(V.permissionMode);return{name:V.name,description:V.description,systemPrompt:H,tools:B,color:V.color,configPath:$,model:V.model||"inherit",permissionMode:Q,skills:K,isolation:V.isolation,source:W}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((W)=>W.trim()).filter(Boolean);return $.split(",").map((W)=>W.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=f0.join(k1.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let W=f0.join(D(),".claude","agents");this.loadFromDirectory(W,"claude-code-project");let Z=f0.join(k1.homedir(),".blade","agents");this.loadFromDirectory(Z,"blade-user");let Y=f0.join(D(),".blade","agents");this.loadFromDirectory(Y,"blade-project");let J=this.getAllNames().length;return C2.debug(`Loaded ${J} subagents from standard locations`),J}loadBuiltinAgents(){for(let $ of v2)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});C2.debug(`Loaded ${v2.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],flag:[],plugin:[]};for(let W of this.subagents.values()){let Z=W.source||"builtin",Y=Z.startsWith("plugin:")?"plugin":Z;$[Y].push(W)}return $}clearPluginAgents(){let $=[];for(let[W,Z]of this.subagents.entries())if(Z.source?.startsWith("plugin:"))$.push(W);for(let W of $)this.subagents.delete(W)}static getClaudeCodeAgentsDir($){if($==="user")return f0.join(k1.homedir(),".claude","agents");return f0.join(D(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return f0.join(k1.homedir(),".blade","agents");return f0.join(D(),".blade","agents")}}var f=new OZ;import{stat as qY}from"node:fs/promises";import*as b8 from"os";import*as M8 from"path";import m6 from"fs/promises";import c6 from"path";var DZ=P("General");async function M1($){for(let W of $)try{let Z;if(W.trim().startsWith("{")){let X=JSON.parse(W);if(X.name&&X.type){let{name:V,...H}=X;Z={[V]:H}}else Z=X}else{let X=c6.resolve(b1(),W),V=await m6.readFile(X,"utf-8"),H=JSON.parse(V);Z=H.mcpServers||H}let J={...k0(),...Z};Z0().config.actions.updateConfig({mcpServers:J}),DZ.debug(`[OK] Loaded MCP config from CLI: ${Object.keys(Z).join(", ")}`)}catch(Z){DZ.warn(`[WARN] Failed to load MCP config "${W}":`,Z)}}function _Z(){return`You are Blade Code, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
162
+ `)}`}loadFromDirectory($,W){if(!x2.existsSync($))return;let Z=x2.readdirSync($);for(let Y of Z){if(!Y.endsWith(".md"))continue;let J=P0.join($,Y);try{let X=this.parseConfigFile(J,W);this.subagents.set(X.name,X)}catch(X){C2.warn(`Failed to load subagent config from ${J}:`,X)}}}parseConfigFile($,W){let Y=x2.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!Y)throw Error(`No YAML frontmatter found in ${$}`);let[,J,X]=Y,V=g6.parse(J);if(!V.name||!V.description)throw Error(`Missing required fields (name, description) in ${$}`);if(V.isolation!==void 0&&V.isolation!=="none"&&V.isolation!=="worktree")throw Error(`Invalid isolation mode "${String(V.isolation)}" in ${$}`);let H=X.trim(),K=this.parseStringOrArray(V.tools),B=this.parseStringOrArray(V.skills),U=RZ(V.permissionMode);return{name:V.name,description:V.description,systemPrompt:H,tools:K,color:V.color,configPath:$,model:V.model||"inherit",permissionMode:U,skills:B,isolation:V.isolation,source:W}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((W)=>W.trim()).filter(Boolean);return $.split(",").map((W)=>W.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=P0.join(k1.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let W=P0.join(D(),".claude","agents");this.loadFromDirectory(W,"claude-code-project");let Z=P0.join(k1.homedir(),".blade","agents");this.loadFromDirectory(Z,"blade-user");let Y=P0.join(D(),".blade","agents");this.loadFromDirectory(Y,"blade-project");let J=this.getAllNames().length;return C2.debug(`Loaded ${J} subagents from standard locations`),J}loadBuiltinAgents(){for(let $ of v2)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});C2.debug(`Loaded ${v2.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],flag:[],plugin:[]};for(let W of this.subagents.values()){let Z=W.source||"builtin",Y=Z.startsWith("plugin:")?"plugin":Z;$[Y].push(W)}return $}clearPluginAgents(){let $=[];for(let[W,Z]of this.subagents.entries())if(Z.source?.startsWith("plugin:"))$.push(W);for(let W of $)this.subagents.delete(W)}static getClaudeCodeAgentsDir($){if($==="user")return P0.join(k1.homedir(),".claude","agents");return P0.join(D(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return P0.join(k1.homedir(),".blade","agents");return P0.join(D(),".blade","agents")}}var P=new OZ;import{stat as qY}from"node:fs/promises";import*as b8 from"os";import*as M8 from"path";import m6 from"fs/promises";import c6 from"path";var _Z=f("General");async function M1($){for(let W of $)try{let Z;if(W.trim().startsWith("{")){let X=JSON.parse(W);if(X.name&&X.type){let{name:V,...H}=X;Z={[V]:H}}else Z=X}else{let X=c6.resolve(b1(),W),V=await m6.readFile(X,"utf-8"),H=JSON.parse(V);Z=H.mcpServers||H}let J={...k0(),...Z};Z0().config.actions.updateConfig({mcpServers:J}),_Z.debug(`[OK] Loaded MCP config from CLI: ${Object.keys(Z).join(", ")}`)}catch(Z){_Z.warn(`[WARN] Failed to load MCP config "${W}":`,Z)}}function DZ(){return`You are Blade Code, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
163
163
 
164
164
  IMPORTANT: Assist with authorized security testing, defensive security, CTF challenges, and educational contexts. Refuse requests for destructive techniques, DoS attacks, mass targeting, supply chain compromise, or detection evasion for malicious purposes. Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.
165
165
  IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.`}function jZ(){return`# System
@@ -261,7 +261,7 @@ You have a persistent memory system that survives across sessions. Your memories
261
261
  **Rules:**
262
262
  - Don't save trivial or obvious information
263
263
  - Don't save sensitive data (passwords, tokens, keys)
264
- - Keep MEMORY.md under 200 lines — overflow into topic files`}function r6(){return[_Z(),jZ(),AZ(),NZ(),TZ(),LZ(),kZ(),bZ(),l6(),i6(),`# Language Requirement
264
+ - Keep MEMORY.md under 200 lines — overflow into topic files`}function r6(){return[DZ(),jZ(),AZ(),NZ(),TZ(),LZ(),kZ(),bZ(),l6(),i6(),`# Language Requirement
265
265
  {{LANGUAGE_INSTRUCTION}}`].join(`
266
266
 
267
267
  `)}var MZ=r6(),vZ=`You are in **PLAN MODE** - a read-only research phase for designing implementation plans.
@@ -306,66 +306,66 @@ Your plan should include:
306
306
  5. **Risks** - Potential issues and mitigations
307
307
  `;function s$($){return`<system-reminder>Plan mode is active. You MUST NOT make any file changes or run non-readonly tools. Research only, then call ExitPlanMode with your plan.</system-reminder>
308
308
 
309
- `+$}import{promises as n6}from"fs";import z0 from"path";var a6=32768,o6=["CLAUDE.md","AGENTS.md","BLADE.md"];function s6($){let W=z0.resolve($),Z=z0.resolve(b1()),Y=z0.relative(W,Z),X=Y===""||!Y.startsWith("..")&&!z0.isAbsolute(Y)?Z:W,V=z0.resolve(xZ(X)),H=[],B=X;while(!0){if(H.push(B),B===V)break;let K=z0.dirname(B);if(K===B||!B.startsWith(`${V}${z0.sep}`))return{root:X,directories:[X]};B=K}return H.reverse(),{root:V,directories:H}}function t6($,W){let Z=Buffer.from($,"utf8");if(Z.length<=W)return $;return Z.subarray(0,W).toString("utf8").replace(/\uFFFD+$/u,"")}function e6($,W){return(z0.relative($,W)||z0.basename(W)).split(z0.sep).join("/").replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}async function $9($){try{let W=(await n6.readFile($,"utf8")).trim();return W?{path:$,content:W,truncated:!1}:null}catch{return null}}async function CZ($,W=a6){if(W<=0)return null;let{root:Z,directories:Y}=s6($),J=Y.flatMap((K)=>o6.map((Q)=>z0.join(K,Q))),X=(await Promise.all(J.map($9))).filter((K)=>K!==null);if(X.length===0)return null;let V=W,H=[];for(let K=X.length-1;K>=0&&V>0;K-=1){let Q=X[K];if(!Q)continue;let U=Buffer.byteLength(Q.content,"utf8"),q=t6(Q.content,V),w=Buffer.byteLength(q,"utf8");if(w===0)continue;H.push({...Q,content:q,truncated:w<U}),V-=w}return H.reverse(),{content:`<project-instructions>
310
- ${H.map((K)=>{let Q=K.truncated?' truncated="true"':"";return`<instruction-file path="${e6(Z,K.path)}"${Q}>
311
- ${K.content}
309
+ `+$}import{promises as n6}from"fs";import z0 from"path";var a6=32768,o6=["CLAUDE.md","AGENTS.md","BLADE.md"];function s6($){let W=z0.resolve($),Z=z0.resolve(b1()),Y=z0.relative(W,Z),X=Y===""||!Y.startsWith("..")&&!z0.isAbsolute(Y)?Z:W,V=z0.resolve(xZ(X)),H=[],K=X;while(!0){if(H.push(K),K===V)break;let B=z0.dirname(K);if(B===K||!K.startsWith(`${V}${z0.sep}`))return{root:X,directories:[X]};K=B}return H.reverse(),{root:V,directories:H}}function t6($,W){let Z=Buffer.from($,"utf8");if(Z.length<=W)return $;return Z.subarray(0,W).toString("utf8").replace(/\uFFFD+$/u,"")}function e6($,W){return(z0.relative($,W)||z0.basename(W)).split(z0.sep).join("/").replaceAll("&","&amp;").replaceAll('"',"&quot;").replaceAll("<","&lt;").replaceAll(">","&gt;")}async function $9($){try{let W=(await n6.readFile($,"utf8")).trim();return W?{path:$,content:W,truncated:!1}:null}catch{return null}}async function CZ($,W=a6){if(W<=0)return null;let{root:Z,directories:Y}=s6($),J=Y.flatMap((B)=>o6.map((U)=>z0.join(B,U))),X=(await Promise.all(J.map($9))).filter((B)=>B!==null);if(X.length===0)return null;let V=W,H=[];for(let B=X.length-1;B>=0&&V>0;B-=1){let U=X[B];if(!U)continue;let Q=Buffer.byteLength(U.content,"utf8"),q=t6(U.content,V),w=Buffer.byteLength(q,"utf8");if(w===0)continue;H.push({...U,content:q,truncated:w<Q}),V-=w}return H.reverse(),{content:`<project-instructions>
310
+ ${H.map((B)=>{let U=B.truncated?' truncated="true"':"";return`<instruction-file path="${e6(Z,B.path)}"${U}>
311
+ ${B.content}
312
312
  </instruction-file>`}).join(`
313
313
 
314
314
  `)}
315
- </project-instructions>`,files:H,contentBytes:W-V}}var W9=/<available_skills>\s*<\/available_skills>/;async function q$($={}){let{projectPath:W,replaceDefault:Z,append:Y,mode:J,includeEnvironment:X=!0,environmentOptions:V,language:H}=$,B=[],K=[],Q=J==="plan",U,q;if(Q)U=vZ,q="plan_mode_prompt";else U=Z??MZ,q=Z?"replace_default":"default";if(B.push(U),K.push({name:q,loaded:!0,length:U.length}),W){let E=await CZ(W);if(E)B.push(E.content),K.push({name:"project_instructions",loaded:!0,length:E.content.length});else K.push({name:"project_instructions",loaded:!1})}if(W&&process.env.BLADE_AUTO_MEMORY!=="0")try{let G=await new l0(W).loadIndex();if(G)B.push(`<auto-memory>
315
+ </project-instructions>`,files:H,contentBytes:W-V}}var W9=/<available_skills>\s*<\/available_skills>/;async function q$($={}){let{projectPath:W,replaceDefault:Z,append:Y,mode:J,includeEnvironment:X=!0,environmentOptions:V,language:H}=$,K=[],B=[],U=J==="plan",Q,q;if(U)Q=vZ,q="plan_mode_prompt";else Q=Z??MZ,q=Z?"replace_default":"default";if(K.push(Q),B.push({name:q,loaded:!0,length:Q.length}),W){let E=await CZ(W);if(E)K.push(E.content),B.push({name:"project_instructions",loaded:!0,length:E.content.length});else B.push({name:"project_instructions",loaded:!1})}if(W&&process.env.BLADE_AUTO_MEMORY!=="0")try{let G=await new l0(W).loadIndex();if(G)K.push(`<auto-memory>
316
316
  ${G}
317
- </auto-memory>`),K.push({name:"auto_memory",loaded:!0,length:G.length});else K.push({name:"auto_memory",loaded:!1})}catch{K.push({name:"auto_memory",loaded:!1})}if(X){let E=yZ(W?{...V,workingDirectory:W}:V);if(E)B.push(E),K.push({name:"environment",loaded:!0,length:E.length})}if(Y?.trim())B.push(Y.trim()),K.push({name:"append",loaded:!0,length:Y.trim().length});let w=B.join(`
317
+ </auto-memory>`),B.push({name:"auto_memory",loaded:!0,length:G.length});else B.push({name:"auto_memory",loaded:!1})}catch{B.push({name:"auto_memory",loaded:!1})}if(X){let E=yZ(W?{...V,workingDirectory:W}:V);if(E)K.push(E),B.push({name:"environment",loaded:!0,length:E.length})}if(Y?.trim())K.push(Y.trim()),B.push({name:"append",loaded:!0,length:Y.trim().length});let w=K.join(`
318
318
 
319
319
  ---
320
320
 
321
- `);return w=Z9(w),w=J9(w,H),{prompt:w,sources:K}}function Z9($){let Z=Q0().generateAvailableSkillsList();if(!Z)return $;return $.replace(W9,`<available_skills>
321
+ `);return w=Z9(w),w=J9(w,H),{prompt:w,sources:B}}function Z9($){let Z=U0().generateAvailableSkillsList();if(!Z)return $;return $.replace(W9,`<available_skills>
322
322
  ${Z}
323
- </available_skills>`)}var Y9={"zh-CN":"Chinese (Simplified Chinese)","zh-TW":"Chinese (Traditional Chinese)","en-US":"English","en-GB":"English (British)","ja-JP":"Japanese","ko-KR":"Korean","es-ES":"Spanish","fr-FR":"French","de-DE":"German","pt-BR":"Portuguese (Brazilian)","ru-RU":"Russian"};function J9($,W){let Z=W||"zh-CN",Y=Y9[Z]||Z,J=`IMPORTANT: Always respond in ${Y}. All your responses must be in ${Y}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",J)}import PZ from"fast-glob";import*as y$ from"fs/promises";import*as fZ from"path";function dX($){return $.endsWith("/")||$.endsWith("\\")}function t$($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}class v1{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let W=[],Z;this.PATTERN.lastIndex=0;while((Z=this.PATTERN.exec($))!==null){let Y=Z[0],J=Z[1]||Z[2],X=this.parseLineRange(J);if(X)J=J.replace(this.LINE_RANGE_PATTERN,"");let V=this.GLOB_PATTERN.test(J);W.push({raw:Y,path:J.trim(),lineRange:X,startIndex:Z.index,endIndex:Z.index+Y.length,isGlob:V})}return W}static parseLineRange($){let W=$.match(this.LINE_RANGE_PATTERN);if(!W)return;let Z=parseInt(W[1],10),Y=W[2]?parseInt(W[2],10):void 0;return{start:Z,end:Y}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let W=["<",">","|","\x00"];for(let Z of W)if($.includes(Z))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var R0=P("Prompts");function x1($){return $ instanceof Map}class e${fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},R0.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}setCwd($){if(this.options.cwd===$)return;this.options.cwd=$,this.fileCache.clear()}async collect($){if(!v1.hasAtMentions($))return[];let W=v1.extract($);if(W.length===0)return[];R0.debug(`Found ${W.length} @ mentions`);let Z=W.map((J)=>this.processOne(J));return(await Promise.allSettled(Z)).map((J,X)=>{if(J.status==="fulfilled")return J.value;else{let V=W[X],H=J.reason instanceof Error?J.reason.message:String(J.reason);return R0.warn(`Failed to process @${V.path}:`,H),{type:"error",path:V.path,content:"",error:H}}})}async processOne($){if($.isGlob)return R0.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let W=await P0.validatePath($.path,this.options.cwd),Z=await P0.resolveSymlink(W,this.options.cwd);if((await y$.stat(Z)).isDirectory())return R0.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(Z,$.path);return R0.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(Z,$.path,$.lineRange)}async readFile($,W,Z){let Y=this.fileCache.get($);if(Y&&Date.now()-Y.timestamp<60000)return R0.debug(`Cache hit: ${W}`),this.formatFileAttachment(W,Y.content,Z);let J=await y$.stat($);if(J.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(J.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let X;try{X=await y$.readFile($,"utf-8")}catch(V){throw Error(`Cannot read file as text: ${W}. It may be a binary file.`)}return this.fileCache.set($,{content:X,timestamp:Date.now()}),this.formatFileAttachment(W,X,Z)}formatFileAttachment($,W,Z){let Y=W.split(`
324
- `),J=W,X=!1,V=Z;if(Z){let H=Math.max(0,Z.start-1),B=Z.end?Z.end:Z.start;if(H>=Y.length)throw Error(`Line range start (${Z.start}) exceeds file length (${Y.length} lines)`);let K=Math.min(B,Y.length);J=Y.slice(H,K).join(`
325
- `);let Q=Array.from({length:K-H},(q,w)=>H+w+1);J=J.split(`
326
- `).map((q,w)=>`${Q[w]}: ${q}`).join(`
327
- `),V={start:Z.start,end:K}}else if(Y.length>this.options.maxLines)J=Y.slice(0,this.options.maxLines).join(`
323
+ </available_skills>`)}var Y9={"zh-CN":"Chinese (Simplified Chinese)","zh-TW":"Chinese (Traditional Chinese)","en-US":"English","en-GB":"English (British)","ja-JP":"Japanese","ko-KR":"Korean","es-ES":"Spanish","fr-FR":"French","de-DE":"German","pt-BR":"Portuguese (Brazilian)","ru-RU":"Russian"};function J9($,W){let Z=W||"zh-CN",Y=Y9[Z]||Z,J=`IMPORTANT: Always respond in ${Y}. All your responses must be in ${Y}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",J)}import fZ from"fast-glob";import*as y$ from"fs/promises";import*as PZ from"path";function dX($){return $.endsWith("/")||$.endsWith("\\")}function t$($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}class v1{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let W=[],Z;this.PATTERN.lastIndex=0;while((Z=this.PATTERN.exec($))!==null){let Y=Z[0],J=Z[1]||Z[2],X=this.parseLineRange(J);if(X)J=J.replace(this.LINE_RANGE_PATTERN,"");let V=this.GLOB_PATTERN.test(J);W.push({raw:Y,path:J.trim(),lineRange:X,startIndex:Z.index,endIndex:Z.index+Y.length,isGlob:V})}return W}static parseLineRange($){let W=$.match(this.LINE_RANGE_PATTERN);if(!W)return;let Z=parseInt(W[1],10),Y=W[2]?parseInt(W[2],10):void 0;return{start:Z,end:Y}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let W=["<",">","|","\x00"];for(let Z of W)if($.includes(Z))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var R0=f("Prompts");function x1($){return $ instanceof Map}class e${fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},R0.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}setCwd($){if(this.options.cwd===$)return;this.options.cwd=$,this.fileCache.clear()}async collect($){if(!v1.hasAtMentions($))return[];let W=v1.extract($);if(W.length===0)return[];R0.debug(`Found ${W.length} @ mentions`);let Z=W.map((J)=>this.processOne(J));return(await Promise.allSettled(Z)).map((J,X)=>{if(J.status==="fulfilled")return J.value;else{let V=W[X],H=J.reason instanceof Error?J.reason.message:String(J.reason);return R0.warn(`Failed to process @${V.path}:`,H),{type:"error",path:V.path,content:"",error:H}}})}async processOne($){if($.isGlob)return R0.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let W=await f0.validatePath($.path,this.options.cwd),Z=await f0.resolveSymlink(W,this.options.cwd);if((await y$.stat(Z)).isDirectory())return R0.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(Z,$.path);return R0.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(Z,$.path,$.lineRange)}async readFile($,W,Z){let Y=this.fileCache.get($);if(Y&&Date.now()-Y.timestamp<60000)return R0.debug(`Cache hit: ${W}`),this.formatFileAttachment(W,Y.content,Z);let J=await y$.stat($);if(J.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(J.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let X;try{X=await y$.readFile($,"utf-8")}catch(V){throw Error(`Cannot read file as text: ${W}. It may be a binary file.`)}return this.fileCache.set($,{content:X,timestamp:Date.now()}),this.formatFileAttachment(W,X,Z)}formatFileAttachment($,W,Z){let Y=W.split(`
324
+ `),J=W,X=!1,V=Z;if(Z){let H=Math.max(0,Z.start-1),K=Z.end?Z.end:Z.start;if(H>=Y.length)throw Error(`Line range start (${Z.start}) exceeds file length (${Y.length} lines)`);let B=Math.min(K,Y.length);J=Y.slice(H,B).join(`
325
+ `);let U=Array.from({length:B-H},(q,w)=>H+w+1);J=J.split(`
326
+ `).map((q,w)=>`${U[w]}: ${q}`).join(`
327
+ `),V={start:Z.start,end:B}}else if(Y.length>this.options.maxLines)J=Y.slice(0,this.options.maxLines).join(`
328
328
  `),J+=`
329
329
 
330
- [... truncated ${Y.length-this.options.maxLines} lines ...]`,X=!0;return{type:"file",path:$,content:J,metadata:{size:W.length,lines:Y.length,truncated:X,lineRange:V}}}async renderDirectoryTree($,W){let Z=await PZ("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"directory",path:W,content:"(empty directory)"};R0.debug(`Found ${Z.length} files in directory: ${W}`);let Y=this.buildFileTree(Z),J=this.printTree(Y,W),X=500,V=Z.length>X?`
330
+ [... truncated ${Y.length-this.options.maxLines} lines ...]`,X=!0;return{type:"file",path:$,content:J,metadata:{size:W.length,lines:Y.length,truncated:X,lineRange:V}}}async renderDirectoryTree($,W){let Z=await fZ("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"directory",path:W,content:"(empty directory)"};R0.debug(`Found ${Z.length} files in directory: ${W}`);let Y=this.buildFileTree(Z),J=this.printTree(Y,W),X=500,V=Z.length>X?`
331
331
 
332
- [... and ${Z.length-X} more files]`:"";return{type:"directory",path:W,content:J+V,metadata:{lines:Z.length,truncated:Z.length>X}}}buildFileTree($){let W=new Map;for(let Z of $){let Y=t$(Z),J=W;for(let X=0;X<Y.length;X++){let V=Y[X],H=X===Y.length-1;if(!J.has(V))J.set(V,H?null:new Map);if(!H){let B=J.get(V);if(B&&x1(B))J=B}}}return W}printTree($,W,Z="",Y=!0){let J=[];if(Z==="")J.push(`${W}/`);let X=Array.from($.entries()).sort((V,H)=>{let B=x1(V[1]),K=x1(H[1]);if(B!==K)return K?1:-1;return V[0].localeCompare(H[0])});return X.forEach(([V,H],B)=>{let K=B===X.length-1,Q=K?"└── ":"├── ",U=x1(H);if(J.push(`${Z}${Q}${V}${U?"/":""}`),U&&H.size>0){let q=Z+(K?" ":"│ ");J.push(this.printTree(H,"",q,K))}}),J.filter((V)=>V).join(`
333
- `)}async processGlob($){let W=await PZ($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(W.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};R0.debug(`Glob pattern "${$}" matched ${W.length} files`);let Z=30,Y=W.slice(0,Z),X=(await Promise.allSettled(Y.map(async(K)=>{let Q=fZ.join(this.options.cwd,K);try{let U=await y$.readFile(Q,"utf-8"),q=U.split(`
334
- `),w=200,E=U,G=!1;if(q.length>200)E=q.slice(0,200).join(`
332
+ [... and ${Z.length-X} more files]`:"";return{type:"directory",path:W,content:J+V,metadata:{lines:Z.length,truncated:Z.length>X}}}buildFileTree($){let W=new Map;for(let Z of $){let Y=t$(Z),J=W;for(let X=0;X<Y.length;X++){let V=Y[X],H=X===Y.length-1;if(!J.has(V))J.set(V,H?null:new Map);if(!H){let K=J.get(V);if(K&&x1(K))J=K}}}return W}printTree($,W,Z="",Y=!0){let J=[];if(Z==="")J.push(`${W}/`);let X=Array.from($.entries()).sort((V,H)=>{let K=x1(V[1]),B=x1(H[1]);if(K!==B)return B?1:-1;return V[0].localeCompare(H[0])});return X.forEach(([V,H],K)=>{let B=K===X.length-1,U=B?"└── ":"├── ",Q=x1(H);if(J.push(`${Z}${U}${V}${Q?"/":""}`),Q&&H.size>0){let q=Z+(B?" ":"│ ");J.push(this.printTree(H,"",q,B))}}),J.filter((V)=>V).join(`
333
+ `)}async processGlob($){let W=await fZ($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(W.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};R0.debug(`Glob pattern "${$}" matched ${W.length} files`);let Z=30,Y=W.slice(0,Z),X=(await Promise.allSettled(Y.map(async(B)=>{let U=PZ.join(this.options.cwd,B);try{let Q=await y$.readFile(U,"utf-8"),q=Q.split(`
334
+ `),w=200,E=Q,G=!1;if(q.length>200)E=q.slice(0,200).join(`
335
335
  `),E+=`
336
336
 
337
- [... truncated ${q.length-200} lines ...]`,G=!0;return{path:K,content:E,lines:q.length,truncated:G}}catch(U){return{path:K,content:`[Error: ${U instanceof Error?U.message:"unknown error"}]`,lines:0,truncated:!1}}}))).map((K)=>K.status==="fulfilled"?K.value:null).filter((K)=>K!==null),H=X.map((K)=>`--- ${K.path} (${K.lines} lines${K.truncated?", truncated":""}) ---
338
- ${K.content}`).join(`
337
+ [... truncated ${q.length-200} lines ...]`,G=!0;return{path:B,content:E,lines:q.length,truncated:G}}catch(Q){return{path:B,content:`[Error: ${Q instanceof Error?Q.message:"unknown error"}]`,lines:0,truncated:!1}}}))).map((B)=>B.status==="fulfilled"?B.value:null).filter((B)=>B!==null),H=X.map((B)=>`--- ${B.path} (${B.lines} lines${B.truncated?", truncated":""}) ---
338
+ ${B.content}`).join(`
339
339
 
340
- `),B=W.length>Z?`
340
+ `),K=W.length>Z?`
341
341
 
342
- [... and ${W.length-Z} more files matched]`:"";return{type:"file",path:$,content:H+B,metadata:{lines:X.reduce((K,Q)=>K+Q.lines,0),truncated:W.length>Z||X.some((K)=>K.truncated)}}}clearExpiredCache(){let $=Date.now(),W=0;for(let[Z,Y]of this.fileCache.entries())if($-Y.timestamp>60000)this.fileCache.delete(Z),W++;if(W>0)R0.debug(`Cleared ${W} expired cache entries`)}clearCache(){this.fileCache.clear(),R0.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import*as R8 from"os";import*as O8 from"path";import{basename as H9,extname as B9}from"path";import{z as y1}from"zod";import*as O0 from"fs/promises";class i0{async readTextFile($){return O0.readFile($,"utf-8")}async writeTextFile($,W){await O0.writeFile($,W,"utf-8")}async exists($){try{return await O0.access($),!0}catch{return!1}}async readBinaryFile($){return O0.readFile($)}async stat($){try{let W=await O0.stat($);return{size:W.size,isDirectory:W.isDirectory(),isFile:W.isFile(),mtime:W.mtime}}catch{return null}}async mkdir($,W){await O0.mkdir($,{recursive:W?.recursive??!1,mode:W?.mode??493})}}var y2=new i0;function P$(){return y2}function C1($){y2=$}function SZ(){y2=new i0}var U0=P("Agent");class P2{connection;sessionId;capabilities;fallback;constructor($,W,Z,Y=new i0){this.connection=$;this.sessionId=W;this.capabilities=Z;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return U0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return U0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(W){return U0.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${W}`),this.fallback.readTextFile($)}}async writeTextFile($,W){if(!this.capabilities.writeTextFile)return U0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,W);try{U0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:W,sessionId:this.sessionId})}catch(Z){return U0.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${Z}`),this.fallback.writeTextFile($,W)}}async exists($){if(!this.capabilities.readTextFile)return U0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),U0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(W){let Z=String(W).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((V)=>Z.includes(V)))return U0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=X9(Z);return U0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(W),errorType:X,filePath:$}),!0}}async readBinaryFile($){return U0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return U0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,W){return U0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,W)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function X9($){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 b0=P("Agent");class f2{async execute($,W){return new Promise((Z)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",J=process.platform==="win32"?["/c",$]:["-c",$],{child:X,processTree:V}=C$(Y,J,{cwd:W?.cwd||D(),env:{...process.env,...W?.env},stdio:["pipe","pipe","pipe"]}),H,B=()=>{return H??=V.terminate(),H},K="",Q="",U=!1,q=W?.timeout?setTimeout(()=>{U=!0,B()},W.timeout):null,w=null,E=()=>{if(q)clearTimeout(q);if(w&&W?.signal)W.signal.removeEventListener("abort",w),w=null};if(W?.signal){if(w=()=>{U=!0,B()},W.signal.addEventListener("abort",w),W.signal.aborted)w()}X.stdout?.on("data",(G)=>{let F=G.toString();K+=F,W?.onOutput?.(F)}),X.stderr?.on("data",(G)=>{let F=G.toString();Q+=F,W?.onOutput?.(F)}),X.on("close",async(G)=>{if(E(),U)await B();Z({success:G===0&&!U,stdout:K,stderr:Q,exitCode:G,error:U?"Command was terminated":void 0})}),X.on("error",(G)=>{E(),Z({success:!1,stdout:K,stderr:Q,exitCode:null,error:G.message})})})}isAvailable(){return!0}}class IZ{connection;sessionId;fallback;constructor($,W,Z=new f2){this.connection=$;this.sessionId=W;this.fallback=Z}async execute($,W){try{b0.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let Z=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:W?.cwd,env:W?.env?Object.entries(W.env).map(([K,Q])=>({name:K,value:Q})):void 0}),Y=0,J=null;if(W?.onOutput)J=setInterval(async()=>{try{let Q=(await Z.currentOutput()).output||"";if(Q.length>Y){let U=Q.slice(Y);Y=Q.length,W.onOutput?.(U)}}catch{}},100);let X=(K=!1)=>{if(J)clearInterval(J),J=null;(K?Z.kill().then(()=>b0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>Z.release()).catch(()=>{}):Z.release().catch(()=>{})).catch(()=>{})},V=[];if(V.push(Z.waitForExit().then((K)=>({type:"completed",exitCode:K.exitCode??null}))),W?.timeout)V.push(new Promise((K)=>{setTimeout(()=>K({type:"timeout"}),W.timeout)}));if(W?.signal)V.push(new Promise((K)=>{if(W.signal.aborted)K({type:"aborted"});else W.signal.addEventListener("abort",()=>K({type:"aborted"}),{once:!0})}));let H=await Promise.race(V),B="";try{if(B=(await Z.currentOutput()).output||"",W?.onOutput&&B.length>Y)W.onOutput(B.slice(Y))}catch{}switch(H.type){case"completed":return X(!1),{success:H.exitCode===0,stdout:B,stderr:"",exitCode:H.exitCode};case"timeout":return b0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),X(!0),{success:!1,stdout:B,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return b0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),X(!0),{success:!1,stdout:B,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(Z){return b0.warn("[AcpTerminal] ACP terminal failed, using fallback:",Z),this.fallback.execute($,W)}}isAvailable(){return!0}}class b{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new b}static initializeSession($,W,Z,Y){let J=Z?.fs?new P2($,W,Z.fs):new i0;if(Z?.fs)b0.debug(`[AcpServiceContext:${W}] Using ACP file system service`);let X=new IZ($,W);b0.debug(`[AcpServiceContext:${W}] Using ACP terminal service`),b.sessions.set(W,{fileSystemService:J,terminalService:X,connection:$,clientCapabilities:Z||null,cwd:Y}),b.currentSessionId=W,C1(J),b0.debug(`[AcpServiceContext:${W}] Initialized with capabilities:`,{fs:!!Z?.fs,readTextFile:Z?.fs?.readTextFile,writeTextFile:Z?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(b.sessions.delete($),b.currentSessionId===$){let W=Array.from(b.sessions.keys());if(b.currentSessionId=W[0]||null,!b.currentSessionId)SZ();else{let Z=b.sessions.get(b.currentSessionId);if(Z)C1(Z.fileSystemService)}}b0.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return b.sessions.get($)||null}static setCurrentSession($){if(b.sessions.has($)){b.currentSessionId=$;let W=b.sessions.get($);if(W)C1(W.fileSystemService)}}static getCurrentSessionId(){return b.currentSessionId}initialize($,W,Z,Y){b.initializeSession($,W,Z,Y||D())}reset(){if(b.currentSessionId)b.destroySession(b.currentSessionId)}isAcpMode(){return b.currentSessionId!==null}getFileSystemService(){if(b.currentSessionId){let $=b.sessions.get(b.currentSessionId);if($)return $.fileSystemService}return new i0}getTerminalService(){if(b.currentSessionId){let $=b.sessions.get(b.currentSessionId);if($)return $.terminalService}return new f2}getConnection(){if(b.currentSessionId){let $=b.sessions.get(b.currentSessionId);if($)return $.connection}return null}getSessionId(){return b.currentSessionId}getClientCapabilities(){if(b.currentSessionId){let $=b.sessions.get(b.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,W,Z,Y,J){let X=b.currentSessionId;if(!X)return;let V=b.sessions.get(X);if(!V)return;try{await V.connection.sessionUpdate({sessionId:X,update:{sessionUpdate:"tool_call",toolCallId:$,status:W,title:Z,content:Y||[],kind:J||"other"}})}catch(H){b0.warn("[AcpServiceContext] Failed to send tool update:",H)}}}function hZ(){return b.getInstance().getTerminalService()}function r0(){return b.getInstance().isAcpMode()}import{isAbsolute as uZ}from"path";import{z as a}from"zod";var I={filePath:($)=>a.string().min(1,"File path is required").refine((W)=>uZ(W),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>a.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,W=300000,Z=30000)=>a.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(W,`Cannot exceed ${W}ms`).default(Z).describe(`Timeout in milliseconds (default ${Z}ms)`),pattern:($)=>a.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>a.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>a.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>a.number().int("Line count must be an integer").min($?.min??1,`Line count cannot be less than ${$?.min??1}`).max($?.max??1e4,`Line count cannot exceed ${$?.max??1e4}`).describe($?.description||"Limit on lines to read"),workingDirectory:()=>a.string().min(1,"Working directory is required").refine(($)=>uZ($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>a.record(a.string(),a.string()).describe("Environment variables (key-value)").optional(),outputMode:($,W)=>{let Z=a.enum($);return W?Z.default(W):Z},flag:($)=>a.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>a.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>a.number().int("Port must be an integer").min(1,"Port cannot be less than 1").max(65535,"Port cannot exceed 65535").describe("Port number"),command:($)=>a.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>a.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>a.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>a.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as S2 from"diff";function pZ($,W,Z=4){if($===W)return null;let Y=S2.createPatch("file",$,W,"","",{context:Z}),J=Y.split(`
342
+ [... and ${W.length-Z} more files matched]`:"";return{type:"file",path:$,content:H+K,metadata:{lines:X.reduce((B,U)=>B+U.lines,0),truncated:W.length>Z||X.some((B)=>B.truncated)}}}clearExpiredCache(){let $=Date.now(),W=0;for(let[Z,Y]of this.fileCache.entries())if($-Y.timestamp>60000)this.fileCache.delete(Z),W++;if(W>0)R0.debug(`Cleared ${W} expired cache entries`)}clearCache(){this.fileCache.clear(),R0.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import*as R8 from"os";import*as O8 from"path";import{basename as H9,extname as B9}from"path";import{z as y1}from"zod";import*as O0 from"fs/promises";class i0{async readTextFile($){return O0.readFile($,"utf-8")}async writeTextFile($,W){await O0.writeFile($,W,"utf-8")}async exists($){try{return await O0.access($),!0}catch{return!1}}async readBinaryFile($){return O0.readFile($)}async stat($){try{let W=await O0.stat($);return{size:W.size,isDirectory:W.isDirectory(),isFile:W.isFile(),mtime:W.mtime}}catch{return null}}async mkdir($,W){await O0.mkdir($,{recursive:W?.recursive??!1,mode:W?.mode??493})}}var y2=new i0;function f$(){return y2}function C1($){y2=$}function SZ(){y2=new i0}var Q0=f("Agent");class f2{connection;sessionId;capabilities;fallback;constructor($,W,Z,Y=new i0){this.connection=$;this.sessionId=W;this.capabilities=Z;this.fallback=Y}async readTextFile($){if(!this.capabilities.readTextFile)return Q0.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return Q0.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(W){return Q0.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${W}`),this.fallback.readTextFile($)}}async writeTextFile($,W){if(!this.capabilities.writeTextFile)return Q0.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,W);try{Q0.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:W,sessionId:this.sessionId})}catch(Z){return Q0.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${Z}`),this.fallback.writeTextFile($,W)}}async exists($){if(!this.capabilities.readTextFile)return Q0.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),Q0.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(W){let Z=String(W).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((V)=>Z.includes(V)))return Q0.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let X=X9(Z);return Q0.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${X} error`,{error:String(W),errorType:X,filePath:$}),!0}}async readBinaryFile($){return Q0.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return Q0.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,W){return Q0.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,W)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function X9($){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 b0=f("Agent");class P2{async execute($,W){return new Promise((Z)=>{let Y=process.platform==="win32"?"cmd.exe":"/bin/bash",J=process.platform==="win32"?["/c",$]:["-c",$],{child:X,processTree:V}=C$(Y,J,{cwd:W?.cwd||D(),env:{...process.env,...W?.env},stdio:["pipe","pipe","pipe"]}),H,K=()=>{return H??=V.terminate(),H},B="",U="",Q=!1,q=W?.timeout?setTimeout(()=>{Q=!0,K()},W.timeout):null,w=null,E=()=>{if(q)clearTimeout(q);if(w&&W?.signal)W.signal.removeEventListener("abort",w),w=null};if(W?.signal){if(w=()=>{Q=!0,K()},W.signal.addEventListener("abort",w),W.signal.aborted)w()}X.stdout?.on("data",(G)=>{let F=G.toString();B+=F,W?.onOutput?.(F)}),X.stderr?.on("data",(G)=>{let F=G.toString();U+=F,W?.onOutput?.(F)}),X.on("close",async(G)=>{if(E(),Q)await K();Z({success:G===0&&!Q,stdout:B,stderr:U,exitCode:G,error:Q?"Command was terminated":void 0})}),X.on("error",(G)=>{E(),Z({success:!1,stdout:B,stderr:U,exitCode:null,error:G.message})})})}isAvailable(){return!0}}class IZ{connection;sessionId;fallback;constructor($,W,Z=new P2){this.connection=$;this.sessionId=W;this.fallback=Z}async execute($,W){try{b0.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let Z=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:W?.cwd,env:W?.env?Object.entries(W.env).map(([B,U])=>({name:B,value:U})):void 0}),Y=0,J=null;if(W?.onOutput)J=setInterval(async()=>{try{let U=(await Z.currentOutput()).output||"";if(U.length>Y){let Q=U.slice(Y);Y=U.length,W.onOutput?.(Q)}}catch{}},100);let X=(B=!1)=>{if(J)clearInterval(J),J=null;(B?Z.kill().then(()=>b0.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>Z.release()).catch(()=>{}):Z.release().catch(()=>{})).catch(()=>{})},V=[];if(V.push(Z.waitForExit().then((B)=>({type:"completed",exitCode:B.exitCode??null}))),W?.timeout)V.push(new Promise((B)=>{setTimeout(()=>B({type:"timeout"}),W.timeout)}));if(W?.signal)V.push(new Promise((B)=>{if(W.signal.aborted)B({type:"aborted"});else W.signal.addEventListener("abort",()=>B({type:"aborted"}),{once:!0})}));let H=await Promise.race(V),K="";try{if(K=(await Z.currentOutput()).output||"",W?.onOutput&&K.length>Y)W.onOutput(K.slice(Y))}catch{}switch(H.type){case"completed":return X(!1),{success:H.exitCode===0,stdout:K,stderr:"",exitCode:H.exitCode};case"timeout":return b0.debug(`[AcpTerminal] Command timed out, killing: ${$}`),X(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return b0.debug(`[AcpTerminal] Command aborted, killing: ${$}`),X(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(Z){return b0.warn("[AcpTerminal] ACP terminal failed, using fallback:",Z),this.fallback.execute($,W)}}isAvailable(){return!0}}class M{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new M}static initializeSession($,W,Z,Y){let J=Z?.fs?new f2($,W,Z.fs):new i0;if(Z?.fs)b0.debug(`[AcpServiceContext:${W}] Using ACP file system service`);let X=new IZ($,W);b0.debug(`[AcpServiceContext:${W}] Using ACP terminal service`),M.sessions.set(W,{fileSystemService:J,terminalService:X,connection:$,clientCapabilities:Z||null,cwd:Y}),M.currentSessionId=W,C1(J),b0.debug(`[AcpServiceContext:${W}] Initialized with capabilities:`,{fs:!!Z?.fs,readTextFile:Z?.fs?.readTextFile,writeTextFile:Z?.fs?.writeTextFile,cwd:Y})}static destroySession($){if(M.sessions.delete($),M.currentSessionId===$){let W=Array.from(M.sessions.keys());if(M.currentSessionId=W[0]||null,!M.currentSessionId)SZ();else{let Z=M.sessions.get(M.currentSessionId);if(Z)C1(Z.fileSystemService)}}b0.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return M.sessions.get($)||null}static setCurrentSession($){if(M.sessions.has($)){M.currentSessionId=$;let W=M.sessions.get($);if(W)C1(W.fileSystemService)}}static getCurrentSessionId(){return M.currentSessionId}initialize($,W,Z,Y){M.initializeSession($,W,Z,Y||D())}reset(){if(M.currentSessionId)M.destroySession(M.currentSessionId)}isAcpMode(){return M.currentSessionId!==null}getFileSystemService(){if(M.currentSessionId){let $=M.sessions.get(M.currentSessionId);if($)return $.fileSystemService}return new i0}getTerminalService(){if(M.currentSessionId){let $=M.sessions.get(M.currentSessionId);if($)return $.terminalService}return new P2}getConnection(){if(M.currentSessionId){let $=M.sessions.get(M.currentSessionId);if($)return $.connection}return null}getSessionId(){return M.currentSessionId}getClientCapabilities(){if(M.currentSessionId){let $=M.sessions.get(M.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,W,Z,Y,J){let X=M.currentSessionId;if(!X)return;let V=M.sessions.get(X);if(!V)return;try{await V.connection.sessionUpdate({sessionId:X,update:{sessionUpdate:"tool_call",toolCallId:$,status:W,title:Z,content:Y||[],kind:J||"other"}})}catch(H){b0.warn("[AcpServiceContext] Failed to send tool update:",H)}}}function hZ(){return M.getInstance().getTerminalService()}function r0(){return M.getInstance().isAcpMode()}import{isAbsolute as uZ}from"path";import{z as a}from"zod";var I={filePath:($)=>a.string().min(1,"File path is required").refine((W)=>uZ(W),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>a.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,W=300000,Z=30000)=>a.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(W,`Cannot exceed ${W}ms`).default(Z).describe(`Timeout in milliseconds (default ${Z}ms)`),pattern:($)=>a.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>a.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>a.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>a.number().int("Line count must be an integer").min($?.min??1,`Line count cannot be less than ${$?.min??1}`).max($?.max??1e4,`Line count cannot exceed ${$?.max??1e4}`).describe($?.description||"Limit on lines to read"),workingDirectory:()=>a.string().min(1,"Working directory is required").refine(($)=>uZ($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>a.record(a.string(),a.string()).describe("Environment variables (key-value)").optional(),outputMode:($,W)=>{let Z=a.enum($);return W?Z.default(W):Z},flag:($)=>a.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>a.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>a.number().int("Port must be an integer").min(1,"Port cannot be less than 1").max(65535,"Port cannot exceed 65535").describe("Port number"),command:($)=>a.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>a.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>a.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>a.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as S2 from"diff";function pZ($,W,Z=4){if($===W)return null;let Y=S2.createPatch("file",$,W,"","",{context:Z}),J=Y.split(`
343
343
  `),X=1;for(let V of J){let H=V.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(H){X=parseInt(H[1],10);break}}return`
344
344
  <<<DIFF>>>
345
345
  ${JSON.stringify({patch:Y,startLine:Math.max(1,X-Z),matchLine:X})}
346
346
  <<</DIFF>>>
347
347
  `}function dZ($,W,Z,Y,J=4){let X=$.indexOf(Z);if(X===-1)return null;let H=$.substring(0,X).split(`
348
- `).length-1,B=$.split(`
349
- `),K=W.split(`
350
- `),Q=Z.split(`
351
- `),U=Y.split(`
352
- `),q=Math.max(0,H-J),w=Math.min(B.length,H+Q.length+J),E=Math.min(K.length,H+U.length+J),G=B.slice(q,w).join(`
353
- `),F=K.slice(q,E).join(`
354
- `),R=S2.createPatch("file",G,F,"","",{context:J});return`
348
+ `).length-1,K=$.split(`
349
+ `),B=W.split(`
350
+ `),U=Z.split(`
351
+ `),Q=Y.split(`
352
+ `),q=Math.max(0,H-J),w=Math.min(K.length,H+U.length+J),E=Math.min(B.length,H+Q.length+J),G=K.slice(q,w).join(`
353
+ `),F=B.slice(q,E).join(`
354
+ `),z=S2.createPatch("file",G,F,"","",{context:J});return`
355
355
  <<<DIFF>>>
356
- ${JSON.stringify({patch:R,startLine:q+1,matchLine:H+1})}
356
+ ${JSON.stringify({patch:z,startLine:q+1,matchLine:H+1})}
357
357
  <<</DIFF>>>
358
358
  `}function gZ($){return $.replace(/\\+(n|t|r|'|"|`|\\|\n)/g,(W,Z)=>{switch(Z){case"n":return`
359
359
  `;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
360
360
  `:return`
361
361
  `;default:return W}})}function mZ($,W){let Z=W.split(`
362
- `);if(Z.length===1)return null;let J=Z[0].match(/^(\s+)/);if(!J)return null;let X=J[1],H=Z.map((K)=>{if(K.startsWith(X))return K.slice(X.length);return K}).join(`
363
- `),B=$.split(`
364
- `);for(let K=0;K<=B.length-Z.length;K++){let Q=B[K].match(/^(\s+)/),U=Q?Q[1]:"",q=B.slice(K,K+Z.length);if(q.map((G)=>{if(G.startsWith(U))return G.slice(U.length);return G}).join(`
362
+ `);if(Z.length===1)return null;let J=Z[0].match(/^(\s+)/);if(!J)return null;let X=J[1],H=Z.map((B)=>{if(B.startsWith(X))return B.slice(X.length);return B}).join(`
363
+ `),K=$.split(`
364
+ `);for(let B=0;B<=K.length-Z.length;B++){let U=K[B].match(/^(\s+)/),Q=U?U[1]:"",q=K.slice(B,B+Z.length);if(q.map((G)=>{if(G.startsWith(Q))return G.slice(Q.length);return G}).join(`
365
365
  `)===H)return q.join(`
366
366
  `)}return null}function cZ($,W){let Z=W.split(`
367
367
  `),Y=$.split(`
368
- `),J=Z.map((X)=>X.trimEnd());for(let X=0;X<=Y.length-Z.length;X++){let V=Y.slice(X,X+Z.length),H=V.map((B)=>B.trimEnd());if(H.length===J.length&&H.every((B,K)=>B===J[K]))return V.join(`
368
+ `),J=Z.map((X)=>X.trimEnd());for(let X=0;X<=Y.length-Z.length;X++){let V=Y.slice(X,X+Z.length),H=V.map((K)=>K.trimEnd());if(H.length===J.length&&H.every((K,B)=>K===J[B]))return V.join(`
369
369
  `)}return null}function lZ($,W){let Z=(V)=>V.split(`
370
370
  `).map((H)=>H.replace(/\s+/g," ").trim()).join(`
371
371
  `),Y=Z(W),J=W.split(`
@@ -374,38 +374,38 @@ ${JSON.stringify({patch:R,startLine:q+1,matchLine:H+1})}
374
374
  `))===Y)return H.join(`
375
375
  `)}return null}function iZ($,W){let Z=W.split(`
376
376
  `);if(Z.length<3)return null;let Y=$.split(`
377
- `),J=Z[0].trim(),X=Z[Z.length-1].trim(),V=Z.length;for(let H=0;H<=Y.length-V;H++){let B=Y[H].trim(),K=Y[H+V-1].trim();if(B!==J)continue;if(K!==X)continue;let Q=Y.slice(H,H+V),U=Q.slice(1,-1).join(`
377
+ `),J=Z[0].trim(),X=Z[Z.length-1].trim(),V=Z.length;for(let H=0;H<=Y.length-V;H++){let K=Y[H].trim(),B=Y[H+V-1].trim();if(K!==J)continue;if(B!==X)continue;let U=Y.slice(H,H+V),Q=U.slice(1,-1).join(`
378
378
  `),q=Z.slice(1,-1).join(`
379
- `);if(V9(U,q)>=0.85)return Q.join(`
379
+ `);if(V9(Q,q)>=0.85)return U.join(`
380
380
  `)}return null}function V9($,W){let Z=$.split(`
381
381
  `),Y=W.split(`
382
- `);if(Z.length!==Y.length)return 0;if(Z.length===0)return 1;let J=0;for(let X=0;X<Z.length;X++)if(Z[X].trim()===Y[X].trim())J++;return J/Z.length}import*as rZ from"node:crypto";import{promises as M0}from"node:fs";import*as w$ from"node:path";class $1{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let W=V0();this.snapshotDir=w$.join(W,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await M0.mkdir(this.snapshotDir,{recursive:!0,mode:493}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,W){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await M0.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let Z=this.trackedFileBackups.get($),Y=Z?Z.version+1:1,J=this.generateFileHash($,Y),X=w$.join(this.snapshotDir,`${J}@v${Y}`);try{let V=await M0.readFile($,{encoding:"utf-8"});await M0.writeFile(X,V,{encoding:"utf-8"});let H={backupFileName:J,version:Y,backupTime:new Date};return this.trackedFileBackups.set($,H),this.snapshots.push({messageId:W,backupFileName:J,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${J}@v${Y}`),await this.cleanupOldSnapshots($),H}catch(V){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,V),V}}async restoreSnapshot($,W){let Z=this.snapshots.slice().reverse().find((X)=>X.messageId===W&&X.filePath===$);if(!Z)throw Error(`未找到快照: messageId=${W}, filePath=${$}`);let Y=this.trackedFileBackups.get($);if(!Y)throw Error(`未找到文件追踪信息: ${$}`);let J=w$.join(this.snapshotDir,`${Z.backupFileName}@v${Y.version}`);try{let X=await M0.readFile(J,{encoding:"utf-8"});await M0.writeFile($,X,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${Z.backupFileName}@v${Y.version}`)}catch(X){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,X),X}}async listSnapshots($){return this.snapshots.filter((W)=>W.filePath===$)}async cleanupOldSnapshots($){let W=this.snapshots.filter((J)=>J.filePath===$);if(W.length<=this.maxSnapshots)return;let Y=W.sort((J,X)=>J.timestamp.getTime()-X.timestamp.getTime()).slice(0,W.length-this.maxSnapshots);for(let J of Y){let X=this.trackedFileBackups.get(J.filePath);if(!X)continue;let V=w$.join(this.snapshotDir,`${J.backupFileName}@v${X.version}`);try{await M0.unlink(V),console.log(`[SnapshotManager] 删除旧快照: ${V}`)}catch(B){console.warn(`[SnapshotManager] 删除快照失败: ${V}`,B)}let H=this.snapshots.indexOf(J);if(H>-1)this.snapshots.splice(H,1)}}async cleanup($=0){try{let W=await M0.readdir(this.snapshotDir);if(W.length<=$)return;let Z=await Promise.all(W.map(async(J)=>{let X=w$.join(this.snapshotDir,J),V=await M0.stat(X);return{file:J,mtime:V.mtime.getTime()}}));Z.sort((J,X)=>X.mtime-J.mtime);let Y=Z.slice($);for(let{file:J}of Y){let X=w$.join(this.snapshotDir,J);await M0.unlink(X),console.log(`[SnapshotManager] 清理快照: ${X}`)}}catch(W){console.warn("[SnapshotManager] 清理快照失败:",W)}}generateFileHash($,W){let Z=rZ.createHash("md5");return Z.update(`${$}:${W}`),Z.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var I2=j({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:y1.object({file_path:I.filePath({description:"Absolute path of the file to edit"}),old_string:y1.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:y1.string().describe("Replacement string (can be empty)"),replace_all:y1.boolean().default(!1).describe("Replace all matches (default: first only)")}),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($,W){let{file_path:Z,old_string:Y,new_string:J,replace_all:X}=$,{updateOutput:V,sessionId:H,messageId:B}=W,K=W.signal??new AbortController().signal;try{V?.("Starting to read file...");let Q=P$(),U=r0(),q;try{if(U)V?.("通过 IDE 读取文件...");q=await Q.readTextFile(Z)}catch(k){let M=k;if(M.code==="ENOENT"||M.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${Z}`,error:{type:"execution_error",message:"文件不存在"}};throw k}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(H){let k=n0.getInstance();if(!k.hasFileBeenRead(Z,H))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 k.checkExternalModification(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.
382
+ `);if(Z.length!==Y.length)return 0;if(Z.length===0)return 1;let J=0;for(let X=0;X<Z.length;X++)if(Z[X].trim()===Y[X].trim())J++;return J/Z.length}import*as rZ from"node:crypto";import{promises as M0}from"node:fs";import*as w$ from"node:path";class $1{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let W=V0();this.snapshotDir=w$.join(W,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await M0.mkdir(this.snapshotDir,{recursive:!0,mode:493}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,W){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await M0.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let Z=this.trackedFileBackups.get($),Y=Z?Z.version+1:1,J=this.generateFileHash($,Y),X=w$.join(this.snapshotDir,`${J}@v${Y}`);try{let V=await M0.readFile($,{encoding:"utf-8"});await M0.writeFile(X,V,{encoding:"utf-8"});let H={backupFileName:J,version:Y,backupTime:new Date};return this.trackedFileBackups.set($,H),this.snapshots.push({messageId:W,backupFileName:J,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${J}@v${Y}`),await this.cleanupOldSnapshots($),H}catch(V){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,V),V}}async restoreSnapshot($,W){let Z=this.snapshots.slice().reverse().find((X)=>X.messageId===W&&X.filePath===$);if(!Z)throw Error(`未找到快照: messageId=${W}, filePath=${$}`);let Y=this.trackedFileBackups.get($);if(!Y)throw Error(`未找到文件追踪信息: ${$}`);let J=w$.join(this.snapshotDir,`${Z.backupFileName}@v${Y.version}`);try{let X=await M0.readFile(J,{encoding:"utf-8"});await M0.writeFile($,X,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${Z.backupFileName}@v${Y.version}`)}catch(X){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,X),X}}async listSnapshots($){return this.snapshots.filter((W)=>W.filePath===$)}async cleanupOldSnapshots($){let W=this.snapshots.filter((J)=>J.filePath===$);if(W.length<=this.maxSnapshots)return;let Y=W.sort((J,X)=>J.timestamp.getTime()-X.timestamp.getTime()).slice(0,W.length-this.maxSnapshots);for(let J of Y){let X=this.trackedFileBackups.get(J.filePath);if(!X)continue;let V=w$.join(this.snapshotDir,`${J.backupFileName}@v${X.version}`);try{await M0.unlink(V),console.log(`[SnapshotManager] 删除旧快照: ${V}`)}catch(K){console.warn(`[SnapshotManager] 删除快照失败: ${V}`,K)}let H=this.snapshots.indexOf(J);if(H>-1)this.snapshots.splice(H,1)}}async cleanup($=0){try{let W=await M0.readdir(this.snapshotDir);if(W.length<=$)return;let Z=await Promise.all(W.map(async(J)=>{let X=w$.join(this.snapshotDir,J),V=await M0.stat(X);return{file:J,mtime:V.mtime.getTime()}}));Z.sort((J,X)=>X.mtime-J.mtime);let Y=Z.slice($);for(let{file:J}of Y){let X=w$.join(this.snapshotDir,J);await M0.unlink(X),console.log(`[SnapshotManager] 清理快照: ${X}`)}}catch(W){console.warn("[SnapshotManager] 清理快照失败:",W)}}generateFileHash($,W){let Z=rZ.createHash("md5");return Z.update(`${$}:${W}`),Z.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var I2=N({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:y1.object({file_path:I.filePath({description:"Absolute path of the file to edit"}),old_string:y1.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:y1.string().describe("Replacement string (can be empty)"),replace_all:y1.boolean().default(!1).describe("Replace all matches (default: first only)")}),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($,W){let{file_path:Z,old_string:Y,new_string:J,replace_all:X}=$,{updateOutput:V,sessionId:H,messageId:K}=W,B=W.signal??new AbortController().signal;try{V?.("Starting to read file...");let U=f$(),Q=r0(),q;try{if(Q)V?.("通过 IDE 读取文件...");q=await U.readTextFile(Z)}catch(L){let b=L;if(b.code==="ENOENT"||b.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${Z}`,error:{type:"execution_error",message:"文件不存在"}};throw L}if(typeof B.throwIfAborted==="function")B.throwIfAborted();if(H){let L=n0.getInstance();if(!L.hasFileBeenRead(Z,H))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 b=await L.checkExternalModification(Z);if(b.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.
383
383
 
384
- Details: ${M.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:M.message}}}}if(H&&B)try{let k=new $1({sessionId:H});await k.initialize(),await k.createSnapshot(Z,B)}catch(k){console.warn("[EditTool] 创建快照失败:",k)}if(Y===J)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let w=K9(q,Y);if(!w.matched){let k=U9(q,Y,Z);return{success:!1,llmContent:k.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:k.metadata}}}let E=w.matched;if(w.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${w.strategy}`);let G=Q9(q,E);if(G.length>1&&!X){let k=q.split(`
385
- `),M=0,y=[];for(let g=0;g<k.length;g++){let c0=k[g],UZ=M,qZ=M+c0.length;for(let k2 of G)if(k2>=UZ&&k2<qZ){let x6=Math.max(0,g-1),C6=Math.min(k.length-1,g+1),y6=k.slice(x6,C6+1).map((P6)=>P6.trim()).join(" ").slice(0,80);y.push({line:g+1,column:k2-UZ+1,context:y6})}M=qZ+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${G.length} locations (must be unique).`,"","**Matches found at:**",...y.map((g,c0)=>` ${c0+1}. Line ${g.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 ${G.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
386
- `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:y.map((g)=>({line:g.line,column:g.column})),count:G.length}}}}else V?.(`找到 ${G.length} 个匹配项,开始替换...`);let F,R;if(X)F=q.split(E).join(J),R=G.length;else{let k=q.indexOf(E);F=q.substring(0,k)+J+q.substring(k+E.length),R=1}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(U)V?.("通过 IDE 写入文件...");if(await Q.writeTextFile(Z,F),H)await n0.getInstance().recordFileEdit(Z,H,"edit");let O=await Q.stat(Z),_=dZ(q,F,E,J,4),z=H9(Z),N=R===1?`替换 1 处匹配到 ${z}`:`替换 ${R} 处匹配到 ${z}`,A={file_path:Z,matches_found:G.length,replacements_made:R,replace_all:X,old_string_length:Y.length,new_string_length:J.length,original_size:q.length,new_size:F.length,size_diff:F.length-q.length,last_modified:O?.mtime instanceof Date?O.mtime.toISOString():void 0,snapshot_created:!!(H&&B),session_id:H,message_id:B,diff_snippet:_,summary:N,kind:"edit",oldContent:q,newContent:F};return{success:!0,llmContent:_?`Edited ${Z} (${R} replacement${R>1?"s":""}):
387
- ${_}`:`Edited ${Z} (${R} replacement${R>1?"s":""})`,metadata:A}}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=B9($.file_path);return W?`**/*${W}`:"**/*"}});function nZ($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function K9($,W){if($.includes(W))return{matched:W,strategy:"exact"};let Z=cZ($,W);if(Z)return{matched:Z,strategy:"line_trim"};let Y=nZ(W),X=nZ($).indexOf(Y);if(X!==-1)return{matched:$.substring(X,X+W.length),strategy:"normalize_quotes"};let V=gZ(W);if(V!==W&&$.includes(V))return{matched:V,strategy:"unescape"};let H=lZ($,W);if(H)return{matched:H,strategy:"whitespace_normalize"};let B=mZ($,W);if(B)return{matched:B,strategy:"flexible"};let K=iZ($,W);if(K)return{matched:K,strategy:"block_anchor"};return{matched:null,strategy:"failed"}}function Q9($,W){if(W.length===0)return[];let Z=[],Y=$.indexOf(W);while(Y!==-1)Z.push(Y),Y=$.indexOf(W,Y+W.length);return Z}function U9($,W,Z){let Y=$.split(`
388
- `),J=Y.length,X=q9($,W,3),V=0,H=Math.min(20,J);if(X.length>0){let q=X[0];V=Math.max(0,q.lineNumber-10),H=Math.min(J,q.lineNumber+10)}let K=Y.slice(V,H).map((q,w)=>{return` ${(V+w+1).toString().padStart(4)}: ${q}`}).join(`
389
- `),Q=`String not found in file.
384
+ Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}if(H&&K)try{let L=new $1({sessionId:H});await L.initialize(),await L.createSnapshot(Z,K)}catch(L){console.warn("[EditTool] 创建快照失败:",L)}if(Y===J)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let w=K9(q,Y);if(!w.matched){let L=Q9(q,Y,Z);return{success:!1,llmContent:L.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:L.metadata}}}let E=w.matched;if(w.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${w.strategy}`);let G=U9(q,E);if(G.length>1&&!X){let L=q.split(`
385
+ `),b=0,y=[];for(let g=0;g<L.length;g++){let c0=L[g],QZ=b,qZ=b+c0.length;for(let k2 of G)if(k2>=QZ&&k2<qZ){let x6=Math.max(0,g-1),C6=Math.min(L.length-1,g+1),y6=L.slice(x6,C6+1).map((f6)=>f6.trim()).join(" ").slice(0,80);y.push({line:g+1,column:k2-QZ+1,context:y6})}b=qZ+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${G.length} locations (must be unique).`,"","**Matches found at:**",...y.map((g,c0)=>` ${c0+1}. Line ${g.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 ${G.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
386
+ `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:y.map((g)=>({line:g.line,column:g.column})),count:G.length}}}}else V?.(`找到 ${G.length} 个匹配项,开始替换...`);let F,z;if(X)F=q.split(E).join(J),z=G.length;else{let L=q.indexOf(E);F=q.substring(0,L)+J+q.substring(L+E.length),z=1}if(typeof B.throwIfAborted==="function")B.throwIfAborted();if(Q)V?.("通过 IDE 写入文件...");if(await U.writeTextFile(Z,F),H)await n0.getInstance().recordFileEdit(Z,H,"edit");let O=await U.stat(Z),_=dZ(q,F,E,J,4),R=H9(Z),j=z===1?`替换 1 处匹配到 ${R}`:`替换 ${z} 处匹配到 ${R}`,A={file_path:Z,matches_found:G.length,replacements_made:z,replace_all:X,old_string_length:Y.length,new_string_length:J.length,original_size:q.length,new_size:F.length,size_diff:F.length-q.length,last_modified:O?.mtime instanceof Date?O.mtime.toISOString():void 0,snapshot_created:!!(H&&K),session_id:H,message_id:K,diff_snippet:_,summary:j,kind:"edit",oldContent:q,newContent:F};return{success:!0,llmContent:_?`Edited ${Z} (${z} replacement${z>1?"s":""}):
387
+ ${_}`:`Edited ${Z} (${z} replacement${z>1?"s":""})`,metadata:A}}catch(U){let Q=U;if(Q.name==="AbortError")return{success:!1,llmContent:"File edit aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${Q.message}`,error:{type:"execution_error",message:Q.message,details:Q}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=B9($.file_path);return W?`**/*${W}`:"**/*"}});function nZ($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function K9($,W){if($.includes(W))return{matched:W,strategy:"exact"};let Z=cZ($,W);if(Z)return{matched:Z,strategy:"line_trim"};let Y=nZ(W),X=nZ($).indexOf(Y);if(X!==-1)return{matched:$.substring(X,X+W.length),strategy:"normalize_quotes"};let V=gZ(W);if(V!==W&&$.includes(V))return{matched:V,strategy:"unescape"};let H=lZ($,W);if(H)return{matched:H,strategy:"whitespace_normalize"};let K=mZ($,W);if(K)return{matched:K,strategy:"flexible"};let B=iZ($,W);if(B)return{matched:B,strategy:"block_anchor"};return{matched:null,strategy:"failed"}}function U9($,W){if(W.length===0)return[];let Z=[],Y=$.indexOf(W);while(Y!==-1)Z.push(Y),Y=$.indexOf(W,Y+W.length);return Z}function Q9($,W,Z){let Y=$.split(`
388
+ `),J=Y.length,X=q9($,W,3),V=0,H=Math.min(20,J);if(X.length>0){let q=X[0];V=Math.max(0,q.lineNumber-10),H=Math.min(J,q.lineNumber+10)}let B=Y.slice(V,H).map((q,w)=>{return` ${(V+w+1).toString().padStart(4)}: ${q}`}).join(`
389
+ `),U=`String not found in file.
390
390
 
391
391
  File: ${Z}
392
392
  Total lines: ${J}
393
393
 
394
- `,U=W.length>300?W.substring(0,300)+`
395
- ... (truncated)`:W;if(Q+=`You tried to match:
396
- ${U}
394
+ `,Q=W.length>300?W.substring(0,300)+`
395
+ ... (truncated)`:W;if(U+=`You tried to match:
396
+ ${Q}
397
397
 
398
- `,X.length>0)Q+=`File content around possible matches (lines ${V+1}-${H}):
399
- ${K}
398
+ `,X.length>0)U+=`File content around possible matches (lines ${V+1}-${H}):
399
+ ${B}
400
400
 
401
- `;else Q+=`File content preview (lines ${V+1}-${H}):
402
- ${K}
401
+ `;else U+=`File content preview (lines ${V+1}-${H}):
402
+ ${B}
403
403
 
404
- `;if(X.length>0)Q+=`Possible similar matches found:
405
- `,X.forEach((q,w)=>{let E=q.text.length>100?q.text.substring(0,100)+"...":q.text;Q+=` ${w+1}. Line ${q.lineNumber} (similarity: ${Math.round(q.similarity*100)}%)
404
+ `;if(X.length>0)U+=`Possible similar matches found:
405
+ `,X.forEach((q,w)=>{let E=q.text.length>100?q.text.substring(0,100)+"...":q.text;U+=` ${w+1}. Line ${q.lineNumber} (similarity: ${Math.round(q.similarity*100)}%)
406
406
  ${E.replace(/\n/g,"\\n")}
407
- `}),Q+=`
408
- `;return Q+=`Recovery suggestions:
407
+ `}),U+=`
408
+ `;return U+=`Recovery suggestions:
409
409
  1. Use the Read tool to verify the current file content
410
410
  2. Check for typos, whitespace differences, or quote mismatches
411
411
  3. Provide more surrounding context to make the match unique
@@ -415,22 +415,22 @@ Common issues:
415
415
  - Line breaks: Ensure \\n characters match exactly
416
416
  - Indentation: Spaces vs tabs mismatch
417
417
  - Smart quotes: " " vs " (use straight quotes)
418
- - Outdated mental model: File may have changed since you last read it`,{llmContent:Q,metadata:{searchStringLength:W.length,fuzzyMatches:X.map((q)=>({line:q.lineNumber,similarity:q.similarity,preview:q.text.substring(0,100)})),excerptRange:[V+1,H],totalLines:J}}}function q9($,W,Z=3){let Y=$.split(`
418
+ - Outdated mental model: File may have changed since you last read it`,{llmContent:U,metadata:{searchStringLength:W.length,fuzzyMatches:X.map((q)=>({line:q.lineNumber,similarity:q.similarity,preview:q.text.substring(0,100)})),excerptRange:[V+1,H],totalLines:J}}}function q9($,W,Z=3){let Y=$.split(`
419
419
  `),J=W.split(`
420
- `);if(J.length===1)return Y.map((B,K)=>({text:B,lineNumber:K+1,similarity:aZ(W.trim(),B.trim())})).filter((B)=>B.similarity>0.5).sort((B,K)=>K.similarity-B.similarity).slice(0,Z);let X=J.length,V=[];for(let H=0;H<=Y.length-X;H++){let B=Y.slice(H,H+X).join(`
421
- `),K=aZ(W,B);if(K>0.5)V.push({text:B,lineNumber:H+1,similarity:K})}return V.sort((H,B)=>B.similarity-H.similarity).slice(0,Z)}function aZ($,W){let Z=(q)=>q.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=Z($),J=Z(W);if(Y===J)return 1;let X=Y.length,V=J.length;if(X===0)return V===0?1:0;if(V===0)return 0;let H=200,B=Y.substring(0,H),K=J.substring(0,H),Q=w9(B,K),U=Math.max(B.length,K.length);return 1-Q/U}function w9($,W){let Z=$.length,Y=W.length,J=Array(Z+1).fill(null).map(()=>Array(Y+1).fill(0));for(let X=0;X<=Z;X++)J[X][0]=X;for(let X=0;X<=Y;X++)J[0][X]=X;for(let X=1;X<=Z;X++)for(let V=1;V<=Y;V++){let H=$[X-1]===W[V-1]?0:1;J[X][V]=Math.min(J[X-1][V]+1,J[X][V-1]+1,J[X-1][V-1]+H)}return J[Z][Y]}import{basename as G9,extname as oZ}from"path";import{z as E9}from"zod";var h2=j({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:E9.object({file_path:I.filePath({description:"File path to read (must be absolute)"}),offset:I.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:I.lineLimit({description:"Number of lines to read (text files only)"}).optional(),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($,W){let{file_path:Z,offset:Y,limit:J,encoding:X="utf8"}=$,{updateOutput:V,sessionId:H}=W,B=W.signal??new AbortController().signal;try{V?.("Starting file read...");let K=P$(),Q=r0();try{if(!await K.exists(Z))throw Error("File not found")}catch(z){return{success:!1,llmContent:`File not found: ${Z}`,error:{type:"execution_error",message:`File not found: ${Z}`}}}if(typeof B.throwIfAborted==="function")B.throwIfAborted();if(H)await n0.getInstance().recordFileRead(Z,H);let U=await K.stat(Z);if(U?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${Z}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let q=oZ(Z).toLowerCase(),w=F9(q),E=z9(q),G,F={file_path:Z,file_size:U?.size,file_type:q,last_modified:U?.mtime instanceof Date?U.mtime.toISOString():void 0,encoding:X,acp_mode:Q};if(E&&X==="utf8"){if(Q)V?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),F.acp_fallback=!0;else V?.("检测到二进制文件,使用 base64 编码...");G=(await K.readBinaryFile(Z)).toString("base64"),F.encoding="base64",F.is_binary=!0}else if(w){if(Q)V?.("通过 IDE 读取文件...");G=await K.readTextFile(Z)}else{if(Q)F.acp_fallback=!0;let z=await K.readBinaryFile(Z);if(X==="base64")G=z.toString("base64");else if(X==="binary")G=z.toString("binary");else G=z.toString("utf8")}if(typeof B.throwIfAborted==="function")B.throwIfAborted();if((Y!==void 0||J!==void 0)&&X==="utf8"&&w){let z=G.split(`
422
- `),N=Y||0,A=J!==void 0?N+J:z.length,k=z.slice(N,A);G=k.map((M,y)=>{let x=N+y+1,g=M.length>2000?`${M.substring(0,2000)}...`:M;return`${x.toString().padStart(6)}|${g}`}).join(`
423
- `),F.lines_read=k.length,F.total_lines=z.length,F.start_line=N+1,F.end_line=Math.min(A,z.length)}let R=G9(Z),O=F.lines_read||F.total_lines,_=O?`读取 ${O} 行从 ${R}`:`读取 ${R}`;return F.summary=_,{success:!0,llmContent:G,metadata:F}}catch(K){let Q=K;if(Q.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${Q.message}`,error:{type:"execution_error",message:Q.message,details:Q}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=oZ($.file_path);return W?`**/*${W}`:"**/*"}});function F9($){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 z9($){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 R9}from"fs";import{basename as O9,dirname as D9,extname as _9}from"path";import{z as u2}from"zod";var p2=j({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:u2.object({file_path:I.filePath({description:"Absolute file path to write"}),content:u2.string().describe("Content to write"),encoding:I.encoding(),create_directories:u2.boolean().default(!0).describe("Automatically create missing parent directories")}),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($,W){let{file_path:Z,content:Y,encoding:J,create_directories:X}=$,{updateOutput:V,sessionId:H,messageId:B}=W,K=W.signal??new AbortController().signal;try{V?.("开始写入文件...");let Q=P$(),U=r0();if(X){let z=D9(Z);try{await Q.mkdir(z,{recursive:!0,mode:493})}catch(N){if(N.code!=="EEXIST")throw N}}if(typeof K.throwIfAborted==="function")K.throwIfAborted();let q=!1,w=null;try{if(q=await Q.exists(Z),q&&J==="utf8")try{w=await Q.readTextFile(Z)}catch(z){console.warn("[WriteTool] 读取旧文件内容失败:",z)}}catch{}if(q&&H){let z=n0.getInstance();if(!z.hasFileBeenRead(Z,H))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 N=await z.checkExternalModification(Z);if(N.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.
424
-
425
- Details: ${N.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:N.message}}}}let E=!1;if(q&&H&&B)try{let z=new $1({sessionId:H});await z.initialize(),await z.createSnapshot(Z,B),E=!0}catch(z){console.warn("[WriteTool] 创建快照失败:",z)}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(J==="utf8"){if(U)V?.("通过 IDE 写入文件...");await Q.writeTextFile(Z,Y)}else{if(U)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 z;if(J==="base64")z=Buffer.from(Y,"base64");else if(J==="binary")z=Buffer.from(Y,"binary");else z=Buffer.from(Y,"utf8");await R9.writeFile(Z,z)}if(H)await n0.getInstance().recordFileEdit(Z,H,"write");if(typeof K.throwIfAborted==="function")K.throwIfAborted();let G=await Q.stat(Z),F=J==="utf8"?Y.split(`
426
- `).length:0,R=O9(Z),O=null;if(w&&J==="utf8"&&w!==Y){if(w.length<1048576&&Y.length<1048576)O=pZ(w,Y,4)}let _={file_path:Z,content_size:Y.length,file_size:G?.size,encoding:J,created_directories:X,snapshot_created:E,session_id:H,message_id:B,last_modified:G?.mtime instanceof Date?G.mtime.toISOString():void 0,has_diff:!!O,summary:J==="utf8"?`写入 ${F} 行到 ${R}`:`写入 ${G?.size?j9(G.size):"unknown"} 到 ${R}`,kind:"edit",oldContent:w||"",newContent:J==="utf8"?Y:void 0};return{success:!0,llmContent:w?`Wrote ${Z} (${Y.length} chars, updated existing file)`:`Created ${Z} (${Y.length} chars, new file)`,metadata:_}}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=_9($.file_path);return W?`**/*${W}`:"**/*"}});function j9($){let W=["B","KB","MB","GB"],Z=$,Y=0;while(Z>=1024&&Y<W.length-1)Z/=1024,Y++;return`${Z.toFixed(1)}${W[Y]}`}import{z as W1}from"zod";var eZ=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),A9=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),N9=W1.object({operation:W1.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:W1.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:W1.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:W1.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function sZ($){let W={...$};if(Array.isArray(W.models))W.models=W.models.map((Z)=>{let Y={...Z};if(typeof Y.apiKey==="string"&&Y.apiKey){let J=Y.apiKey;Y.apiKey=J.length>8?`${J.slice(0,4)}...${J.slice(-4)}`:"****"}return Y});return W}function tZ($,W){let Z=W.split("."),Y=$;for(let J of Z){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[J]}return Y}function T9($){let W=["可配置项列表(白名单):",""];for(let Z of eZ){let Y=$[Z],J=Y===void 0?"(未设置)":JSON.stringify(Y,null,2),X=J.length>200?`${J.slice(0,197)}...`:J;W.push(`- ${Z}: ${X}`)}return W.join(`
427
- `)}var d2=j({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:N9,description:{short:"Read, update, or list Blade configuration",long:"Manage Blade configuration: get reads a config value, set updates a whitelisted config field (with persistence), list enumerates all settable keys and their current values.",usageNotes:['Use operation="get" with key="*" to dump all config','Use operation="get" with a dotted key like "hooks.PreToolUse"','Use operation="set" with key and value to update config','Use operation="list" to see all settable keys',"The scope option controls persistence: local/project/global","models and apiKey fields cannot be modified for security"],examples:[{description:"Get all configuration",params:{operation:"get",key:"*"}},{description:"Get a specific config value",params:{operation:"get",key:"hooks"}},{description:"Set temperature",params:{operation:"set",key:"temperature",value:0.7,scope:"global"}},{description:"List all settable keys",params:{operation:"list"}}]},async execute($,W){let{operation:Z,key:Y,value:J,scope:X}=$,V=Y0();if(!V)return{success:!1,llmContent:"Config not initialized. Please wait for Blade to finish starting.",error:{message:"Config not initialized",type:"execution_error"},metadata:{summary:"配置未初始化"}};switch(Z){case"get":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for get operation. Use key="*" to get all config.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(Y==="*"){let Q=sZ(V);return{success:!0,llmContent:JSON.stringify(Q,null,2),metadata:{summary:"获取全部配置"}}}let H=V;if(Y.split(".")[0]==="models"){let Q=sZ(H),U=tZ(Q,Y);return{success:!0,llmContent:JSON.stringify(U,null,2),metadata:{summary:`获取配置: ${Y}`}}}let K=tZ(H,Y);if(K===void 0)return{success:!0,llmContent:`Config key "${Y}" is not set or does not exist.`,metadata:{summary:`配置项 ${Y} 不存在`}};return{success:!0,llmContent:JSON.stringify(K,null,2),metadata:{summary:`获取配置: ${Y}`}}}case"set":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(J===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let H=Y.split(".")[0];if(H==="models"||H==="currentModelId")return{success:!1,llmContent:'Refused: "models" and "currentModelId" cannot be modified via ConfigTool to protect API keys. Use the /model slash command instead.',error:{message:"Forbidden key: models",type:"permission_denied"},metadata:{summary:"拒绝修改 models"}};if(A9.has(H))return{success:!1,llmContent:`Refused: "${H}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${H}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${H}`}};if(!eZ.has(H))return{success:!1,llmContent:`Key "${H}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${H}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${H}`}};let B;if(Y.includes(".")){let K=Y.split(".");if(B={[K[0]]:J},K.length===2){let Q=V[K[0]];if(typeof Q==="object"&&Q!==null)B={[K[0]]:{...Q,[K[1]]:J}};else B={[K[0]]:{[K[1]]:J}}}}else B={[Y]:J};try{await a0().updateConfig(B,X?{scope:X}:{});let K=JSON.stringify(J).length>200?`${JSON.stringify(J).slice(0,197)}...`:JSON.stringify(J);return{success:!0,llmContent:`Config updated: ${Y} = ${K}`+(X?` (scope: ${X})`:""),metadata:{summary:`配置已更新: ${Y}`}}}catch(K){let Q=K instanceof Error?K.message:String(K);return{success:!1,llmContent:`Failed to update config: ${Q}`,error:{message:Q,type:"execution_error"},metadata:{summary:`配置更新失败: ${Y}`}}}}case"list":return{success:!0,llmContent:T9(V),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${Z}`,error:{message:`Unknown operation: ${Z}`,type:"validation_error"},metadata:{summary:`未知操作: ${Z}`}}}}});import{z as $5}from"zod";var g2=j({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:$5.object({topic:$5.string().describe('Topic name to read (e.g., "debugging", "patterns", "MEMORY" for the index, "_list" to list all topics). Without .md extension.')}),description:{short:"Read a topic file from project auto memory",long:"Reads a topic file from the project's persistent auto memory directory. Use this to retrieve detailed notes that were saved in previous sessions. The MEMORY.md index is automatically loaded at session start, but topic files need to be read on demand.",usageNotes:['Use topic="MEMORY" to read the full MEMORY.md index','Use topic="_list" to list all available memory files',"Topic files are stored at ~/.blade/projects/{project}/memory/{topic}.md"],examples:[{description:"Read debugging notes",params:{topic:"debugging"}},{description:"Read the full MEMORY.md index",params:{topic:"MEMORY"}},{description:"List all memory topics",params:{topic:"_list"}}]},async execute($,W){let{topic:Z}=$,Y=W.workspaceRoot||D(),J=new l0(Y);if(Z==="_list"){let V=await J.listTopics();if(V.length===0)return{success:!0,llmContent:"No memory files found. Use MemoryWrite to save project knowledge.",metadata:{summary:"无记忆文件"}};return{success:!0,llmContent:`Memory files:
428
- ${V.map((K)=>`- ${K.name}.md (${K.size} bytes, updated ${K.lastModified.toISOString()})`).join(`
429
- `)}`,metadata:{summary:`列出 ${V.length} 个记忆文件`}}}let X=await J.readTopic(Z);if(X===null)return{success:!0,llmContent:`Memory topic "${Z}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${Z}`}};return{success:!0,llmContent:X,metadata:{summary:`读取记忆: ${Z}`}}}});import{z as P1}from"zod";var L9=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],m2=j({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:P1.object({topic:P1.string().describe('Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'),content:P1.string().describe("Content to write to the memory file"),mode:P1.enum(["overwrite","append"]).default("append").describe('Write mode: "append" adds to existing content, "overwrite" replaces it')}),description:{short:"Save project knowledge to persistent auto memory",long:"Saves notes and learnings to the project's persistent auto memory. Use this to record useful project knowledge that should survive across sessions — build commands, code patterns, debugging insights, architecture notes, and user preferences.",usageNotes:['Use topic="MEMORY" to update the index file (keep it concise, under 200 lines)','Use descriptive topic names for detailed notes (e.g., "debugging", "api-conventions")','Default mode is "append" — adds to existing content','Use "overwrite" mode to replace the entire topic file',"Do NOT save sensitive data (passwords, tokens, API keys)"],examples:[{description:"Save a debugging insight",params:{topic:"debugging",content:"## Redis connection timeout\nThe test suite requires a local Redis instance. Start with `docker compose up redis`."}},{description:"Update the memory index",params:{topic:"MEMORY",content:"# Project Memory\n\n- Build: `bun run build`\n- Test: `bun run test`\n- See debugging.md for common issues",mode:"overwrite"}}]},async execute($,W){let{topic:Z,content:Y,mode:J}=$,X=W.workspaceRoot||D();for(let K of L9)if(K.test(Y)){let Q=`Refused: content appears to contain sensitive data (matched ${K}). Do not save passwords, tokens, or API keys to memory.`;return{success:!1,llmContent:Q,error:{message:Q,type:"validation_error"},metadata:{summary:"拒绝写入敏感信息"}}}let V=new l0(X);if(Z==="MEMORY")await V.updateIndex(Y,J);else await V.writeTopic(Z,Y,J);return{success:!0,llmContent:`${J==="overwrite"?"Written":"Appended"} to memory/${Z}.md (${Y.length} chars)`,metadata:{summary:`写入记忆: ${Z}`}}}});import*as f1 from"fs/promises";import{z as f$}from"zod";var c2=j({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:f$.object({notebook_path:f$.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:f$.string().optional().describe("The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified."),new_source:f$.string().describe("The new source for the cell"),cell_type:f$.enum(["code","markdown"]).optional().describe("The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required."),edit_mode:f$.enum(["replace","insert","delete"]).optional().default("replace").describe("The type of edit to make (replace, insert, delete). Defaults to replace.")}),description:{short:"Completely replaces the contents of a specific cell in a Jupyter notebook",long:"Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number."},async execute($,W){let{notebook_path:Z,cell_id:Y,new_source:J,cell_type:X,edit_mode:V="replace"}=$;try{let H=await f1.readFile(Z,"utf-8"),B=JSON.parse(H);if(!B.cells||!Array.isArray(B.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",error:{type:"validation_error",message:"Invalid notebook format"},metadata:{summary:"无效的 Notebook 格式"}};let K=-1;if(Y){if(K=B.cells.findIndex((U)=>U.id===Y),K===-1&&V!=="insert")return{success:!1,llmContent:`Cell with ID "${Y}" not found`,error:{type:"validation_error",message:`Cell ID "${Y}" not found`},metadata:{summary:`Cell 未找到: ${Y}`}}}switch(V){case"replace":{if(K===-1)return{success:!1,llmContent:"Cell ID required for replace operation",error:{type:"validation_error",message:"Cell ID required for replace"},metadata:{summary:"替换操作需要 Cell ID"}};let U=B.cells[K];if(U.source=J.split(`
420
+ `);if(J.length===1)return Y.map((K,B)=>({text:K,lineNumber:B+1,similarity:aZ(W.trim(),K.trim())})).filter((K)=>K.similarity>0.5).sort((K,B)=>B.similarity-K.similarity).slice(0,Z);let X=J.length,V=[];for(let H=0;H<=Y.length-X;H++){let K=Y.slice(H,H+X).join(`
421
+ `),B=aZ(W,K);if(B>0.5)V.push({text:K,lineNumber:H+1,similarity:B})}return V.sort((H,K)=>K.similarity-H.similarity).slice(0,Z)}function aZ($,W){let Z=(q)=>q.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),Y=Z($),J=Z(W);if(Y===J)return 1;let X=Y.length,V=J.length;if(X===0)return V===0?1:0;if(V===0)return 0;let H=200,K=Y.substring(0,H),B=J.substring(0,H),U=w9(K,B),Q=Math.max(K.length,B.length);return 1-U/Q}function w9($,W){let Z=$.length,Y=W.length,J=Array(Z+1).fill(null).map(()=>Array(Y+1).fill(0));for(let X=0;X<=Z;X++)J[X][0]=X;for(let X=0;X<=Y;X++)J[0][X]=X;for(let X=1;X<=Z;X++)for(let V=1;V<=Y;V++){let H=$[X-1]===W[V-1]?0:1;J[X][V]=Math.min(J[X-1][V]+1,J[X][V-1]+1,J[X-1][V-1]+H)}return J[Z][Y]}import{basename as G9,extname as oZ}from"path";import{z as E9}from"zod";var h2=N({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:E9.object({file_path:I.filePath({description:"File path to read (must be absolute)"}),offset:I.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:I.lineLimit({description:"Number of lines to read (text files only)"}).optional(),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($,W){let{file_path:Z,offset:Y,limit:J,encoding:X="utf8"}=$,{updateOutput:V,sessionId:H}=W,K=W.signal??new AbortController().signal;try{V?.("Starting file read...");let B=f$(),U=r0();try{if(!await B.exists(Z))throw Error("File not found")}catch(R){return{success:!1,llmContent:`File not found: ${Z}`,error:{type:"execution_error",message:`File not found: ${Z}`}}}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(H)await n0.getInstance().recordFileRead(Z,H);let Q=await B.stat(Z);if(Q?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${Z}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let q=oZ(Z).toLowerCase(),w=F9(q),E=z9(q),G,F={file_path:Z,file_size:Q?.size,file_type:q,last_modified:Q?.mtime instanceof Date?Q.mtime.toISOString():void 0,encoding:X,acp_mode:U};if(E&&X==="utf8"){if(U)V?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),F.acp_fallback=!0;else V?.("检测到二进制文件,使用 base64 编码...");G=(await B.readBinaryFile(Z)).toString("base64"),F.encoding="base64",F.is_binary=!0}else if(w){if(U)V?.("通过 IDE 读取文件...");G=await B.readTextFile(Z)}else{if(U)F.acp_fallback=!0;let R=await B.readBinaryFile(Z);if(X==="base64")G=R.toString("base64");else if(X==="binary")G=R.toString("binary");else G=R.toString("utf8")}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if((Y!==void 0||J!==void 0)&&X==="utf8"&&w){let R=G.split(`
422
+ `),j=Y||0,A=J!==void 0?j+J:R.length,L=R.slice(j,A);G=L.map((b,y)=>{let x=j+y+1,g=b.length>2000?`${b.substring(0,2000)}...`:b;return`${x.toString().padStart(6)}|${g}`}).join(`
423
+ `),F.lines_read=L.length,F.total_lines=R.length,F.start_line=j+1,F.end_line=Math.min(A,R.length)}let z=G9(Z),O=F.lines_read||F.total_lines,_=O?`读取 ${O} 行从 ${z}`:`读取 ${z}`;return F.summary=_,{success:!0,llmContent:G,metadata:F}}catch(B){let U=B;if(U.name==="AbortError")return{success:!1,llmContent:"File read aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=oZ($.file_path);return W?`**/*${W}`:"**/*"}});function F9($){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 z9($){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 R9}from"fs";import{basename as O9,dirname as _9,extname as D9}from"path";import{z as u2}from"zod";var p2=N({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:u2.object({file_path:I.filePath({description:"Absolute file path to write"}),content:u2.string().describe("Content to write"),encoding:I.encoding(),create_directories:u2.boolean().default(!0).describe("Automatically create missing parent directories")}),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($,W){let{file_path:Z,content:Y,encoding:J,create_directories:X}=$,{updateOutput:V,sessionId:H,messageId:K}=W,B=W.signal??new AbortController().signal;try{V?.("开始写入文件...");let U=f$(),Q=r0();if(X){let R=_9(Z);try{await U.mkdir(R,{recursive:!0,mode:493})}catch(j){if(j.code!=="EEXIST")throw j}}if(typeof B.throwIfAborted==="function")B.throwIfAborted();let q=!1,w=null;try{if(q=await U.exists(Z),q&&J==="utf8")try{w=await U.readTextFile(Z)}catch(R){console.warn("[WriteTool] 读取旧文件内容失败:",R)}}catch{}if(q&&H){let R=n0.getInstance();if(!R.hasFileBeenRead(Z,H))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 j=await R.checkExternalModification(Z);if(j.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.
424
+
425
+ Details: ${j.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:j.message}}}}let E=!1;if(q&&H&&K)try{let R=new $1({sessionId:H});await R.initialize(),await R.createSnapshot(Z,K),E=!0}catch(R){console.warn("[WriteTool] 创建快照失败:",R)}if(typeof B.throwIfAborted==="function")B.throwIfAborted();if(J==="utf8"){if(Q)V?.("通过 IDE 写入文件...");await U.writeTextFile(Z,Y)}else{if(Q)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 R;if(J==="base64")R=Buffer.from(Y,"base64");else if(J==="binary")R=Buffer.from(Y,"binary");else R=Buffer.from(Y,"utf8");await R9.writeFile(Z,R)}if(H)await n0.getInstance().recordFileEdit(Z,H,"write");if(typeof B.throwIfAborted==="function")B.throwIfAborted();let G=await U.stat(Z),F=J==="utf8"?Y.split(`
426
+ `).length:0,z=O9(Z),O=null;if(w&&J==="utf8"&&w!==Y){if(w.length<1048576&&Y.length<1048576)O=pZ(w,Y,4)}let _={file_path:Z,content_size:Y.length,file_size:G?.size,encoding:J,created_directories:X,snapshot_created:E,session_id:H,message_id:K,last_modified:G?.mtime instanceof Date?G.mtime.toISOString():void 0,has_diff:!!O,summary:J==="utf8"?`写入 ${F} 行到 ${z}`:`写入 ${G?.size?j9(G.size):"unknown"} 到 ${z}`,kind:"edit",oldContent:w||"",newContent:J==="utf8"?Y:void 0};return{success:!0,llmContent:w?`Wrote ${Z} (${Y.length} chars, updated existing file)`:`Created ${Z} (${Y.length} chars, new file)`,metadata:_}}catch(U){let Q=U;if(Q.name==="AbortError")return{success:!1,llmContent:"File write aborted",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${Q.message}`,error:{type:"execution_error",message:Q.message,details:Q}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let W=D9($.file_path);return W?`**/*${W}`:"**/*"}});function j9($){let W=["B","KB","MB","GB"],Z=$,Y=0;while(Z>=1024&&Y<W.length-1)Z/=1024,Y++;return`${Z.toFixed(1)}${W[Y]}`}import{z as W1}from"zod";var eZ=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),A9=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),N9=W1.object({operation:W1.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:W1.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:W1.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:W1.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function sZ($){let W={...$};if(Array.isArray(W.models))W.models=W.models.map((Z)=>{let Y={...Z};if(typeof Y.apiKey==="string"&&Y.apiKey){let J=Y.apiKey;Y.apiKey=J.length>8?`${J.slice(0,4)}...${J.slice(-4)}`:"****"}return Y});return W}function tZ($,W){let Z=W.split("."),Y=$;for(let J of Z){if(Y===null||Y===void 0||typeof Y!=="object")return;Y=Y[J]}return Y}function T9($){let W=["可配置项列表(白名单):",""];for(let Z of eZ){let Y=$[Z],J=Y===void 0?"(未设置)":JSON.stringify(Y,null,2),X=J.length>200?`${J.slice(0,197)}...`:J;W.push(`- ${Z}: ${X}`)}return W.join(`
427
+ `)}var d2=N({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:N9,description:{short:"Read, update, or list Blade configuration",long:"Manage Blade configuration: get reads a config value, set updates a whitelisted config field (with persistence), list enumerates all settable keys and their current values.",usageNotes:['Use operation="get" with key="*" to dump all config','Use operation="get" with a dotted key like "hooks.PreToolUse"','Use operation="set" with key and value to update config','Use operation="list" to see all settable keys',"The scope option controls persistence: local/project/global","models and apiKey fields cannot be modified for security"],examples:[{description:"Get all configuration",params:{operation:"get",key:"*"}},{description:"Get a specific config value",params:{operation:"get",key:"hooks"}},{description:"Set temperature",params:{operation:"set",key:"temperature",value:0.7,scope:"global"}},{description:"List all settable keys",params:{operation:"list"}}]},async execute($,W){let{operation:Z,key:Y,value:J,scope:X}=$,V=Y0();if(!V)return{success:!1,llmContent:"Config not initialized. Please wait for Blade to finish starting.",error:{message:"Config not initialized",type:"execution_error"},metadata:{summary:"配置未初始化"}};switch(Z){case"get":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for get operation. Use key="*" to get all config.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(Y==="*"){let U=sZ(V);return{success:!0,llmContent:JSON.stringify(U,null,2),metadata:{summary:"获取全部配置"}}}let H=V;if(Y.split(".")[0]==="models"){let U=sZ(H),Q=tZ(U,Y);return{success:!0,llmContent:JSON.stringify(Q,null,2),metadata:{summary:`获取配置: ${Y}`}}}let B=tZ(H,Y);if(B===void 0)return{success:!0,llmContent:`Config key "${Y}" is not set or does not exist.`,metadata:{summary:`配置项 ${Y} 不存在`}};return{success:!0,llmContent:JSON.stringify(B,null,2),metadata:{summary:`获取配置: ${Y}`}}}case"set":{if(!Y)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(J===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let H=Y.split(".")[0];if(H==="models"||H==="currentModelId")return{success:!1,llmContent:'Refused: "models" and "currentModelId" cannot be modified via ConfigTool to protect API keys. Use the /model slash command instead.',error:{message:"Forbidden key: models",type:"permission_denied"},metadata:{summary:"拒绝修改 models"}};if(A9.has(H))return{success:!1,llmContent:`Refused: "${H}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${H}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${H}`}};if(!eZ.has(H))return{success:!1,llmContent:`Key "${H}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${H}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${H}`}};let K;if(Y.includes(".")){let B=Y.split(".");if(K={[B[0]]:J},B.length===2){let U=V[B[0]];if(typeof U==="object"&&U!==null)K={[B[0]]:{...U,[B[1]]:J}};else K={[B[0]]:{[B[1]]:J}}}}else K={[Y]:J};try{await a0().updateConfig(K,X?{scope:X}:{});let B=JSON.stringify(J).length>200?`${JSON.stringify(J).slice(0,197)}...`:JSON.stringify(J);return{success:!0,llmContent:`Config updated: ${Y} = ${B}`+(X?` (scope: ${X})`:""),metadata:{summary:`配置已更新: ${Y}`}}}catch(B){let U=B instanceof Error?B.message:String(B);return{success:!1,llmContent:`Failed to update config: ${U}`,error:{message:U,type:"execution_error"},metadata:{summary:`配置更新失败: ${Y}`}}}}case"list":return{success:!0,llmContent:T9(V),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${Z}`,error:{message:`Unknown operation: ${Z}`,type:"validation_error"},metadata:{summary:`未知操作: ${Z}`}}}}});import{z as $5}from"zod";var g2=N({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:$5.object({topic:$5.string().describe('Topic name to read (e.g., "debugging", "patterns", "MEMORY" for the index, "_list" to list all topics). Without .md extension.')}),description:{short:"Read a topic file from project auto memory",long:"Reads a topic file from the project's persistent auto memory directory. Use this to retrieve detailed notes that were saved in previous sessions. The MEMORY.md index is automatically loaded at session start, but topic files need to be read on demand.",usageNotes:['Use topic="MEMORY" to read the full MEMORY.md index','Use topic="_list" to list all available memory files',"Topic files are stored at ~/.blade/projects/{project}/memory/{topic}.md"],examples:[{description:"Read debugging notes",params:{topic:"debugging"}},{description:"Read the full MEMORY.md index",params:{topic:"MEMORY"}},{description:"List all memory topics",params:{topic:"_list"}}]},async execute($,W){let{topic:Z}=$,Y=W.workspaceRoot||D(),J=new l0(Y);if(Z==="_list"){let V=await J.listTopics();if(V.length===0)return{success:!0,llmContent:"No memory files found. Use MemoryWrite to save project knowledge.",metadata:{summary:"无记忆文件"}};return{success:!0,llmContent:`Memory files:
428
+ ${V.map((B)=>`- ${B.name}.md (${B.size} bytes, updated ${B.lastModified.toISOString()})`).join(`
429
+ `)}`,metadata:{summary:`列出 ${V.length} 个记忆文件`}}}let X=await J.readTopic(Z);if(X===null)return{success:!0,llmContent:`Memory topic "${Z}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${Z}`}};return{success:!0,llmContent:X,metadata:{summary:`读取记忆: ${Z}`}}}});import{z as f1}from"zod";var L9=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],m2=N({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:f1.object({topic:f1.string().describe('Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'),content:f1.string().describe("Content to write to the memory file"),mode:f1.enum(["overwrite","append"]).default("append").describe('Write mode: "append" adds to existing content, "overwrite" replaces it')}),description:{short:"Save project knowledge to persistent auto memory",long:"Saves notes and learnings to the project's persistent auto memory. Use this to record useful project knowledge that should survive across sessions — build commands, code patterns, debugging insights, architecture notes, and user preferences.",usageNotes:['Use topic="MEMORY" to update the index file (keep it concise, under 200 lines)','Use descriptive topic names for detailed notes (e.g., "debugging", "api-conventions")','Default mode is "append" — adds to existing content','Use "overwrite" mode to replace the entire topic file',"Do NOT save sensitive data (passwords, tokens, API keys)"],examples:[{description:"Save a debugging insight",params:{topic:"debugging",content:"## Redis connection timeout\nThe test suite requires a local Redis instance. Start with `docker compose up redis`."}},{description:"Update the memory index",params:{topic:"MEMORY",content:"# Project Memory\n\n- Build: `bun run build`\n- Test: `bun run test`\n- See debugging.md for common issues",mode:"overwrite"}}]},async execute($,W){let{topic:Z,content:Y,mode:J}=$,X=W.workspaceRoot||D();for(let B of L9)if(B.test(Y)){let U=`Refused: content appears to contain sensitive data (matched ${B}). Do not save passwords, tokens, or API keys to memory.`;return{success:!1,llmContent:U,error:{message:U,type:"validation_error"},metadata:{summary:"拒绝写入敏感信息"}}}let V=new l0(X);if(Z==="MEMORY")await V.updateIndex(Y,J);else await V.writeTopic(Z,Y,J);return{success:!0,llmContent:`${J==="overwrite"?"Written":"Appended"} to memory/${Z}.md (${Y.length} chars)`,metadata:{summary:`写入记忆: ${Z}`}}}});import*as P1 from"fs/promises";import{z as P$}from"zod";var c2=N({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:P$.object({notebook_path:P$.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:P$.string().optional().describe("The ID of the cell to edit. When inserting a new cell, the new cell will be inserted after the cell with this ID, or at the beginning if not specified."),new_source:P$.string().describe("The new source for the cell"),cell_type:P$.enum(["code","markdown"]).optional().describe("The type of the cell (code or markdown). If not specified, it defaults to the current cell type. If using edit_mode=insert, this is required."),edit_mode:P$.enum(["replace","insert","delete"]).optional().default("replace").describe("The type of edit to make (replace, insert, delete). Defaults to replace.")}),description:{short:"Completely replaces the contents of a specific cell in a Jupyter notebook",long:"Completely replaces the contents of a specific cell in a Jupyter notebook (.ipynb file) with new source. Jupyter notebooks are interactive documents that combine code, text, and visualizations, commonly used for data analysis and scientific computing. The notebook_path parameter must be an absolute path, not a relative path. The cell_number is 0-indexed. Use edit_mode=insert to add a new cell at the index specified by cell_number. Use edit_mode=delete to delete the cell at the index specified by cell_number."},async execute($,W){let{notebook_path:Z,cell_id:Y,new_source:J,cell_type:X,edit_mode:V="replace"}=$;try{let H=await P1.readFile(Z,"utf-8"),K=JSON.parse(H);if(!K.cells||!Array.isArray(K.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",error:{type:"validation_error",message:"Invalid notebook format"},metadata:{summary:"无效的 Notebook 格式"}};let B=-1;if(Y){if(B=K.cells.findIndex((Q)=>Q.id===Y),B===-1&&V!=="insert")return{success:!1,llmContent:`Cell with ID "${Y}" not found`,error:{type:"validation_error",message:`Cell ID "${Y}" not found`},metadata:{summary:`Cell 未找到: ${Y}`}}}switch(V){case"replace":{if(B===-1)return{success:!1,llmContent:"Cell ID required for replace operation",error:{type:"validation_error",message:"Cell ID required for replace"},metadata:{summary:"替换操作需要 Cell ID"}};let Q=K.cells[B];if(Q.source=J.split(`
430
430
  `).map((q,w,E)=>w<E.length-1?q+`
431
- `:q),X)U.cell_type=X;break}case"insert":{if(!X)return{success:!1,llmContent:"cell_type is required for insert operation",error:{type:"validation_error",message:"cell_type required for insert"},metadata:{summary:"插入操作需要 cell_type"}};let U={cell_type:X,source:J.split(`
431
+ `:q),X)Q.cell_type=X;break}case"insert":{if(!X)return{success:!1,llmContent:"cell_type is required for insert operation",error:{type:"validation_error",message:"cell_type required for insert"},metadata:{summary:"插入操作需要 cell_type"}};let Q={cell_type:X,source:J.split(`
432
432
  `).map((w,E,G)=>E<G.length-1?w+`
433
- `:w),metadata:{},...X==="code"?{execution_count:null,outputs:[]}:{}},q=K===-1?0:K+1;B.cells.splice(q,0,U);break}case"delete":{if(K===-1)return{success:!1,llmContent:"Cell ID required for delete operation",error:{type:"validation_error",message:"Cell ID required for delete"},metadata:{summary:"删除操作需要 Cell ID"}};B.cells.splice(K,1);break}}await f1.writeFile(Z,JSON.stringify(B,null,2));let Q=V==="replace"?"replaced":V==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${Q} cell in ${Z}`,metadata:{notebook_path:Z,edit_mode:V,cell_id:Y,summary:`Notebook cell ${Q}: ${Z}`}}}catch(H){let B=H instanceof Error?H.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${B}`,error:{type:"execution_error",message:B},metadata:{summary:"编辑 Notebook 失败"}}}}});import{z as k9}from"zod";var l2=j({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:k9.object({}),description:{short:"Use this tool to enter plan mode for complex tasks requiring careful planning",long:`Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
433
+ `:w),metadata:{},...X==="code"?{execution_count:null,outputs:[]}:{}},q=B===-1?0:B+1;K.cells.splice(q,0,Q);break}case"delete":{if(B===-1)return{success:!1,llmContent:"Cell ID required for delete operation",error:{type:"validation_error",message:"Cell ID required for delete"},metadata:{summary:"删除操作需要 Cell ID"}};K.cells.splice(B,1);break}}await P1.writeFile(Z,JSON.stringify(K,null,2));let U=V==="replace"?"replaced":V==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${U} cell in ${Z}`,metadata:{notebook_path:Z,edit_mode:V,cell_id:Y,summary:`Notebook cell ${U}: ${Z}`}}}catch(H){let K=H instanceof Error?H.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${K}`,error:{type:"execution_error",message:K},metadata:{summary:"编辑 Notebook 失败"}}}}});import{z as k9}from"zod";var l2=N({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:k9.object({}),description:{short:"Use this tool to enter plan mode for complex tasks requiring careful planning",long:`Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
434
434
 
435
435
  ## When to Use This Tool
436
436
 
@@ -515,7 +515,7 @@ Begin your research now.`,metadata:{approved:!0,enterPlanMode:!0,summary:"进入
515
515
 
516
516
  Proceed with the task directly without planning phase. You can still use search tools to understand the codebase as needed, but implement the solution directly.`,metadata:{approved:!1,enterPlanMode:!1,summary:"Plan 模式被拒绝"}}}catch(Z){return{success:!1,llmContent:`Confirmation flow error: ${Z instanceof Error?Z.message:"Unknown error"}`,error:{type:"execution_error",message:"Confirmation flow error"},metadata:{summary:"确认流程出错"}}}return{success:!0,llmContent:`Plan mode requested but no interactive confirmation available.
517
517
 
518
- Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,metadata:{approved:null,enterPlanMode:!0,summary:"Plan 模式(非交互)"}}}});import{promises as W5}from"node:fs";import{homedir as b9}from"node:os";import*as i2 from"node:path";import{z as Z5}from"zod";var r2=j({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:Z5.object({plan:Z5.string().describe("The complete implementation plan in markdown format")}),description:{short:"Use this tool when you are in plan mode and have finished creating your plan and are ready for user approval",long:`Use this tool when you are in plan mode and have finished creating your implementation plan and are ready for user approval.
518
+ Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,metadata:{approved:null,enterPlanMode:!0,summary:"Plan 模式(非交互)"}}}});import{promises as W5}from"node:fs";import{homedir as b9}from"node:os";import*as i2 from"node:path";import{z as Z5}from"zod";var r2=N({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",isConcurrencySafe:!1,schema:Z5.object({plan:Z5.string().describe("The complete implementation plan in markdown format")}),description:{short:"Use this tool when you are in plan mode and have finished creating your plan and are ready for user approval",long:`Use this tool when you are in plan mode and have finished creating your implementation plan and are ready for user approval.
519
519
 
520
520
  ## PREREQUISITES (MUST be satisfied before calling)
521
521
 
@@ -555,33 +555,33 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
555
555
  `+(Y.feedback||"No specific feedback provided.")+`
556
556
 
557
557
  The agent has stopped and control is returned to the user. The user can now provide additional information or clarification.`,metadata:{approved:!1,shouldExitLoop:!0,feedback:Y.feedback,awaitingUserInput:!0,summary:"方案被拒绝,等待用户反馈"}}}catch(Y){return{success:!1,llmContent:`Confirmation flow error: ${Y instanceof Error?Y.message:"Unknown error"}`,error:{type:"execution_error",message:"Confirmation flow error"},metadata:{summary:"确认流程出错"}}}return{success:!0,llmContent:`[OK] Plan mode exit requested. No interactive confirmation available.
558
- Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import h9 from"fast-glob";import{stat as u9}from"node:fs/promises";import{join as p9,resolve as d9}from"path";import{z as I1}from"zod";import{existsSync as M9,readFileSync as v9}from"node:fs";import{readFile as x9}from"node:fs/promises";import{dirname as C9,join as J5}from"node:path";import y9 from"fast-glob";import{LRUCache as P9}from"lru-cache";import Z1 from"picomatch";var G$=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],f9=["*.log","npm-debug.log*","yarn-debug.log*","pnpm-debug.log*","*.lock","bun.lock","package-lock.json","yarn.lock","pnpm-lock.yaml","*.tmp","*.temp","*.swp","*.bak","*~",".DS_Store","Thumbs.db","*.pid","*.seed"];function S9($){if(!M9($))return{patterns:[],negatePatterns:[]};try{let W=v9($,"utf-8"),Z=[],Y=[];for(let J of W.split(`
559
- `)){let X=J.trim();if(!X||X.startsWith("#"))continue;if(X.startsWith("!"))Y.push(X.slice(1));else Z.push(X)}return{patterns:Z,negatePatterns:Y}}catch(W){return console.warn(`Failed to read .gitignore: ${W}`),{patterns:[],negatePatterns:[]}}}var Y5=new P9({max:100,ttl:30000,updateAgeOnGet:!0});async function I9($,W){let Z=[...G$.map((B)=>`${B}/**`),...W?.scanIgnore??[]],Y=`${$}|${Z.join(",")}`,J=Y5.get(Y);if(J)return J;let X=await y9("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:Z});X.sort((B,K)=>t$(B).length-t$(K).length);let V=[];for(let B of X){let K=C9(B).replace(/\\/g,"/"),Q=K==="."?"":K,q=(await x9(J5($,B),"utf-8")).split(`
560
- `);for(let w of q){let E=w.trim();if(!E||E.startsWith("#"))continue;let G=E.startsWith("!"),R=(G?E.slice(1):E).trim();if(!R)continue;let O="";if(R.startsWith("/")){let _=R.slice(1).replace(/\\/g,"/");if(O=(Q?Q+"/":"")+_,V.push({type:G?"negate":"ignore",pattern:O}),R.endsWith("/")){let z=O+"**";V.push({type:G?"negate":"ignore",pattern:z});let N=O.replace(/\/$/,"");if(N!==O)V.push({type:G?"negate":"ignore",pattern:N})}}else{let _=R.replace(/\\/g,"/");if(_.includes("/")){if(O=(Q?Q+"/":"")+_,V.push({type:G?"negate":"ignore",pattern:O}),_.endsWith("/")){let z=O+"**";V.push({type:G?"negate":"ignore",pattern:z});let N=O.replace(/\/$/,"");if(N!==O)V.push({type:G?"negate":"ignore",pattern:N})}}else O=(Q?Q+"/**/":"**/")+_,V.push({type:G?"negate":"ignore",pattern:O})}}}let H=W?.cacheTTL??30000;return Y5.set(Y,V,{ttl:H}),V}class S1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let W=new S1({...$,useGitignore:!1}),{cwd:Z=D(),useGitignore:Y=!0,gitignoreScanMode:J="root",customScanIgnore:X=[],cacheTTL:V}=$;if(Y&&J==="recursive"){let H=await I9(Z,{scanIgnore:X,cacheTTL:V});for(let B of H)if(W.orderedRules.push({type:B.type,matcher:Z1(B.pattern,{dot:!0})}),B.type==="ignore")W.ignorePatterns.push(B.pattern);else W.negatePatterns.push(B.pattern)}return W}initialize($){let{cwd:W=D(),useGitignore:Z=!0,useDefaults:Y=!0,customPatterns:J=[]}=$,X=[],V=[];if(Y){let H=[...G$.map((B)=>`${B}/**`),...G$,...f9];X.push(...H);for(let B of H)this.orderedRules.push({type:"ignore",matcher:Z1(B,{dot:!0})})}if(Z){let H=J5(W,".gitignore"),{patterns:B,negatePatterns:K}=S9(H);for(let Q of B)this.orderedRules.push({type:"ignore",matcher:Z1(Q,{dot:!0})}),X.push(Q);for(let Q of K)this.orderedRules.push({type:"negate",matcher:Z1(Q,{dot:!0})}),V.push(Q)}X.push(...J);for(let H of J)this.orderedRules.push({type:"ignore",matcher:Z1(H,{dot:!0})});this.ignorePatterns=X,this.negatePatterns=V}shouldIgnore($){let W=$.replace(/\\/g,"/"),Z=void 0;for(let Y of this.orderedRules)if(Y.matcher(W))Z=Y.type==="ignore";return Z===!0}shouldIgnoreDirectory($){let W=$.replace(/\\/g,"/");return this.shouldIgnore(W)||this.shouldIgnore(`${W}/`)}filter($){return $.filter((W)=>!this.shouldIgnore(W))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function n2($){let W=Error($);return W.name="AbortError",W}var a2=j({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:I1.object({pattern:I.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:I1.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:I.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:I1.boolean().default(!1).describe("Include directories in results"),case_sensitive:I1.boolean().default(!1).describe("Case sensitive matching")}),description:{short:"Fast file pattern matching tool that works with any codebase size",long:'Fast file pattern matching tool that works with any codebase size. Supports glob patterns like "**/*.js" or "src/**/*.ts". Returns matching file paths sorted by modification time.',usageNotes:["Use this tool when you need to find files by name patterns","When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead","You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful."]},async execute($,W){let{pattern:Z,path:Y,max_results:J,include_directories:X,case_sensitive:V}=$,{updateOutput:H}=W,B=W.signal??new AbortController().signal,K=Y??W.workspaceRoot??D();try{H?.(`Searching in ${K} for pattern "${Z}"...`);let Q=d9(K);try{if(!(await u9(Q)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${Q}`,metadata:{summary:"搜索失败: 搜索路径必须是目录"},error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(R){if(R.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${Q}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw R}B.throwIfAborted();let U=await S1.create({cwd:Q,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:q,wasTruncated:w}=await g9(Q,Z,{maxResults:J,includeDirectories:X,caseSensitive:V,signal:B},U),E=m9(q),G={search_path:Q,pattern:Z,total_matches:q.length,returned_matches:q.length,max_results:J,include_directories:X,case_sensitive:V,truncated:w},F;if(E.length>0)F=`${w?`Found at least ${E.length} file(s) matching "${Z}" (truncated)`:`Found ${E.length} file(s) matching "${Z}"`}:
558
+ Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import h9 from"fast-glob";import{stat as u9}from"node:fs/promises";import{join as p9,resolve as d9}from"path";import{z as I1}from"zod";import{existsSync as M9,readFileSync as v9}from"node:fs";import{readFile as x9}from"node:fs/promises";import{dirname as C9,join as J5}from"node:path";import y9 from"fast-glob";import{LRUCache as f9}from"lru-cache";import Z1 from"picomatch";var G$=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],P9=["*.log","npm-debug.log*","yarn-debug.log*","pnpm-debug.log*","*.lock","bun.lock","package-lock.json","yarn.lock","pnpm-lock.yaml","*.tmp","*.temp","*.swp","*.bak","*~",".DS_Store","Thumbs.db","*.pid","*.seed"];function S9($){if(!M9($))return{patterns:[],negatePatterns:[]};try{let W=v9($,"utf-8"),Z=[],Y=[];for(let J of W.split(`
559
+ `)){let X=J.trim();if(!X||X.startsWith("#"))continue;if(X.startsWith("!"))Y.push(X.slice(1));else Z.push(X)}return{patterns:Z,negatePatterns:Y}}catch(W){return console.warn(`Failed to read .gitignore: ${W}`),{patterns:[],negatePatterns:[]}}}var Y5=new f9({max:100,ttl:30000,updateAgeOnGet:!0});async function I9($,W){let Z=[...G$.map((K)=>`${K}/**`),...W?.scanIgnore??[]],Y=`${$}|${Z.join(",")}`,J=Y5.get(Y);if(J)return J;let X=await y9("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:Z});X.sort((K,B)=>t$(K).length-t$(B).length);let V=[];for(let K of X){let B=C9(K).replace(/\\/g,"/"),U=B==="."?"":B,q=(await x9(J5($,K),"utf-8")).split(`
560
+ `);for(let w of q){let E=w.trim();if(!E||E.startsWith("#"))continue;let G=E.startsWith("!"),z=(G?E.slice(1):E).trim();if(!z)continue;let O="";if(z.startsWith("/")){let _=z.slice(1).replace(/\\/g,"/");if(O=(U?U+"/":"")+_,V.push({type:G?"negate":"ignore",pattern:O}),z.endsWith("/")){let R=O+"**";V.push({type:G?"negate":"ignore",pattern:R});let j=O.replace(/\/$/,"");if(j!==O)V.push({type:G?"negate":"ignore",pattern:j})}}else{let _=z.replace(/\\/g,"/");if(_.includes("/")){if(O=(U?U+"/":"")+_,V.push({type:G?"negate":"ignore",pattern:O}),_.endsWith("/")){let R=O+"**";V.push({type:G?"negate":"ignore",pattern:R});let j=O.replace(/\/$/,"");if(j!==O)V.push({type:G?"negate":"ignore",pattern:j})}}else O=(U?U+"/**/":"**/")+_,V.push({type:G?"negate":"ignore",pattern:O})}}}let H=W?.cacheTTL??30000;return Y5.set(Y,V,{ttl:H}),V}class S1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let W=new S1({...$,useGitignore:!1}),{cwd:Z=D(),useGitignore:Y=!0,gitignoreScanMode:J="root",customScanIgnore:X=[],cacheTTL:V}=$;if(Y&&J==="recursive"){let H=await I9(Z,{scanIgnore:X,cacheTTL:V});for(let K of H)if(W.orderedRules.push({type:K.type,matcher:Z1(K.pattern,{dot:!0})}),K.type==="ignore")W.ignorePatterns.push(K.pattern);else W.negatePatterns.push(K.pattern)}return W}initialize($){let{cwd:W=D(),useGitignore:Z=!0,useDefaults:Y=!0,customPatterns:J=[]}=$,X=[],V=[];if(Y){let H=[...G$.map((K)=>`${K}/**`),...G$,...P9];X.push(...H);for(let K of H)this.orderedRules.push({type:"ignore",matcher:Z1(K,{dot:!0})})}if(Z){let H=J5(W,".gitignore"),{patterns:K,negatePatterns:B}=S9(H);for(let U of K)this.orderedRules.push({type:"ignore",matcher:Z1(U,{dot:!0})}),X.push(U);for(let U of B)this.orderedRules.push({type:"negate",matcher:Z1(U,{dot:!0})}),V.push(U)}X.push(...J);for(let H of J)this.orderedRules.push({type:"ignore",matcher:Z1(H,{dot:!0})});this.ignorePatterns=X,this.negatePatterns=V}shouldIgnore($){let W=$.replace(/\\/g,"/"),Z=void 0;for(let Y of this.orderedRules)if(Y.matcher(W))Z=Y.type==="ignore";return Z===!0}shouldIgnoreDirectory($){let W=$.replace(/\\/g,"/");return this.shouldIgnore(W)||this.shouldIgnore(`${W}/`)}filter($){return $.filter((W)=>!this.shouldIgnore(W))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function n2($){let W=Error($);return W.name="AbortError",W}var a2=N({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:I1.object({pattern:I.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:I1.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:I.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:I1.boolean().default(!1).describe("Include directories in results"),case_sensitive:I1.boolean().default(!1).describe("Case sensitive matching")}),description:{short:"Fast file pattern matching tool that works with any codebase size",long:'Fast file pattern matching tool that works with any codebase size. Supports glob patterns like "**/*.js" or "src/**/*.ts". Returns matching file paths sorted by modification time.',usageNotes:["Use this tool when you need to find files by name patterns","When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead","You can call multiple tools in a single response. It is always better to speculatively perform multiple searches in parallel if they are potentially useful."]},async execute($,W){let{pattern:Z,path:Y,max_results:J,include_directories:X,case_sensitive:V}=$,{updateOutput:H}=W,K=W.signal??new AbortController().signal,B=Y??W.workspaceRoot??D();try{H?.(`Searching in ${B} for pattern "${Z}"...`);let U=d9(B);try{if(!(await u9(U)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${U}`,metadata:{summary:"搜索失败: 搜索路径必须是目录"},error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(z){if(z.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${U}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw z}K.throwIfAborted();let Q=await S1.create({cwd:U,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:q,wasTruncated:w}=await g9(U,Z,{maxResults:J,includeDirectories:X,caseSensitive:V,signal:K},Q),E=m9(q),G={search_path:U,pattern:Z,total_matches:q.length,returned_matches:q.length,max_results:J,include_directories:X,case_sensitive:V,truncated:w},F;if(E.length>0)F=`${w?`Found at least ${E.length} file(s) matching "${Z}" (truncated)`:`Found ${E.length} file(s) matching "${Z}"`}:
561
561
 
562
562
  `+E.map((O)=>`- ${O.relative_path}`).join(`
563
563
  `)+`
564
564
 
565
- Use the relative_path values above for Read/Edit operations.`;else F=`No files found matching "${Z}"`;return{success:!0,llmContent:F,metadata:{...G,matches:E,summary:`找到 ${q.length} 个匹配 "${Z}" 的文件`}}}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"File search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${U.message}`,metadata:{summary:`搜索失败: ${U.message}`},error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function g9($,W,Z,Y){let J=Y.getIgnorePatterns(),X=[],V=!1;return await new Promise((H,B)=>{if(Z.signal.aborted){B(n2("文件搜索被用户中止"));return}let K=h9.stream(W,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:Z.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!Z.includeDirectories,ignore:J}),Q=!1,U=null,q=()=>{if(U){if(Z.signal.removeEventListener)Z.signal.removeEventListener("abort",U);else if("onabort"in Z.signal)Z.signal.onabort=null;U=null}},w=()=>{if(!Q)Q=!0,V=!0,K.destroy(),q(),H({matches:X,wasTruncated:V})},E=(G)=>{if(Z.signal.aborted){if(!Q)Q=!0,K.destroy(n2("文件搜索被用户中止"));return}if(X.length>=Z.maxResults){w();return}let F=G.path.replace(/\\/g,"/"),R=p9($,F);if(Y.shouldIgnore(F))return;let O=G.stats?G.stats.isDirectory():!1;if(O&&Y.shouldIgnoreDirectory(F))return;let _=G.stats&&G.stats.isFile()?G.stats.size:void 0,z=G.stats?G.stats.mtime.toISOString():void 0;if(X.push({path:R,relative_path:F,is_directory:O,size:_,modified:z}),X.length>=Z.maxResults)w()};if(K.on("data",E),U=()=>{if(!Q)Q=!0,q(),K.destroy(n2("文件搜索被用户中止"))},Z.signal.addEventListener)Z.signal.addEventListener("abort",U);else if("onabort"in Z.signal)Z.signal.onabort=U;K.once("error",(G)=>{if(!Q)Q=!0,q(),B(G)}),K.once("end",()=>{if(!Q)Q=!0,q(),H({matches:X,wasTruncated:V})})})}function m9($){return $.sort((W,Z)=>{if(W.is_directory!==Z.is_directory)return W.is_directory?1:-1;if(W.modified&&Z.modified)return new Date(Z.modified).getTime()-new Date(W.modified).getTime();return W.relative_path.localeCompare(Z.relative_path)})}import{execSync as s2,spawn as t2}from"child_process";import{existsSync as o2}from"fs";import{readdir as c9,readFile as l9}from"fs/promises";import{join as i9,relative as r9}from"path";import n9 from"picomatch";import{z as o0}from"zod";function a9(){let{platform:$,arch:W}=process,Z={"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"},Y=`${$}-${W}`,J=Z[Y];if(!J)return null;try{let X=new URL("../../../../vendor/ripgrep/"+J,import.meta.url).pathname;if(o2(X))return X}catch{}return null}function X5(){try{let W=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",Z=s2(W,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(Z)return Z}catch{}let $=a9();if($&&o2($))return $;try{let W=U$("@vscode/ripgrep");if(W?.rgPath&&o2(W.rgPath))return W.rgPath}catch{}return null}async function o9($){try{return s2("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function s9(){try{return s2("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function t9($,W,Z,Y){let J=X5();if(!J)throw Error("ripgrep not available");return new Promise((X,V)=>{let H=t2(J,$,{stdio:["pipe","pipe","pipe"]}),B="",K="";H.stdout.on("data",(U)=>{B+=U.toString()}),H.stderr.on("data",(U)=>{K+=U.toString()}),H.on("close",(U)=>{X({stdout:B,stderr:K,exitCode:U||0})}),H.on("error",(U)=>{V(U)});let Q=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Z.addEventListener("abort",Q),H.on("close",()=>{Z.removeEventListener("abort",Q)})})}async function e9($,W,Z,Y){let J=["grep","-n"];if(Z.caseInsensitive)J.push("-i");if(Z.contextLines!==void 0)J.push(`-C${Z.contextLines}`);if(J.push("-e",$),Z.glob)J.push("--",Z.glob);return new Promise((X,V)=>{let H=t2("git",J,{cwd:W,stdio:["pipe","pipe","pipe"]}),B="",K="";H.stdout.on("data",(U)=>{B+=U.toString()}),H.stderr.on("data",(U)=>{K+=U.toString()}),H.on("close",(U)=>{X({stdout:B,stderr:K,exitCode:U||0})}),H.on("error",(U)=>{V(U)});let Q=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Y.addEventListener("abort",Q),H.on("close",()=>{Y.removeEventListener("abort",Q)})})}async function $4($,W,Z,Y){let J=["-rn"];if(Z.caseInsensitive)J.push("-i");if(Z.contextLines!==void 0)J.push(`-C${Z.contextLines}`);for(let X of G$)J.push("--exclude-dir="+X.replace(/^\./,""));return J.push("-e",$,W),new Promise((X,V)=>{let H=t2("grep",J,{stdio:["pipe","pipe","pipe"]}),B="",K="";H.stdout.on("data",(U)=>{B+=U.toString()}),H.stderr.on("data",(U)=>{K+=U.toString()}),H.on("close",(U)=>{X({stdout:B,stderr:K,exitCode:U||0})}),H.on("error",(U)=>{V(U)});let Q=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Y.addEventListener("abort",Q),H.on("close",()=>{Y.removeEventListener("abort",Q)})})}async function W4($,W,Z,Y){let J=[],X=new RegExp($,Z.caseInsensitive?"gi":"g"),V=await Z4(W,Y),H=0;for(let B of V){if(Y.throwIfAborted(),V5(B))continue;if(Z.glob&&!Y4(B,Z.glob))continue;try{(await l9(B,"utf-8")).split(`
566
- `).forEach((U,q)=>{if(X.test(U))J.push({file_path:r9(W,B),line_number:q+1,content:U})}),H++}catch(K){continue}}return{matches:J,totalFiles:H}}async function Z4($,W){let Z=[];async function Y(J){W.throwIfAborted();try{let X=await c9(J,{withFileTypes:!0});for(let V of X){W.throwIfAborted();let H=i9(J,V.name);if(V.isDirectory()){if(!V5(H))await Y(H)}else if(V.isFile())Z.push(H)}}catch(X){}}return await Y($),Z}function V5($){for(let W of G$)if($.includes(W))return!0;return!1}function Y4($,W){return n9(W)($)}function J4($){let W=[];if($.case_insensitive)W.push("-i");if($.multiline)W.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":W.push("-l");break;case"count":W.push("-c");break;case"content":if($.line_numbers)W.push("-n");break}if($.context!==void 0&&$.output_mode==="content")W.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")W.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")W.push("-A",$.context_after.toString())}if($.type)W.push("--type",$.type);for(let Z of G$)W.push("--glob",`!${Z}/**`);if($.glob)W.push("--glob",$.glob);if($.head_limit!==void 0){let Z=($.offset??0)+$.head_limit;W.push("-m",Z.toString())}return W.push($.pattern),W.push($.path),W}function X4($,W){if(!$.trim())return[];let Z=$.trim().split(`
567
- `),Y=[];switch(W){case"files_with_matches":return Z.map((J)=>({file_path:J.trim()}));case"count":return Z.map((J)=>{let[X,V]=J.split(":");return{file_path:X,count:parseInt(V,10)}});case"content":for(let J of Z){let X=V4(J);if(X)Y.push(X)}return Y;default:return[]}}function V4($){let W=$.indexOf(":");if(W===-1)return null;let Z=$.substring(0,W),Y=$.substring(W+1),J=Y.indexOf(":");if(J!==-1&&/^\d+$/.test(Y.substring(0,J))){let X=parseInt(Y.substring(0,J),10),V=Y.substring(J+1);return{file_path:Z,line_number:X,content:V}}else return{file_path:Z,content:Y}}var e2=j({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:o0.object({pattern:I.pattern({description:"The regular expression pattern to search for in file contents"}),path:o0.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:o0.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:o0.string().optional().describe("File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types"),output_mode:o0.enum(["content","files_with_matches","count"]).default("files_with_matches").describe('Output mode: "content" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), "files_with_matches" shows file paths (supports head_limit), "count" shows match counts (supports head_limit). Defaults to "files_with_matches"'),"-i":o0.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":o0.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":I.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":I.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":I.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:I.positiveInt().optional().describe('Limit output to first N lines/entries, equivalent to "| head -N". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults based on "cap" experiment value: 0 (unlimited), 20, or 100'),offset:I.nonNegativeInt().optional().describe('Skip first N lines/entries before applying head_limit, equivalent to "| tail -n +N | head -N". Works across all output modes. Defaults to 0'),multiline:o0.boolean().default(!1).describe("Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false")}),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($,W){let{pattern:Z,path:Y,glob:J,type:X,output_mode:V,"-i":H,"-n":B=!0,"-B":K,"-A":Q,"-C":U,head_limit:q,offset:w,multiline:E}=$,{updateOutput:G}=W,F=W.signal??new AbortController().signal,R=Y??W.workspaceRoot??D();try{G?.(`使用智能搜索策略查找模式 "${Z}"...`);let O=null,_="ripgrep",z=[],N=X5();if(N)try{G?.(`使用 ripgrep (${N})`);let M=J4({pattern:Z,path:R,glob:J,type:X,output_mode:V,case_insensitive:H??!1,line_numbers:B,context_before:K,context_after:Q,context:U,head_limit:q,offset:w,multiline:E??!1});O=await t9(M,V,F,G),_="ripgrep"}catch{G?.("[WARN] ripgrep 失败,尝试降级策略..."),O=null}if(!O&&await o9(R))try{G?.("使用 git grep"),O=await e9(Z,R,{caseInsensitive:H??!1,glob:J,contextLines:U},F),_="git-grep"}catch{G?.("[WARN] git grep 失败,继续尝试其他策略..."),O=null}if(!O&&s9())try{G?.("使用系统 grep"),O=await $4(Z,R,{caseInsensitive:H??!1,contextLines:U},F),_="system-grep"}catch{G?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),O=null}if(!O)G?.("使用纯 JavaScript 搜索实现"),z=(await W4(Z,R,{caseInsensitive:H??!1,glob:J,multiline:E??!1},F)).matches,_="fallback",O={stdout:"",stderr:"",exitCode:0};else z=X4(O.stdout,V);let A=z.length;if(w!==void 0&&w>0)z=z.slice(w);if(q!==void 0&&z.length>q)z=z.slice(0,q);let k={search_pattern:Z,search_path:R,output_mode:V,case_insensitive:H??!1,total_matches:z.length,original_total:A,offset:w,head_limit:q,strategy:_,exit_code:O?.exitCode};if(O&&O.exitCode!==0&&O.stderr)return{success:!1,llmContent:`Search execution failed: ${O.stderr}`,metadata:{...k,summary:`搜索失败: ${O.stderr}`},error:{type:"execution_error",message:O.stderr}};return{success:!0,llmContent:z,metadata:{...k,summary:z.length>0?`搜索 "${Z}" 找到 ${z.length} 个文件`:`搜索 "${Z}" 未找到匹配`}}}catch(O){let _=O;if(_.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${_.message}`,metadata:{summary:`搜索失败: ${_.message}`},error:{type:"execution_error",message:_.message,details:_}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{isAbsolute as q4,resolve as w4}from"node:path";import{z as $W}from"zod";var H4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),B4=/^(LD_.+|DYLD_.+|PATH)$/,H5=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function E$($){let W=$;while(!0){let Z=W.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let Y=Z[1],J=Z[2],X=Y.match(H5);if(!X)break;let V=X[1];if(!H4.has(V))break;W=J}return W}function B5($){let W=$;while(!0){let Z=W.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let Y=Z[1],J=Z[2],X=Y.match(H5);if(!X)break;let V=X[1];if(B4.test(V))break;W=J}return W}var K4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function s0($){let W=$,Z=!0;while(Z){Z=!1;for(let Y of K4){let J=W.match(Y);if(J){W=W.slice(J[0].length),Z=!0;break}}if(W.startsWith("-- "))W=W.slice(3),Z=!0}return W}function K5($){let W=[],Z="",Y=!1,J=!1,X=!1;for(let V=0;V<$.length;V++){let H=$[V];if(X){Z+=H,X=!1;continue}if(H==="\\"&&!Y){Z+=H,X=!0;continue}if(H==="'"&&!J){Y=!Y,Z+=H;continue}if(H==='"'&&!Y){J=!J,Z+=H;continue}if(Y||J){Z+=H;continue}if(H==="|"){if(V+1<$.length&&$[V+1]==="|"){if(Z.trim())W.push(Z.trim());Z="",V++;continue}return null}if(H===">"||H==="<")return null;if(H==="&"&&V+1<$.length&&$[V+1]==="&"){if(Z.trim())W.push(Z.trim());Z="",V++;continue}if(H==="&")return null;if(H===";"){if(Z.trim())W.push(Z.trim());Z="";continue}Z+=H}if(Z.trim())W.push(Z.trim());return W.length>0?W:null}function Q5($){let W=[],Z="",Y=!1,J=!1,X=!1;for(let V=0;V<$.length;V++){let H=$[V];if(X){Z+=H,X=!1;continue}if(H==="\\"&&!Y){if(X=!0,J){let B=$[V+1];if(B&&'$`"\\'.includes(B))continue;Z+=H,X=!1}continue}if(H==="'"&&!J){Y=!Y;continue}if(H==='"'&&!Y){J=!J;continue}if(!Y&&!J&&/[ \t]/.test(H)){if(Z)W.push(Z),Z="";continue}Z+=H}if(Z)W.push(Z);return W}var h1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},F$={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},U5={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Q4={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},U4=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:h1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:h1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:F$,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:U5},{pattern:/^git\s+(status|branch|remote)/i,config:F$},{pattern:/^git\s+(log|diff|show)/i,config:U5},{pattern:/^(ls|dir|tree)\s+/i,config:F$,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:F$,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:F$,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:h1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:h1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:F$,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:F$,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class Y1{static getConfigForCommand($){for(let{pattern:W,config:Z,summaryTemplate:Y}of U4)if(W.test($))return{config:Z,summaryTemplate:Y};return{config:Q4}}static truncate($,W){let{config:Z,summaryTemplate:Y}=this.getConfigForCommand(W);return this.truncateWithConfig($,Z,Y)}static truncateWithConfig($,W,Z){let Y=$.length,J=$.split(`
568
- `),X=J.length;if(X<=W.maxLines&&Y<=W.maxChars)return{content:$,truncated:!1,originalLines:X,originalChars:Y};let V=J.slice(0,W.keepHead),H=J.slice(-W.keepTail),B=X-W.keepHead-W.keepTail,K=V.join(`
569
- `);if(K+=`
565
+ Use the relative_path values above for Read/Edit operations.`;else F=`No files found matching "${Z}"`;return{success:!0,llmContent:F,metadata:{...G,matches:E,summary:`找到 ${q.length} 个匹配 "${Z}" 的文件`}}}catch(U){let Q=U;if(Q.name==="AbortError")return{success:!1,llmContent:"File search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${Q.message}`,metadata:{summary:`搜索失败: ${Q.message}`},error:{type:"execution_error",message:Q.message,details:Q}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function g9($,W,Z,Y){let J=Y.getIgnorePatterns(),X=[],V=!1;return await new Promise((H,K)=>{if(Z.signal.aborted){K(n2("文件搜索被用户中止"));return}let B=h9.stream(W,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:Z.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!Z.includeDirectories,ignore:J}),U=!1,Q=null,q=()=>{if(Q){if(Z.signal.removeEventListener)Z.signal.removeEventListener("abort",Q);else if("onabort"in Z.signal)Z.signal.onabort=null;Q=null}},w=()=>{if(!U)U=!0,V=!0,B.destroy(),q(),H({matches:X,wasTruncated:V})},E=(G)=>{if(Z.signal.aborted){if(!U)U=!0,B.destroy(n2("文件搜索被用户中止"));return}if(X.length>=Z.maxResults){w();return}let F=G.path.replace(/\\/g,"/"),z=p9($,F);if(Y.shouldIgnore(F))return;let O=G.stats?G.stats.isDirectory():!1;if(O&&Y.shouldIgnoreDirectory(F))return;let _=G.stats&&G.stats.isFile()?G.stats.size:void 0,R=G.stats?G.stats.mtime.toISOString():void 0;if(X.push({path:z,relative_path:F,is_directory:O,size:_,modified:R}),X.length>=Z.maxResults)w()};if(B.on("data",E),Q=()=>{if(!U)U=!0,q(),B.destroy(n2("文件搜索被用户中止"))},Z.signal.addEventListener)Z.signal.addEventListener("abort",Q);else if("onabort"in Z.signal)Z.signal.onabort=Q;B.once("error",(G)=>{if(!U)U=!0,q(),K(G)}),B.once("end",()=>{if(!U)U=!0,q(),H({matches:X,wasTruncated:V})})})}function m9($){return $.sort((W,Z)=>{if(W.is_directory!==Z.is_directory)return W.is_directory?1:-1;if(W.modified&&Z.modified)return new Date(Z.modified).getTime()-new Date(W.modified).getTime();return W.relative_path.localeCompare(Z.relative_path)})}import{execSync as s2,spawn as t2}from"child_process";import{existsSync as o2}from"fs";import{readdir as c9,readFile as l9}from"fs/promises";import{join as i9,relative as r9}from"path";import n9 from"picomatch";import{z as o0}from"zod";function a9(){let{platform:$,arch:W}=process,Z={"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"},Y=`${$}-${W}`,J=Z[Y];if(!J)return null;try{let X=new URL("../../../../vendor/ripgrep/"+J,import.meta.url).pathname;if(o2(X))return X}catch{}return null}function X5(){try{let W=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",Z=s2(W,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(Z)return Z}catch{}let $=a9();if($&&o2($))return $;try{let W=Q$("@vscode/ripgrep");if(W?.rgPath&&o2(W.rgPath))return W.rgPath}catch{}return null}async function o9($){try{return s2("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function s9(){try{return s2("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function t9($,W,Z,Y){let J=X5();if(!J)throw Error("ripgrep not available");return new Promise((X,V)=>{let H=t2(J,$,{stdio:["pipe","pipe","pipe"]}),K="",B="";H.stdout.on("data",(Q)=>{K+=Q.toString()}),H.stderr.on("data",(Q)=>{B+=Q.toString()}),H.on("close",(Q)=>{X({stdout:K,stderr:B,exitCode:Q||0})}),H.on("error",(Q)=>{V(Q)});let U=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Z.addEventListener("abort",U),H.on("close",()=>{Z.removeEventListener("abort",U)})})}async function e9($,W,Z,Y){let J=["grep","-n"];if(Z.caseInsensitive)J.push("-i");if(Z.contextLines!==void 0)J.push(`-C${Z.contextLines}`);if(J.push("-e",$),Z.glob)J.push("--",Z.glob);return new Promise((X,V)=>{let H=t2("git",J,{cwd:W,stdio:["pipe","pipe","pipe"]}),K="",B="";H.stdout.on("data",(Q)=>{K+=Q.toString()}),H.stderr.on("data",(Q)=>{B+=Q.toString()}),H.on("close",(Q)=>{X({stdout:K,stderr:B,exitCode:Q||0})}),H.on("error",(Q)=>{V(Q)});let U=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Y.addEventListener("abort",U),H.on("close",()=>{Y.removeEventListener("abort",U)})})}async function $4($,W,Z,Y){let J=["-rn"];if(Z.caseInsensitive)J.push("-i");if(Z.contextLines!==void 0)J.push(`-C${Z.contextLines}`);for(let X of G$)J.push("--exclude-dir="+X.replace(/^\./,""));return J.push("-e",$,W),new Promise((X,V)=>{let H=t2("grep",J,{stdio:["pipe","pipe","pipe"]}),K="",B="";H.stdout.on("data",(Q)=>{K+=Q.toString()}),H.stderr.on("data",(Q)=>{B+=Q.toString()}),H.on("close",(Q)=>{X({stdout:K,stderr:B,exitCode:Q||0})}),H.on("error",(Q)=>{V(Q)});let U=()=>{H.kill("SIGTERM"),V(Error("搜索被用户中止"))};Y.addEventListener("abort",U),H.on("close",()=>{Y.removeEventListener("abort",U)})})}async function W4($,W,Z,Y){let J=[],X=new RegExp($,Z.caseInsensitive?"gi":"g"),V=await Z4(W,Y),H=0;for(let K of V){if(Y.throwIfAborted(),V5(K))continue;if(Z.glob&&!Y4(K,Z.glob))continue;try{(await l9(K,"utf-8")).split(`
566
+ `).forEach((Q,q)=>{if(X.test(Q))J.push({file_path:r9(W,K),line_number:q+1,content:Q})}),H++}catch(B){continue}}return{matches:J,totalFiles:H}}async function Z4($,W){let Z=[];async function Y(J){W.throwIfAborted();try{let X=await c9(J,{withFileTypes:!0});for(let V of X){W.throwIfAborted();let H=i9(J,V.name);if(V.isDirectory()){if(!V5(H))await Y(H)}else if(V.isFile())Z.push(H)}}catch(X){}}return await Y($),Z}function V5($){for(let W of G$)if($.includes(W))return!0;return!1}function Y4($,W){return n9(W)($)}function J4($){let W=[];if($.case_insensitive)W.push("-i");if($.multiline)W.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":W.push("-l");break;case"count":W.push("-c");break;case"content":if($.line_numbers)W.push("-n");break}if($.context!==void 0&&$.output_mode==="content")W.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")W.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")W.push("-A",$.context_after.toString())}if($.type)W.push("--type",$.type);for(let Z of G$)W.push("--glob",`!${Z}/**`);if($.glob)W.push("--glob",$.glob);if($.head_limit!==void 0){let Z=($.offset??0)+$.head_limit;W.push("-m",Z.toString())}return W.push($.pattern),W.push($.path),W}function X4($,W){if(!$.trim())return[];let Z=$.trim().split(`
567
+ `),Y=[];switch(W){case"files_with_matches":return Z.map((J)=>({file_path:J.trim()}));case"count":return Z.map((J)=>{let[X,V]=J.split(":");return{file_path:X,count:parseInt(V,10)}});case"content":for(let J of Z){let X=V4(J);if(X)Y.push(X)}return Y;default:return[]}}function V4($){let W=$.indexOf(":");if(W===-1)return null;let Z=$.substring(0,W),Y=$.substring(W+1),J=Y.indexOf(":");if(J!==-1&&/^\d+$/.test(Y.substring(0,J))){let X=parseInt(Y.substring(0,J),10),V=Y.substring(J+1);return{file_path:Z,line_number:X,content:V}}else return{file_path:Z,content:Y}}var e2=N({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:o0.object({pattern:I.pattern({description:"The regular expression pattern to search for in file contents"}),path:o0.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:o0.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:o0.string().optional().describe("File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types"),output_mode:o0.enum(["content","files_with_matches","count"]).default("files_with_matches").describe('Output mode: "content" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), "files_with_matches" shows file paths (supports head_limit), "count" shows match counts (supports head_limit). Defaults to "files_with_matches"'),"-i":o0.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":o0.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":I.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":I.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":I.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:I.positiveInt().optional().describe('Limit output to first N lines/entries, equivalent to "| head -N". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults based on "cap" experiment value: 0 (unlimited), 20, or 100'),offset:I.nonNegativeInt().optional().describe('Skip first N lines/entries before applying head_limit, equivalent to "| tail -n +N | head -N". Works across all output modes. Defaults to 0'),multiline:o0.boolean().default(!1).describe("Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false")}),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($,W){let{pattern:Z,path:Y,glob:J,type:X,output_mode:V,"-i":H,"-n":K=!0,"-B":B,"-A":U,"-C":Q,head_limit:q,offset:w,multiline:E}=$,{updateOutput:G}=W,F=W.signal??new AbortController().signal,z=Y??W.workspaceRoot??D();try{G?.(`使用智能搜索策略查找模式 "${Z}"...`);let O=null,_="ripgrep",R=[],j=X5();if(j)try{G?.(`使用 ripgrep (${j})`);let b=J4({pattern:Z,path:z,glob:J,type:X,output_mode:V,case_insensitive:H??!1,line_numbers:K,context_before:B,context_after:U,context:Q,head_limit:q,offset:w,multiline:E??!1});O=await t9(b,V,F,G),_="ripgrep"}catch{G?.("[WARN] ripgrep 失败,尝试降级策略..."),O=null}if(!O&&await o9(z))try{G?.("使用 git grep"),O=await e9(Z,z,{caseInsensitive:H??!1,glob:J,contextLines:Q},F),_="git-grep"}catch{G?.("[WARN] git grep 失败,继续尝试其他策略..."),O=null}if(!O&&s9())try{G?.("使用系统 grep"),O=await $4(Z,z,{caseInsensitive:H??!1,contextLines:Q},F),_="system-grep"}catch{G?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),O=null}if(!O)G?.("使用纯 JavaScript 搜索实现"),R=(await W4(Z,z,{caseInsensitive:H??!1,glob:J,multiline:E??!1},F)).matches,_="fallback",O={stdout:"",stderr:"",exitCode:0};else R=X4(O.stdout,V);let A=R.length;if(w!==void 0&&w>0)R=R.slice(w);if(q!==void 0&&R.length>q)R=R.slice(0,q);let L={search_pattern:Z,search_path:z,output_mode:V,case_insensitive:H??!1,total_matches:R.length,original_total:A,offset:w,head_limit:q,strategy:_,exit_code:O?.exitCode};if(O&&O.exitCode!==0&&O.stderr)return{success:!1,llmContent:`Search execution failed: ${O.stderr}`,metadata:{...L,summary:`搜索失败: ${O.stderr}`},error:{type:"execution_error",message:O.stderr}};return{success:!0,llmContent:R,metadata:{...L,summary:R.length>0?`搜索 "${Z}" 找到 ${R.length} 个文件`:`搜索 "${Z}" 未找到匹配`}}}catch(O){let _=O;if(_.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${_.message}`,metadata:{summary:`搜索失败: ${_.message}`},error:{type:"execution_error",message:_.message,details:_}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{isAbsolute as q4,resolve as w4}from"node:path";import{z as $W}from"zod";var H4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),B4=/^(LD_.+|DYLD_.+|PATH)$/,H5=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function E$($){let W=$;while(!0){let Z=W.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let Y=Z[1],J=Z[2],X=Y.match(H5);if(!X)break;let V=X[1];if(!H4.has(V))break;W=J}return W}function B5($){let W=$;while(!0){let Z=W.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let Y=Z[1],J=Z[2],X=Y.match(H5);if(!X)break;let V=X[1];if(B4.test(V))break;W=J}return W}var K4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function s0($){let W=$,Z=!0;while(Z){Z=!1;for(let Y of K4){let J=W.match(Y);if(J){W=W.slice(J[0].length),Z=!0;break}}if(W.startsWith("-- "))W=W.slice(3),Z=!0}return W}function K5($){let W=[],Z="",Y=!1,J=!1,X=!1;for(let V=0;V<$.length;V++){let H=$[V];if(X){Z+=H,X=!1;continue}if(H==="\\"&&!Y){Z+=H,X=!0;continue}if(H==="'"&&!J){Y=!Y,Z+=H;continue}if(H==='"'&&!Y){J=!J,Z+=H;continue}if(Y||J){Z+=H;continue}if(H==="|"){if(V+1<$.length&&$[V+1]==="|"){if(Z.trim())W.push(Z.trim());Z="",V++;continue}return null}if(H===">"||H==="<")return null;if(H==="&"&&V+1<$.length&&$[V+1]==="&"){if(Z.trim())W.push(Z.trim());Z="",V++;continue}if(H==="&")return null;if(H===";"){if(Z.trim())W.push(Z.trim());Z="";continue}Z+=H}if(Z.trim())W.push(Z.trim());return W.length>0?W:null}function U5($){let W=[],Z="",Y=!1,J=!1,X=!1;for(let V=0;V<$.length;V++){let H=$[V];if(X){Z+=H,X=!1;continue}if(H==="\\"&&!Y){if(X=!0,J){let K=$[V+1];if(K&&'$`"\\'.includes(K))continue;Z+=H,X=!1}continue}if(H==="'"&&!J){Y=!Y;continue}if(H==='"'&&!Y){J=!J;continue}if(!Y&&!J&&/[ \t]/.test(H)){if(Z)W.push(Z),Z="";continue}Z+=H}if(Z)W.push(Z);return W}var h1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},F$={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},Q5={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},U4={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Q4=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:h1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:h1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:F$,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:Q5},{pattern:/^git\s+(status|branch|remote)/i,config:F$},{pattern:/^git\s+(log|diff|show)/i,config:Q5},{pattern:/^(ls|dir|tree)\s+/i,config:F$,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:F$,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:F$,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:h1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:h1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:F$,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:F$,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class Y1{static getConfigForCommand($){for(let{pattern:W,config:Z,summaryTemplate:Y}of Q4)if(W.test($))return{config:Z,summaryTemplate:Y};return{config:U4}}static truncate($,W){let{config:Z,summaryTemplate:Y}=this.getConfigForCommand(W);return this.truncateWithConfig($,Z,Y)}static truncateWithConfig($,W,Z){let Y=$.length,J=$.split(`
568
+ `),X=J.length;if(X<=W.maxLines&&Y<=W.maxChars)return{content:$,truncated:!1,originalLines:X,originalChars:Y};let V=J.slice(0,W.keepHead),H=J.slice(-W.keepTail),K=X-W.keepHead-W.keepTail,B=V.join(`
569
+ `);if(B+=`
570
570
 
571
- ... (${B} lines truncated, showing first ${W.keepHead} and last ${W.keepTail} of ${X} total) ...
571
+ ... (${K} lines truncated, showing first ${W.keepHead} and last ${W.keepTail} of ${X} total) ...
572
572
 
573
- `,K+=H.join(`
574
- `),K.length>W.maxChars){let U=Math.floor(W.maxChars/2)-50,q=K.slice(0,U),w=K.slice(-U);K=`${q}
573
+ `,B+=H.join(`
574
+ `),B.length>W.maxChars){let Q=Math.floor(W.maxChars/2)-50,q=B.slice(0,Q),w=B.slice(-Q);B=`${q}
575
575
 
576
576
  ... (content truncated to ${W.maxChars} chars) ...
577
577
 
578
- ${w}`}let Q=W.summarize&&Z?Z(X,Y):void 0;if(Q)K+=`
578
+ ${w}`}let U=W.summarize&&Z?Z(X,Y):void 0;if(U)B+=`
579
579
 
580
- [Summary: ${Q}]`;return{content:K,truncated:!0,originalLines:X,originalChars:Y,summary:Q}}static truncateForLLM($,W,Z){let Y=this.truncate($,Z),J=this.truncate(W,Z),X;if(Y.truncated||J.truncated){let V=[];if(Y.truncated)V.push(`stdout: ${Y.originalLines} lines -> ${Y.content.split(`
580
+ [Summary: ${U}]`;return{content:B,truncated:!0,originalLines:X,originalChars:Y,summary:U}}static truncateForLLM($,W,Z){let Y=this.truncate($,Z),J=this.truncate(W,Z),X;if(Y.truncated||J.truncated){let V=[];if(Y.truncated)V.push(`stdout: ${Y.originalLines} lines -> ${Y.content.split(`
581
581
  `).length} lines`);if(J.truncated)V.push(`stderr: ${J.originalLines} lines -> ${J.content.split(`
582
582
  `).length} lines`);X=`Output truncated: ${V.join(", ")}`}return{stdout:Y.content,stderr:J.content,truncationInfo:X}}static shouldTruncate($,W){let{config:Z}=this.getConfigForCommand(W);return $.split(`
583
583
  `).length>Z.maxLines||$.length>Z.maxChars}static getStats($){return{lines:$.split(`
584
- `).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var WW=j({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,schema:$W.object({command:I.command({description:"Bash command to execute"}),timeout:I.timeout(1000,300000,30000),cwd:$W.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:I.environment(),run_in_background:$W.boolean().default(!1).describe("Run in background (suitable for long-running commands)")}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
584
+ `).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var WW=N({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,schema:$W.object({command:I.command({description:"Bash command to execute"}),timeout:I.timeout(1000,300000,30000),cwd:$W.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:I.environment(),run_in_background:$W.boolean().default(!1).describe("Run in background (suitable for long-running commands)")}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
585
585
 
586
586
  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.
587
587
 
@@ -597,17 +597,17 @@ Before executing commands:
597
597
  * cd "/Users/name/My Documents" (correct)
598
598
  * cd /Users/name/My Documents (incorrect - will fail)
599
599
  * python "/path/with spaces/script.py" (correct)
600
- * python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,W){let{command:Z,timeout:Y=30000,cwd:J,env:X,run_in_background:V=!1}=$,{updateOutput:H}=W,B=W.signal??new AbortController().signal,K=W.workspaceRoot??D(),Q=J===void 0?K:q4(J)?J:w4(K,J);try{H?.(`Executing Bash command: ${Z}`);let U=W.worktreeActive?await FZ.prepare({command:Z,cwd:Q,workspaceRoot:K,signal:B}):void 0;if(V)return G4(Z,Q,X,W.sessionId,U);if(r0()&&!U)return H?.("通过 IDE 终端执行命令..."),E4(Z,Q,X,Y,B,H);else return F4(Z,Q,X,Y,B,H,U)}catch(U){let q=U;if(q.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};if(U instanceof Q$||U instanceof x$)return{success:!1,llmContent:`Workspace sandbox blocked Bash execution: ${q.message}. The command was not started.`,error:{type:"permission_denied",message:q.message},metadata:{command:Z,sandbox_required:!0,sandboxed:!1,summary:"Workspace sandbox unavailable; command not started"}};return{success:!1,llmContent:`Command execution failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let Z=E$(s0($.command.trim())).split(/\s+/);if(Z.length===1)return Z[0];if(["run","exec","test","start","build","dev"].includes(Z[1])){if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}});function G4($,W,Z,Y,J){if(!Y)return J?.cleanup(),{success:!1,llmContent:"Background Bash requires an active session",error:{type:"validation_error",message:"后台命令缺少 session 上下文"},metadata:{summary:"后台命令启动失败: 缺少 session"}};let V=$0.getInstance().startBackgroundProcess({command:$,sessionId:Y,cwd:W||D(),env:Z,sandboxedCommand:J}),B=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,K={command:$,background:!0,pid:V.pid??0,bash_id:V.id,shell_id:V.id,message:"命令已在后台启动",sandboxed:Boolean(J),summary:B};return{success:!0,llmContent:{command:$,background:!0,pid:V.pid,bash_id:V.id,shell_id:V.id},metadata:K}}function q5($,W,Z,Y){let J=$===null?`Command terminated${W?` by signal ${W}`:""}`:`Command exited with code ${$}`,X=[Y?`stderr:
600
+ * python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the TaskOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,W){let{command:Z,timeout:Y=30000,cwd:J,env:X,run_in_background:V=!1}=$,{updateOutput:H}=W,K=W.signal??new AbortController().signal,B=W.workspaceRoot??D(),U=J===void 0?B:q4(J)?J:w4(B,J);try{H?.(`Executing Bash command: ${Z}`);let Q=W.worktreeActive?await FZ.prepare({command:Z,cwd:U,workspaceRoot:B,signal:K}):void 0;if(V)return G4(Z,U,X,W.sessionId,Q);if(r0()&&!Q)return H?.("通过 IDE 终端执行命令..."),E4(Z,U,X,Y,K,H);else return F4(Z,U,X,Y,K,H,Q)}catch(Q){let q=Q;if(q.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};if(Q instanceof U$||Q instanceof x$)return{success:!1,llmContent:`Workspace sandbox blocked Bash execution: ${q.message}. The command was not started.`,error:{type:"permission_denied",message:q.message},metadata:{command:Z,sandbox_required:!0,sandboxed:!1,summary:"Workspace sandbox unavailable; command not started"}};return{success:!1,llmContent:`Command execution failed: ${q.message}`,error:{type:"execution_error",message:q.message,details:q}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let Z=E$(s0($.command.trim())).split(/\s+/);if(Z.length===1)return Z[0];if(["run","exec","test","start","build","dev"].includes(Z[1])){if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}});function G4($,W,Z,Y,J){if(!Y)return J?.cleanup(),{success:!1,llmContent:"Background Bash requires an active session",error:{type:"validation_error",message:"后台命令缺少 session 上下文"},metadata:{summary:"后台命令启动失败: 缺少 session"}};let V=$0.getInstance().startBackgroundProcess({command:$,sessionId:Y,cwd:W||D(),env:Z,sandboxedCommand:J}),K=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,B={command:$,background:!0,pid:V.pid??0,bash_id:V.id,shell_id:V.id,message:"命令已在后台启动",sandboxed:Boolean(J),summary:K};return{success:!0,llmContent:{command:$,background:!0,pid:V.pid,bash_id:V.id,shell_id:V.id},metadata:B}}function q5($,W,Z,Y){let J=$===null?`Command terminated${W?` by signal ${W}`:""}`:`Command exited with code ${$}`,X=[Y?`stderr:
601
601
  ${Y}`:"",Z?`stdout:
602
602
  ${Z}`:""].filter(Boolean);return X.length>0?`${J}
603
603
  ${X.join(`
604
- `)}`:J}async function E4($,W,Z,Y,J,X){let V=Date.now();try{let B=await hZ().execute($,{cwd:W||D(),env:Z,timeout:Y,signal:J,onOutput:(G)=>{X?.(G)}}),K=Date.now()-V;if(J.aborted||B.error==="Command was aborted"||B.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:B.stdout,stderr:B.stderr,execution_time:K}};if(B.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:B.stdout,stderr:B.stderr,execution_time:K}};let Q=$.length>30?`${$.substring(0,30)}...`:$,U=B.exitCode===0?`执行命令成功 (${K}ms): ${Q}`:`执行命令完成 (退出码 ${B.exitCode}, ${K}ms): ${Q}`,q={command:$,execution_time:K,exit_code:B.exitCode,stdout_length:B.stdout.length,stderr_length:B.stderr.length,has_stderr:B.stderr.length>0,acp_mode:!0,summary:U},w=Y1.truncateForLLM(B.stdout.trim(),B.stderr.trim(),$),E={stdout:w.stdout,stderr:w.stderr,execution_time:K,exit_code:B.exitCode,...w.truncationInfo&&{truncation_info:w.truncationInfo}};return{success:B.success,llmContent:E,...B.success?{}:{error:{type:"execution_error",message:q5(B.exitCode,void 0,w.stdout,w.stderr)}},metadata:q}}catch(H){let B=H,K=Date.now()-V;return{success:!1,llmContent:`Command execution failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:B},metadata:{command:$,execution_time:K,error:B.message}}}}async function F4($,W,Z,Y,J,X,V){return new Promise((H)=>{let B=Date.now(),K="",Q="",U=!1,q=V?.executable??"bash",w=V?.args??["-c",$],{child:E,processTree:G}=C$(q,w,{cwd:W||D(),env:{...process.env,...Z,...V?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),F,R=()=>{return F??=G.terminate(),F};E.stdout?.on("data",(z)=>{K+=z.toString()}),E.stderr?.on("data",(z)=>{Q+=z.toString()});let O=setTimeout(()=>{U=!0,R()},Y),_=()=>{R(),clearTimeout(O)};if(J.addEventListener)J.addEventListener("abort",_);else if("onabort"in J)J.onabort=_;if(J.aborted)_();E.on("close",async(z,N)=>{if(V?.cleanup(),clearTimeout(O),J.removeEventListener)J.removeEventListener("abort",_);else if("onabort"in J)J.onabort=null;let A=Date.now()-B;if(U||J.aborted)await R();if(U){H({success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,sandboxed:Boolean(V),timeout:!0,stdout:K,stderr:Q,execution_time:A}});return}if(J.aborted){H({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,sandboxed:Boolean(V),aborted:!0,stdout:K,stderr:Q,execution_time:A}});return}if(V&&L1(z,Q)){H({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:Q.trim()||"Workspace sandbox failed to start"},metadata:{command:$,sandbox_required:!0,sandboxed:!1,execution_time:A,exit_code:z,stderr:Q,summary:"Workspace sandbox failed closed"}});return}let k=$.length>30?`${$.substring(0,30)}...`:$,M=z===0?`执行命令成功 (${A}ms): ${k}`:`执行命令完成 (退出码 ${z}, ${A}ms): ${k}`,y={command:$,execution_time:A,exit_code:z,signal:N,stdout_length:K.length,stderr_length:Q.length,has_stderr:Q.length>0,sandboxed:Boolean(V),summary:M},x=Y1.truncateForLLM(K.trim(),Q.trim(),$),g={stdout:x.stdout,stderr:x.stderr,execution_time:A,exit_code:z,signal:N,...x.truncationInfo&&{truncation_info:x.truncationInfo}},c0=z===0;H({success:c0,llmContent:g,...c0?{}:{error:{type:"execution_error",message:q5(z,N,x.stdout,x.stderr)}},metadata:y})}),E.on("error",(z)=>{if(V?.cleanup(),clearTimeout(O),J.removeEventListener)J.removeEventListener("abort",_);else if("onabort"in J)J.onabort=null;H({success:!1,llmContent:`Command execution failed: ${z.message}`,error:{type:"execution_error",message:z.message,details:z}})})})}import{z as w5}from"zod";var ZW=j({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:w5.object({shell_id:w5.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
604
+ `)}`:J}async function E4($,W,Z,Y,J,X){let V=Date.now();try{let K=await hZ().execute($,{cwd:W||D(),env:Z,timeout:Y,signal:J,onOutput:(G)=>{X?.(G)}}),B=Date.now()-V;if(J.aborted||K.error==="Command was aborted"||K.error==="Command was terminated")return{success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:K.stdout,stderr:K.stderr,execution_time:B}};if(K.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K.stdout,stderr:K.stderr,execution_time:B}};let U=$.length>30?`${$.substring(0,30)}...`:$,Q=K.exitCode===0?`执行命令成功 (${B}ms): ${U}`:`执行命令完成 (退出码 ${K.exitCode}, ${B}ms): ${U}`,q={command:$,execution_time:B,exit_code:K.exitCode,stdout_length:K.stdout.length,stderr_length:K.stderr.length,has_stderr:K.stderr.length>0,acp_mode:!0,summary:Q},w=Y1.truncateForLLM(K.stdout.trim(),K.stderr.trim(),$),E={stdout:w.stdout,stderr:w.stderr,execution_time:B,exit_code:K.exitCode,...w.truncationInfo&&{truncation_info:w.truncationInfo}};return{success:K.success,llmContent:E,...K.success?{}:{error:{type:"execution_error",message:q5(K.exitCode,void 0,w.stdout,w.stderr)}},metadata:q}}catch(H){let K=H,B=Date.now()-V;return{success:!1,llmContent:`Command execution failed: ${K.message}`,error:{type:"execution_error",message:K.message,details:K},metadata:{command:$,execution_time:B,error:K.message}}}}async function F4($,W,Z,Y,J,X,V){return new Promise((H)=>{let K=Date.now(),B="",U="",Q=!1,q=V?.executable??"bash",w=V?.args??["-c",$],{child:E,processTree:G}=C$(q,w,{cwd:W||D(),env:{...process.env,...Z,...V?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]}),F,z=()=>{return F??=G.terminate(),F};E.stdout?.on("data",(R)=>{B+=R.toString()}),E.stderr?.on("data",(R)=>{U+=R.toString()});let O=setTimeout(()=>{Q=!0,z()},Y),_=()=>{z(),clearTimeout(O)};if(J.addEventListener)J.addEventListener("abort",_);else if("onabort"in J)J.onabort=_;if(J.aborted)_();E.on("close",async(R,j)=>{if(V?.cleanup(),clearTimeout(O),J.removeEventListener)J.removeEventListener("abort",_);else if("onabort"in J)J.onabort=null;let A=Date.now()-K;if(Q||J.aborted)await z();if(Q){H({success:!1,llmContent:`Command execution timed out (${Y}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,sandboxed:Boolean(V),timeout:!0,stdout:B,stderr:U,execution_time:A}});return}if(J.aborted){H({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,sandboxed:Boolean(V),aborted:!0,stdout:B,stderr:U,execution_time:A}});return}if(V&&L1(R,U)){H({success:!1,llmContent:"Workspace sandbox could not start, so the Bash command was not executed.",error:{type:"permission_denied",message:U.trim()||"Workspace sandbox failed to start"},metadata:{command:$,sandbox_required:!0,sandboxed:!1,execution_time:A,exit_code:R,stderr:U,summary:"Workspace sandbox failed closed"}});return}let L=$.length>30?`${$.substring(0,30)}...`:$,b=R===0?`执行命令成功 (${A}ms): ${L}`:`执行命令完成 (退出码 ${R}, ${A}ms): ${L}`,y={command:$,execution_time:A,exit_code:R,signal:j,stdout_length:B.length,stderr_length:U.length,has_stderr:U.length>0,sandboxed:Boolean(V),summary:b},x=Y1.truncateForLLM(B.trim(),U.trim(),$),g={stdout:x.stdout,stderr:x.stderr,execution_time:A,exit_code:R,signal:j,...x.truncationInfo&&{truncation_info:x.truncationInfo}},c0=R===0;H({success:c0,llmContent:g,...c0?{}:{error:{type:"execution_error",message:q5(R,j,x.stdout,x.stderr)}},metadata:y})}),E.on("error",(R)=>{if(V?.cleanup(),clearTimeout(O),J.removeEventListener)J.removeEventListener("abort",_);else if("onabort"in J)J.onabort=null;H({success:!1,llmContent:`Command execution failed: ${R.message}`,error:{type:"execution_error",message:R.message,details:R}})})})}import{z as w5}from"zod";var ZW=N({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:w5.object({shell_id:w5.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
605
605
  - Kills a running background bash shell by its ID
606
606
  - Takes a shell_id parameter identifying the shell to kill
607
607
  - Returns a success or failure status
608
608
  - Use this tool when you need to terminate a long-running shell
609
609
  - Shell IDs can be found using the /tasks command
610
- `},async execute($,W){let Z=$0.getInstance(),Y=W.sessionId?await Z.kill($.shell_id,W.sessionId):void 0;if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!Y.success&&!Y.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...Y,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},metadata:{...Y,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as v0}from"zod";var z4=v0.object({label:v0.string().describe("The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."),description:v0.string().describe("Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.")}),R4=v0.object({question:v0.string().describe('The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'),header:v0.string().max(12).describe('Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'),multiSelect:v0.boolean().describe("Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."),options:v0.array(z4).min(2).max(4).describe('The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Other" option, that will be provided automatically.')}),O4=v0.object({questions:v0.array(R4).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),YW=j({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:O4,description:{short:"Ask user questions to gather preferences or clarify requirements",long:`Use this tool when you need to ask the user questions during execution. This allows you to:
610
+ `},async execute($,W){let Z=$0.getInstance(),Y=W.sessionId?await Z.kill($.shell_id,W.sessionId):void 0;if(!Y)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!Y.success&&!Y.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...Y,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:Y.status,already_exited:Y.alreadyExited,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal},metadata:{...Y,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as v0}from"zod";var z4=v0.object({label:v0.string().describe("The display text for this option that the user will see and select. Should be concise (1-5 words) and clearly describe the choice."),description:v0.string().describe("Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.")}),R4=v0.object({question:v0.string().describe('The complete question to ask the user. Should be clear, specific, and end with a question mark. Example: "Which library should we use for date formatting?" If multiSelect is true, phrase it accordingly, e.g. "Which features do you want to enable?"'),header:v0.string().max(12).describe('Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'),multiSelect:v0.boolean().describe("Set to true to allow the user to select multiple options instead of just one. Use when choices are not mutually exclusive."),options:v0.array(z4).min(2).max(4).describe('The available choices for this question. Must have 2-4 options. Each option should be a distinct, mutually exclusive choice (unless multiSelect is enabled). There should be no "Other" option, that will be provided automatically.')}),O4=v0.object({questions:v0.array(R4).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),YW=N({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:O4,description:{short:"Ask user questions to gather preferences or clarify requirements",long:`Use this tool when you need to ask the user questions during execution. This allows you to:
611
611
  1. Gather user preferences or requirements
612
612
  2. Clarify ambiguous instructions
613
613
  3. Get decisions on implementation choices as you work
@@ -618,7 +618,7 @@ Usage notes:
618
618
  - Use multiSelect: true to allow multiple answers to be selected for a question
619
619
  - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label`},async execute($,W){if(W.confirmationHandler)try{let Z=await W.confirmationHandler.requestConfirmation({type:"askUserQuestion",kind:"readonly",message:"Please answer the following questions:",questions:$.questions});if(!Z.approved)return{success:!0,llmContent:"User cancelled the question prompt without providing answers.",metadata:{cancelled:!0,summary:"用户取消了问题"}};if(Z.answers&&Object.keys(Z.answers).length>0)return{success:!0,llmContent:`User answers:
620
620
  ${Object.entries(Z.answers).map(([J,X])=>{let V=Array.isArray(X)?X.join(", "):X;return`${J}: ${V}`}).join(`
621
- `)}`,metadata:{answers:Z.answers,summary:"用户已回答问题"}};return{success:!0,llmContent:"The question was approved but no answers were collected. This typically happens in IDE/ACP sessions where structured question UI is not available. Please ask the user directly in your response or make reasonable assumptions based on context.",metadata:{acpMode:!0,noAnswersCollected:!0,summary:"ACP 模式:无法收集答案"}}}catch(Z){return{success:!1,llmContent:`Failed to ask user questions: ${Z instanceof Error?Z.message:"Unknown error"}`,error:{type:"execution_error",message:"Failed to display questions"},metadata:{summary:"问题显示失败"}}}return{success:!1,llmContent:"No confirmation handler available. Cannot ask user questions in non-interactive mode.",error:{type:"execution_error",message:"No confirmation handler available"},metadata:{summary:"非交互模式,无法提问"}}}});import{z as JW}from"zod";var XW=j({name:"Skill",displayName:"Skill",kind:"execute",isConcurrencySafe:!1,schema:JW.object({skill:JW.string().describe('The skill name. E.g., "commit-message" or "code-review"'),args:JW.string().optional().describe("Optional arguments for the skill")}),description:{short:"Execute a skill within the main conversation",long:`Execute a skill within the main conversation
621
+ `)}`,metadata:{answers:Z.answers,summary:"用户已回答问题"}};return{success:!0,llmContent:"The question was approved but no answers were collected. This typically happens in IDE/ACP sessions where structured question UI is not available. Please ask the user directly in your response or make reasonable assumptions based on context.",metadata:{acpMode:!0,noAnswersCollected:!0,summary:"ACP 模式:无法收集答案"}}}catch(Z){return{success:!1,llmContent:`Failed to ask user questions: ${Z instanceof Error?Z.message:"Unknown error"}`,error:{type:"execution_error",message:"Failed to display questions"},metadata:{summary:"问题显示失败"}}}return{success:!1,llmContent:"No confirmation handler available. Cannot ask user questions in non-interactive mode.",error:{type:"execution_error",message:"No confirmation handler available"},metadata:{summary:"非交互模式,无法提问"}}}});import{z as JW}from"zod";var XW=N({name:"Skill",displayName:"Skill",kind:"execute",isConcurrencySafe:!1,schema:JW.object({skill:JW.string().describe('The skill name. E.g., "commit-message" or "code-review"'),args:JW.string().optional().describe("Optional arguments for the skill")}),description:{short:"Execute a skill within the main conversation",long:`Execute a skill within the main conversation
622
622
 
623
623
  <skills_instructions>
624
624
  When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
@@ -637,7 +637,7 @@ Important:
637
637
  <available_skills>
638
638
 
639
639
  </available_skills>
640
- `},async execute($,W){let{skill:Z}=$,Y=Q0();if(!Y.has(Z))return{success:!1,llmContent:`Skill "${Z}" not found. Available skills: ${Y.getAll().map((H)=>H.name).join(", ")||"none"}`,error:{type:"validation_error",message:`Skill "${Z}" is not registered`},metadata:{summary:`Skill 未找到: ${Z}`}};let J=await Y.loadContent(Z);if(!J)return{success:!1,llmContent:`Failed to load skill "${Z}" content`,error:{type:"execution_error",message:`Could not read SKILL.md for "${Z}"`},metadata:{summary:`加载 Skill 失败: ${Z}`}};let X=D4(J.metadata.name,J.instructions,J.metadata.basePath),V=typeof J.metadata.model==="string"&&J.metadata.model!=="inherit"&&J.metadata.model.trim()!==""?J.metadata.model:void 0;return{success:!0,llmContent:X,metadata:{summary:`加载 Skill: ${Z}`,skillName:Z,basePath:J.metadata.basePath,version:J.metadata.version,allowedTools:J.metadata.allowedTools,modelId:V}}}});function D4($,W,Z){return`# Skill: ${$}
640
+ `},async execute($,W){let{skill:Z}=$,Y=U0();if(!Y.has(Z))return{success:!1,llmContent:`Skill "${Z}" not found. Available skills: ${Y.getAll().map((H)=>H.name).join(", ")||"none"}`,error:{type:"validation_error",message:`Skill "${Z}" is not registered`},metadata:{summary:`Skill 未找到: ${Z}`}};let J=await Y.loadContent(Z);if(!J)return{success:!1,llmContent:`Failed to load skill "${Z}" content`,error:{type:"execution_error",message:`Could not read SKILL.md for "${Z}"`},metadata:{summary:`加载 Skill 失败: ${Z}`}};let X=_4(J.metadata.name,J.instructions,J.metadata.basePath),V=typeof J.metadata.model==="string"&&J.metadata.model!=="inherit"&&J.metadata.model.trim()!==""?J.metadata.model:void 0;return{success:!0,llmContent:X,metadata:{summary:`加载 Skill: ${Z}`,skillName:Z,basePath:J.metadata.basePath,version:J.metadata.version,allowedTools:J.metadata.allowedTools,modelId:V}}}});function _4($,W,Z){return`# Skill: ${$}
641
641
 
642
642
  You are now operating in the "${$}" skill mode. Follow the instructions below to complete the task.
643
643
 
@@ -650,19 +650,19 @@ ${W}
650
650
 
651
651
  ---
652
652
 
653
- Remember: Follow the above instructions carefully to complete the user's request.`}import{z as QW}from"zod";import{execSync as _4}from"node:child_process";import G5 from"node:fs";import E5 from"node:path";class VW{async execute($,W){let Z=$.content;if(W.signal?.aborted)throw Error("Command execution aborted");return Z=this.interpolateArgs(Z,W.args),Z=await this.executeBashEmbeds(Z,W),Z=await this.resolveFileReferences(Z,W.workspaceRoot),Z}interpolateArgs($,W){$=$.replace(/\$ARGUMENTS/g,W.join(" "));for(let Z=9;Z>=1;Z--){let Y=`$${Z}`,J=W[Z-1]??"";$=$.split(Y).join(J)}return $}async executeBashEmbeds($,W){let Z=/!`([^`]+)`/g,Y=[];for(let X of $.matchAll(Z))Y.push({match:X[0],command:X[1]});let J=$;for(let{match:X,command:V}of Y){if(W.signal?.aborted){J=J.replace(X,"[Execution aborted]");continue}try{let H=_4(V,{cwd:W.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();J=J.replace(X,H)}catch(H){let B=H instanceof Error?H.message:String(H);J=J.replace(X,`[Error executing '${V}': ${B}]`)}}return J}async resolveFileReferences($,W){let Z=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,Y=[];for(let X of $.matchAll(Z))Y.push({match:X[0],relativePath:X[1]});let J=$;for(let{match:X,relativePath:V}of Y){let H=E5.resolve(W,V);try{if(G5.statSync(H).isFile()){let K=G5.readFileSync(H,"utf-8"),U=`\`\`\`${E5.extname(V).slice(1)||"text"}
654
- ${K}
655
- \`\`\``;J=J.replace(X,U)}}catch{}}return J}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import BW from"node:fs";import z5 from"node:os";import I0 from"node:path";import j4 from"node:fs";import F5 from"node:path";import A4 from"gray-matter";class HW{parse($,W,Z,Y){try{let J=j4.readFileSync($,"utf-8"),{data:X,content:V}=A4(J),{name:H,namespace:B}=this.extractNameAndNamespace($,W);if(!H)return null;return{name:H,namespace:B,config:this.normalizeConfig(X),content:V.trim(),path:$,source:Z,sourceDir:Y}}catch(J){return console.error(`Failed to parse command file: ${$}`,J),null}}normalizeConfig($){return{description:this.asString($.description),allowedTools:this.parseAllowedTools($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseAllowedTools($){if(!$)return;if(Array.isArray($))return $.map((W)=>String(W).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((W)=>W.trim()).filter(Boolean);return}extractNameAndNamespace($,W){let Y=F5.relative(W,$).split(F5.sep),J=Y.pop();if(!J)return{name:""};let X=J.replace(/\.md$/i,""),V=Y.length>0?Y.join("/"):void 0;return{name:X,namespace:V}}validateConfig($){let W=[];if($.model&&!this.isValidModelId($.model))W.push(`Invalid model ID: ${$.model}`);return W}isValidModelId($){return $.length>0&&$.length<200}}class KW{parser=new HW;async discover($){let W=[],Z=[],Y=[],J=this.getSearchDirs($);for(let X of J){if(!BW.existsSync(X.path))continue;Z.push(X.path);try{let V=await this.scanDirectory(X.path);for(let H of V)try{let B=this.parser.parse(H,X.path,X.source,X.sourceDir);if(B)W.push(B)}catch(B){Y.push({path:H,error:B instanceof Error?B.message:String(B)})}}catch(V){Y.push({path:X.path,error:V instanceof Error?V.message:String(V)})}}return{commands:W,scannedDirs:Z,errors:Y}}getSearchDirs($){let W=z5.homedir();return[{path:I0.join(W,".blade","commands"),source:"user",sourceDir:"blade"},{path:I0.join(W,".claude","commands"),source:"user",sourceDir:"claude"},{path:I0.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:I0.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let W=[],Z=async(Y)=>{let J=await BW.promises.readdir(Y,{withFileTypes:!0});for(let X of J){let V=I0.join(Y,X.name);if(X.isDirectory())await Z(V);else if(X.isFile()&&X.name.endsWith(".md"))W.push(V)}};return await Z($),W}async hasCommands($){let W=this.getSearchDirs($);for(let Z of W){if(!BW.existsSync(Z.path))continue;if((await this.scanDirectory(Z.path)).length>0)return!0}return!1}getCommandDirs($){let W=z5.homedir();return{projectBlade:I0.join($,".blade","commands"),projectClaude:I0.join($,".claude","commands"),userBlade:I0.join(W,".blade","commands"),userClaude:I0.join(W,".claude","commands")}}}class r{static instance;commands=new Map;pluginCommands=new Map;loader=new KW;executor=new VW;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!r.instance)r.instance=new r;return r.instance}static resetInstance(){r.instance=new r}constructor(){}async initialize($){this.workspaceRoot=$;let W=await this.loader.discover($);this.lastDiscoveryResult=W,this.commands.clear();for(let Z of W.commands)this.commands.set(Z.name,Z);return this.initialized=!0,W}async refresh(){if(!this.workspaceRoot)throw Error("Registry not initialized. Call initialize() first.");return this.initialize(this.workspaceRoot)}isInitialized(){return this.initialized}getCommand($){return this.commands.get($)}hasCommand($){return this.commands.has($)}getAllCommands(){return Array.from(this.commands.values())}getCommandCount(){return this.commands.size}getModelInvocableCommands(){return this.getAllCommands().filter(($)=>$.config.description&&!$.config.disableModelInvocation)}async executeCommand($,W){let Z=this.getCommand($);if(!Z)return null;return this.executor.execute(Z,W)}getCommandLabel($){let W=$.source==="project"?"project":"user";if($.namespace)return`(${W}:${$.namespace})`;return`(${W})`}getCommandDisplayName($){let W=[`/${$.name}`];if($.config.argumentHint)W.push($.config.argumentHint);if($.config.description)W.push("-",$.config.description);return W.push(this.getCommandLabel($)),W.join(" ")}getCommandsBySource(){let $=[],W=[];for(let Z of this.commands.values())if(Z.source==="project")$.push(Z);else W.push(Z);return{project:$,user:W}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let W=this.getModelInvocableCommands(),Z=W.length;if(Z===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let Y=`Available custom commands:
653
+ Remember: Follow the above instructions carefully to complete the user's request.`}import{z as UW}from"zod";import{execSync as D4}from"node:child_process";import G5 from"node:fs";import E5 from"node:path";class VW{async execute($,W){let Z=$.content;if(W.signal?.aborted)throw Error("Command execution aborted");return Z=this.interpolateArgs(Z,W.args),Z=await this.executeBashEmbeds(Z,W),Z=await this.resolveFileReferences(Z,W.workspaceRoot),Z}interpolateArgs($,W){$=$.replace(/\$ARGUMENTS/g,W.join(" "));for(let Z=9;Z>=1;Z--){let Y=`$${Z}`,J=W[Z-1]??"";$=$.split(Y).join(J)}return $}async executeBashEmbeds($,W){let Z=/!`([^`]+)`/g,Y=[];for(let X of $.matchAll(Z))Y.push({match:X[0],command:X[1]});let J=$;for(let{match:X,command:V}of Y){if(W.signal?.aborted){J=J.replace(X,"[Execution aborted]");continue}try{let H=D4(V,{cwd:W.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();J=J.replace(X,H)}catch(H){let K=H instanceof Error?H.message:String(H);J=J.replace(X,`[Error executing '${V}': ${K}]`)}}return J}async resolveFileReferences($,W){let Z=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,Y=[];for(let X of $.matchAll(Z))Y.push({match:X[0],relativePath:X[1]});let J=$;for(let{match:X,relativePath:V}of Y){let H=E5.resolve(W,V);try{if(G5.statSync(H).isFile()){let B=G5.readFileSync(H,"utf-8"),Q=`\`\`\`${E5.extname(V).slice(1)||"text"}
654
+ ${B}
655
+ \`\`\``;J=J.replace(X,Q)}}catch{}}return J}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import BW from"node:fs";import z5 from"node:os";import I0 from"node:path";import j4 from"node:fs";import F5 from"node:path";import A4 from"gray-matter";class HW{parse($,W,Z,Y){try{let J=j4.readFileSync($,"utf-8"),{data:X,content:V}=A4(J),{name:H,namespace:K}=this.extractNameAndNamespace($,W);if(!H)return null;return{name:H,namespace:K,config:this.normalizeConfig(X),content:V.trim(),path:$,source:Z,sourceDir:Y}}catch(J){return console.error(`Failed to parse command file: ${$}`,J),null}}normalizeConfig($){return{description:this.asString($.description),allowedTools:this.parseAllowedTools($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseAllowedTools($){if(!$)return;if(Array.isArray($))return $.map((W)=>String(W).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((W)=>W.trim()).filter(Boolean);return}extractNameAndNamespace($,W){let Y=F5.relative(W,$).split(F5.sep),J=Y.pop();if(!J)return{name:""};let X=J.replace(/\.md$/i,""),V=Y.length>0?Y.join("/"):void 0;return{name:X,namespace:V}}validateConfig($){let W=[];if($.model&&!this.isValidModelId($.model))W.push(`Invalid model ID: ${$.model}`);return W}isValidModelId($){return $.length>0&&$.length<200}}class KW{parser=new HW;async discover($){let W=[],Z=[],Y=[],J=this.getSearchDirs($);for(let X of J){if(!BW.existsSync(X.path))continue;Z.push(X.path);try{let V=await this.scanDirectory(X.path);for(let H of V)try{let K=this.parser.parse(H,X.path,X.source,X.sourceDir);if(K)W.push(K)}catch(K){Y.push({path:H,error:K instanceof Error?K.message:String(K)})}}catch(V){Y.push({path:X.path,error:V instanceof Error?V.message:String(V)})}}return{commands:W,scannedDirs:Z,errors:Y}}getSearchDirs($){let W=z5.homedir();return[{path:I0.join(W,".blade","commands"),source:"user",sourceDir:"blade"},{path:I0.join(W,".claude","commands"),source:"user",sourceDir:"claude"},{path:I0.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:I0.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let W=[],Z=async(Y)=>{let J=await BW.promises.readdir(Y,{withFileTypes:!0});for(let X of J){let V=I0.join(Y,X.name);if(X.isDirectory())await Z(V);else if(X.isFile()&&X.name.endsWith(".md"))W.push(V)}};return await Z($),W}async hasCommands($){let W=this.getSearchDirs($);for(let Z of W){if(!BW.existsSync(Z.path))continue;if((await this.scanDirectory(Z.path)).length>0)return!0}return!1}getCommandDirs($){let W=z5.homedir();return{projectBlade:I0.join($,".blade","commands"),projectClaude:I0.join($,".claude","commands"),userBlade:I0.join(W,".blade","commands"),userClaude:I0.join(W,".claude","commands")}}}class r{static instance;commands=new Map;pluginCommands=new Map;loader=new KW;executor=new VW;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!r.instance)r.instance=new r;return r.instance}static resetInstance(){r.instance=new r}constructor(){}async initialize($){this.workspaceRoot=$;let W=await this.loader.discover($);this.lastDiscoveryResult=W,this.commands.clear();for(let Z of W.commands)this.commands.set(Z.name,Z);return this.initialized=!0,W}async refresh(){if(!this.workspaceRoot)throw Error("Registry not initialized. Call initialize() first.");return this.initialize(this.workspaceRoot)}isInitialized(){return this.initialized}getCommand($){return this.commands.get($)}hasCommand($){return this.commands.has($)}getAllCommands(){return Array.from(this.commands.values())}getCommandCount(){return this.commands.size}getModelInvocableCommands(){return this.getAllCommands().filter(($)=>$.config.description&&!$.config.disableModelInvocation)}async executeCommand($,W){let Z=this.getCommand($);if(!Z)return null;return this.executor.execute(Z,W)}getCommandLabel($){let W=$.source==="project"?"project":"user";if($.namespace)return`(${W}:${$.namespace})`;return`(${W})`}getCommandDisplayName($){let W=[`/${$.name}`];if($.config.argumentHint)W.push($.config.argumentHint);if($.config.description)W.push("-",$.config.description);return W.push(this.getCommandLabel($)),W.join(" ")}getCommandsBySource(){let $=[],W=[];for(let Z of this.commands.values())if(Z.source==="project")$.push(Z);else W.push(Z);return{project:$,user:W}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let W=this.getModelInvocableCommands(),Z=W.length;if(Z===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let Y=`Available custom commands:
656
656
 
657
- `,J=Y.length,X=0;for(let V of W){let H=this.getCommandLabel(V),B=V.config.argumentHint?` ${V.config.argumentHint}`:"",K=`- /${V.name}${B}: ${V.config.description} ${H}
658
- `;if(J+K.length>$)break;Y+=K,J+=K.length,X++}if(X<Z)Y+=`
657
+ `,J=Y.length,X=0;for(let V of W){let H=this.getCommandLabel(V),K=V.config.argumentHint?` ${V.config.argumentHint}`:"",B=`- /${V.name}${K}: ${V.config.description} ${H}
658
+ `;if(J+B.length>$)break;Y+=B,J+=B.length,X++}if(X<Z)Y+=`
659
659
  (${X} of ${Z} commands shown due to character budget)`;return{text:Y,includedCount:X,totalCount:Z}}registerPluginCommand($){this.pluginCommands.set($.namespacedName,$)}findPluginCommand($){let W=this.pluginCommands.get($);if(W)return W;let Z=[];for(let Y of this.pluginCommands.values())if(Y.originalName===$)Z.push(Y);if(Z.length===1)return Z[0];return}hasPluginCommand($){return this.findPluginCommand($)!==void 0}getAllPluginCommands(){return Array.from(this.pluginCommands.values())}async executePluginCommand($,W){let Z=this.findPluginCommand($);if(!Z)return null;let Y={name:Z.namespacedName,config:Z.config,content:Z.content,path:Z.path,source:"project",sourceDir:"blade"};return this.executor.execute(Y,W)}clearPluginCommands(){this.pluginCommands.clear()}getPluginCommandCount(){return this.pluginCommands.size}hasPluginCommandConflict($){let W=0;for(let Z of this.pluginCommands.values())if(Z.originalName===$){if(W++,W>1)return!0}return!1}getPluginCommandProviders($){let W=[];for(let Z of this.pluginCommands.values())if(Z.originalName===$)W.push(Z.pluginName);return W}}var N4=Number.parseInt(process.env.SLASH_COMMAND_TOOL_CHAR_BUDGET||"15000",10);function T4(){let $=r.getInstance();if(!$.isInitialized())return`
660
660
  (Custom commands not yet initialized)`;let{text:W,totalCount:Z}=$.generateCommandListDescription(N4);if(Z===0)return`
661
661
  (No custom commands available)`;return`
662
662
 
663
663
  <available_commands>
664
664
  ${W}
665
- </available_commands>`}var UW=j({name:"SlashCommand",displayName:"Slash Command",kind:"execute",isConcurrencySafe:!1,schema:QW.object({command:QW.string().describe('The command name without the leading slash, e.g., "review-pr" or "commit"'),arguments:QW.string().optional().describe('Arguments to pass to the command, e.g., "123" or "fix bug"')}),description:{short:"Execute a custom slash command within the main conversation",long:`Execute a custom slash command within the main conversation
665
+ </available_commands>`}var QW=N({name:"SlashCommand",displayName:"Slash Command",kind:"execute",isConcurrencySafe:!1,schema:UW.object({command:UW.string().describe('The command name without the leading slash, e.g., "review-pr" or "commit"'),arguments:UW.string().optional().describe('Arguments to pass to the command, e.g., "123" or "fix bug"')}),description:{short:"Execute a custom slash command within the main conversation",long:`Execute a custom slash command within the main conversation
666
666
 
667
667
  How slash commands work:
668
668
  When you use this tool, the command's content (from .blade/commands/ or .claude/commands/) will be processed and returned. The content may include:
@@ -685,7 +685,7 @@ Notes:
685
685
  - Only custom slash commands with descriptions are listed in Available Commands
686
686
  - Commands with \`disable-model-invocation: true\` cannot be invoked by this tool
687
687
  - If a command is not listed, ask the user to check the slash command file
688
- ${T4()}`},async execute($,W){let{command:Z,arguments:Y}=$,J=r.getInstance();if(!J.isInitialized())return{success:!1,llmContent:"Custom command system not initialized. Please wait for the application to fully initialize.",error:{type:"execution_error",message:"CustomCommandRegistry not initialized"},metadata:{summary:"命令系统未初始化"}};let X=J.getCommand(Z);if(!X){let H=J.getModelInvocableCommands().map((B)=>`/${B.name}`).join(", ");return{success:!1,llmContent:`Command "/${Z}" not found. Available commands: ${H||"none"}`,error:{type:"validation_error",message:`Command "/${Z}" is not registered`},metadata:{summary:`命令未找到: /${Z}`}}}if(X.config.disableModelInvocation)return{success:!1,llmContent:`Command "/${Z}" has disabled model invocation. This command can only be executed by the user directly.`,error:{type:"permission_denied",message:`Command "/${Z}" has disable-model-invocation: true`},metadata:{summary:`命令禁止 AI 调用: /${Z}`}};if(!X.config.description)return{success:!1,llmContent:`Command "/${Z}" does not have a description and cannot be invoked by AI. Add a description in the command's frontmatter to enable AI invocation.`,error:{type:"validation_error",message:`Command "/${Z}" missing description for AI invocation`},metadata:{summary:`命令缺少描述: /${Z}`}};let V=Y?Y.split(/\s+/).filter(Boolean):[];try{let H=await J.executeCommand(Z,{args:V,workspaceRoot:D()});if(!H)return{success:!1,llmContent:`Failed to execute command "/${Z}"`,error:{type:"execution_error",message:"Command execution returned null"},metadata:{summary:`执行命令失败: /${Z}`}};return{success:!0,llmContent:L4(X.name,H,X.config),metadata:{summary:`执行命令: /${Z}`,commandName:Z,allowedTools:X.config.allowedTools,model:X.config.model,source:X.source,namespace:X.namespace}}}catch(H){let B=H instanceof Error?H.message:String(H);return{success:!1,llmContent:`Error executing command "/${Z}": ${B}`,error:{type:"execution_error",message:B},metadata:{summary:`命令执行出错: /${Z}`}}}}});function L4($,W,Z){let Y=`# Custom Command: /${$}
688
+ ${T4()}`},async execute($,W){let{command:Z,arguments:Y}=$,J=r.getInstance();if(!J.isInitialized())return{success:!1,llmContent:"Custom command system not initialized. Please wait for the application to fully initialize.",error:{type:"execution_error",message:"CustomCommandRegistry not initialized"},metadata:{summary:"命令系统未初始化"}};let X=J.getCommand(Z);if(!X){let H=J.getModelInvocableCommands().map((K)=>`/${K.name}`).join(", ");return{success:!1,llmContent:`Command "/${Z}" not found. Available commands: ${H||"none"}`,error:{type:"validation_error",message:`Command "/${Z}" is not registered`},metadata:{summary:`命令未找到: /${Z}`}}}if(X.config.disableModelInvocation)return{success:!1,llmContent:`Command "/${Z}" has disabled model invocation. This command can only be executed by the user directly.`,error:{type:"permission_denied",message:`Command "/${Z}" has disable-model-invocation: true`},metadata:{summary:`命令禁止 AI 调用: /${Z}`}};if(!X.config.description)return{success:!1,llmContent:`Command "/${Z}" does not have a description and cannot be invoked by AI. Add a description in the command's frontmatter to enable AI invocation.`,error:{type:"validation_error",message:`Command "/${Z}" missing description for AI invocation`},metadata:{summary:`命令缺少描述: /${Z}`}};let V=Y?Y.split(/\s+/).filter(Boolean):[];try{let H=await J.executeCommand(Z,{args:V,workspaceRoot:D()});if(!H)return{success:!1,llmContent:`Failed to execute command "/${Z}"`,error:{type:"execution_error",message:"Command execution returned null"},metadata:{summary:`执行命令失败: /${Z}`}};return{success:!0,llmContent:L4(X.name,H,X.config),metadata:{summary:`执行命令: /${Z}`,commandName:Z,allowedTools:X.config.allowedTools,model:X.config.model,source:X.source,namespace:X.namespace}}}catch(H){let K=H instanceof Error?H.message:String(H);return{success:!1,llmContent:`Error executing command "/${Z}": ${K}`,error:{type:"execution_error",message:K},metadata:{summary:`命令执行出错: /${Z}`}}}}});function L4($,W,Z){let Y=`# Custom Command: /${$}
689
689
 
690
690
  The user has invoked the custom command "/${$}". Follow the instructions below to complete the task.
691
691
 
@@ -700,29 +700,29 @@ ${W}
700
700
 
701
701
  ---
702
702
 
703
- Remember: Follow the above instructions carefully to complete the user's request.`,Y}import{z as qW}from"zod";var wW=j({name:"ToolSearch",displayName:"Tool Search",kind:"readonly",isConcurrencySafe:!0,schema:qW.object({query:qW.string().describe('Search query. Use "select:Read,Edit,Grep" for exact selection, or keywords for fuzzy search.'),max_results:qW.number().default(5).describe("Maximum results to return (default 5)")}),description:{short:"Search and load deferred tool schemas",long:["Fetches full schema definitions for deferred tools so","they can be called. Deferred tools appear by name in","<available-deferred-tools> messages. Until fetched, only","the name is known — there is no parameter schema, so","the tool cannot be invoked."].join(" "),usageNotes:['Use "select:Read,Edit,Grep" to fetch exact tools by name',"Use keywords to search by tool name or description","Once loaded via ToolSearch, a tool becomes callable"],examples:[{description:"Load specific tools by name",params:{query:"select:WebFetch,WebSearch",max_results:5}},{description:"Search for notebook-related tools",params:{query:"notebook jupyter",max_results:5}}]},async execute($,W){let{query:Z,max_results:Y}=$,J=W.toolRegistry;if(!J)return{success:!1,llmContent:"Tool registry not available in execution context."};let X=[];if(Z.startsWith("select:")){let H=Z.slice(7).split(",").map((B)=>B.trim());for(let B of H){let K=J.get(B);if(K)X.push({name:K.name,declaration:K.getFunctionDeclaration()})}}else X=J.search(Z).slice(0,Y).map((B)=>({name:B.name,declaration:B.getFunctionDeclaration()}));if(X.length===0)return{success:!0,llmContent:`No tools found matching "${Z}".`};if(W.deferredToolManager)for(let{name:H}of X)W.deferredToolManager.markLoaded(H);return{success:!0,llmContent:`<functions>
703
+ Remember: Follow the above instructions carefully to complete the user's request.`,Y}import{z as qW}from"zod";var wW=N({name:"ToolSearch",displayName:"Tool Search",kind:"readonly",isConcurrencySafe:!0,schema:qW.object({query:qW.string().describe('Search query. Use "select:Read,Edit,Grep" for exact selection, or keywords for fuzzy search.'),max_results:qW.number().default(5).describe("Maximum results to return (default 5)")}),description:{short:"Search and load deferred tool schemas",long:["Fetches full schema definitions for deferred tools so","they can be called. Deferred tools appear by name in","<available-deferred-tools> messages. Until fetched, only","the name is known — there is no parameter schema, so","the tool cannot be invoked."].join(" "),usageNotes:['Use "select:Read,Edit,Grep" to fetch exact tools by name',"Use keywords to search by tool name or description","Once loaded via ToolSearch, a tool becomes callable"],examples:[{description:"Load specific tools by name",params:{query:"select:WebFetch,WebSearch",max_results:5}},{description:"Search for notebook-related tools",params:{query:"notebook jupyter",max_results:5}}]},async execute($,W){let{query:Z,max_results:Y}=$,J=W.toolRegistry;if(!J)return{success:!1,llmContent:"Tool registry not available in execution context."};let X=[];if(Z.startsWith("select:")){let H=Z.slice(7).split(",").map((K)=>K.trim());for(let K of H){let B=J.get(K);if(B)X.push({name:B.name,declaration:B.getFunctionDeclaration()})}}else X=J.search(Z).slice(0,Y).map((K)=>({name:K.name,declaration:K.getFunctionDeclaration()}));if(X.length===0)return{success:!0,llmContent:`No tools found matching "${Z}".`};if(W.deferredToolManager)for(let{name:H}of X)W.deferredToolManager.markLoaded(H);return{success:!0,llmContent:`<functions>
704
704
  ${X.map(({declaration:H})=>`<function>${JSON.stringify(H)}</function>`).join(`
705
705
  `)}
706
- </functions>`,metadata:{summary:`加载了 ${X.length} 个工具 schema`}}}});import{nanoid as o5}from"nanoid";import{z as J$}from"zod";import{nanoid as l7}from"nanoid";import*as I5 from"os";import*as h5 from"path";import{randomUUID as z7}from"node:crypto";import{EventEmitter as R7}from"node:events";import{execFile as S4}from"node:child_process";import{existsSync as I4}from"node:fs";import q0 from"node:path";import{promisify as h4}from"node:util";import{execFile as k4}from"node:child_process";import{createHash as b4}from"node:crypto";import{existsSync as EW,readFileSync as M4}from"node:fs";import D0 from"node:path";import{promisify as v4}from"node:util";var x4=v4(k4),GW=P("Execution");class t0{static instance=null;cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??f4}static getInstance(){if(!t0.instance)t0.instance=new t0;return t0.instance}static resetInstance(){t0.instance=null}async verify($,W){let Z=y4($,W);if(!Z)return null;let Y=Date.now(),J=C4($,W),X=this.cache.get(Z);if(X&&X.inputFingerprint===J&&Y-X.at<this.cacheMs)return GW.debug(`[VerifyQueue] cache hit: ${Z}`),X.result;let V=this.running.get(Z);if(V?.inputFingerprint===J)return GW.debug(`[VerifyQueue] coalescing into running check: ${Z}`),V.promise;let H=async()=>{let U=await this.runTypeCheck(Z);return this.cache.set(Z,{result:U,at:Date.now(),inputFingerprint:J}),U},B=V?.promise,K=(B?B.then(H,H):H()).finally(()=>{if(this.running.get(Z)?.promise===K)this.running.delete(Z)}),Q={inputFingerprint:J,promise:K};return this.running.set(Z,Q),K}clearCache(){this.cache.clear()}async runTypeCheck($){let{cmd:W,args:Z}=P4($);GW.debug(`[VerifyQueue] running: ${W} ${Z.join(" ")} in ${$}`);let{stdout:Y,stderr:J,exitCode:X,timedOut:V}=await this.runCommand(W,Z,$,this.timeoutMs),H=`${Y}
707
- ${J}`.trim();return{hasErrors:X!==0&&!V,rawOutput:H,timedOut:V,workspaceRoot:$}}}function C4($,W){let Z=D0.isAbsolute($)?D0.normalize($):D0.resolve(W,$);try{let Y=b4("sha256").update(M4(Z)).digest("hex");return`${Z}\x00${Y}`}catch{return`${Z}\x00missing`}}function y4($,W){let Z=D0.isAbsolute($)?$:D0.resolve(W,$),Y=D0.dirname(Z),J=D0.parse(Y).root;while(Y!==J){if(EW(D0.join(Y,"tsconfig.json")))return Y;Y=D0.dirname(Y)}if(EW(D0.join(W,"tsconfig.json")))return W;return null}function P4($){let W=D0.join($,"package.json");if(EW(W))try{if(U$(W)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function f4($,W,Z,Y){try{let{stdout:J,stderr:X}=await x4($,W,{cwd:Z,timeout:Y,encoding:"utf-8",maxBuffer:4194304});return{stdout:J,stderr:X,exitCode:0,timedOut:!1}}catch(J){let X=J,V=X.killed===!0||X.signal==="SIGTERM",H=typeof X.code==="number"?X.code:1;return{stdout:X.stdout??"",stderr:X.stderr??"",exitCode:H,timedOut:V}}}var O5=h4(S4),R5=P("Execution"),u4=new Set(["Edit","Write"]),FW=15,p4=5000,d4=15000,g4=10;function m4($,W){let Z=$.split(`
706
+ </functions>`,metadata:{summary:`加载了 ${X.length} 个工具 schema`}}}});import{nanoid as o5}from"nanoid";import{z as J$}from"zod";import{nanoid as l7}from"nanoid";import*as I5 from"os";import*as h5 from"path";import{randomUUID as z7}from"node:crypto";import{EventEmitter as R7}from"node:events";import{execFile as S4}from"node:child_process";import{existsSync as I4}from"node:fs";import q0 from"node:path";import{promisify as h4}from"node:util";import{execFile as k4}from"node:child_process";import{createHash as b4}from"node:crypto";import{existsSync as EW,readFileSync as M4}from"node:fs";import _0 from"node:path";import{promisify as v4}from"node:util";var x4=v4(k4),GW=f("Execution");class t0{static instance=null;cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??P4}static getInstance(){if(!t0.instance)t0.instance=new t0;return t0.instance}static resetInstance(){t0.instance=null}async verify($,W){let Z=y4($,W);if(!Z)return null;let Y=Date.now(),J=C4($,W),X=this.cache.get(Z);if(X&&X.inputFingerprint===J&&Y-X.at<this.cacheMs)return GW.debug(`[VerifyQueue] cache hit: ${Z}`),X.result;let V=this.running.get(Z);if(V?.inputFingerprint===J)return GW.debug(`[VerifyQueue] coalescing into running check: ${Z}`),V.promise;let H=async()=>{let Q=await this.runTypeCheck(Z);return this.cache.set(Z,{result:Q,at:Date.now(),inputFingerprint:J}),Q},K=V?.promise,B=(K?K.then(H,H):H()).finally(()=>{if(this.running.get(Z)?.promise===B)this.running.delete(Z)}),U={inputFingerprint:J,promise:B};return this.running.set(Z,U),B}clearCache(){this.cache.clear()}async runTypeCheck($){let{cmd:W,args:Z}=f4($);GW.debug(`[VerifyQueue] running: ${W} ${Z.join(" ")} in ${$}`);let{stdout:Y,stderr:J,exitCode:X,timedOut:V}=await this.runCommand(W,Z,$,this.timeoutMs),H=`${Y}
707
+ ${J}`.trim();return{hasErrors:X!==0&&!V,rawOutput:H,timedOut:V,workspaceRoot:$}}}function C4($,W){let Z=_0.isAbsolute($)?_0.normalize($):_0.resolve(W,$);try{let Y=b4("sha256").update(M4(Z)).digest("hex");return`${Z}\x00${Y}`}catch{return`${Z}\x00missing`}}function y4($,W){let Z=_0.isAbsolute($)?$:_0.resolve(W,$),Y=_0.dirname(Z),J=_0.parse(Y).root;while(Y!==J){if(EW(_0.join(Y,"tsconfig.json")))return Y;Y=_0.dirname(Y)}if(EW(_0.join(W,"tsconfig.json")))return W;return null}function f4($){let W=_0.join($,"package.json");if(EW(W))try{if(Q$(W)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function P4($,W,Z,Y){try{let{stdout:J,stderr:X}=await x4($,W,{cwd:Z,timeout:Y,encoding:"utf-8",maxBuffer:4194304});return{stdout:J,stderr:X,exitCode:0,timedOut:!1}}catch(J){let X=J,V=X.killed===!0||X.signal==="SIGTERM",H=typeof X.code==="number"?X.code:1;return{stdout:X.stdout??"",stderr:X.stderr??"",exitCode:H,timedOut:V}}}var O5=h4(S4),R5=f("Execution"),u4=new Set(["Edit","Write"]),FW=15,p4=5000,d4=15000,g4=10;function m4($,W){let Z=$.split(`
708
708
  `),Y=q0.basename(W),J=q0.isAbsolute(W)?W:q0.resolve(W);return Z.filter((X)=>X.includes(Y)||X.includes(J))}async function c4($,W){try{return await O5("npx",["biome","lint","--max-diagnostics=5",$],{cwd:W,timeout:p4,encoding:"utf-8"}),null}catch(Z){let Y=Z;if(Y.killed)return null;let J=(Y.stdout||"")+(Y.stderr||"");if(J.includes("error"))return J.trim();return null}}async function l4($,W){try{return await O5("npx",["vitest","run","--reporter=dot",$],{cwd:W,timeout:d4,encoding:"utf-8"}),null}catch(Z){let Y=Z;if(Y.killed)return null;if(Y.code===0)return null;let J=(Y.stdout||"")+(Y.stderr||"");if(!J.trim())return null;let V=J.split(`
709
709
  `).filter((H)=>H.includes("FAIL")||H.includes("Error")||H.includes("✗")||H.includes("expected"));if(V.length===0)return null;return V.slice(0,g4).join(`
710
- `)}}function i4($){if($.includes(".test.")||$.includes(".spec.")||$.includes("__tests__"))return null;let W=q0.dirname($),Z=q0.extname($),Y=q0.basename($,Z),J=[q0.join(W,`${Y}.test${Z}`),q0.join(W,`${Y}.spec${Z}`),q0.join(W,"__tests__",`${Y}.test${Z}`),q0.join(W,"..","tests",`${Y}.test${Z}`)];for(let X of J)if(I4(X))return X;return null}async function D5($,W,Z,Y,J=t0.getInstance()){if(!u4.has($)||!Y.success)return;let X=W.file_path||W.path;if(!X)return;let V=Z.workspaceRoot||D(),H=[];try{let q=await J.verify(X,V);if(q&&!q.timedOut&&q.hasErrors){let w=m4(q.rawOutput,X);if(w.length>0){let E=w.slice(0,FW);H.push(`Type errors:
710
+ `)}}function i4($){if($.includes(".test.")||$.includes(".spec.")||$.includes("__tests__"))return null;let W=q0.dirname($),Z=q0.extname($),Y=q0.basename($,Z),J=[q0.join(W,`${Y}.test${Z}`),q0.join(W,`${Y}.spec${Z}`),q0.join(W,"__tests__",`${Y}.test${Z}`),q0.join(W,"..","tests",`${Y}.test${Z}`)];for(let X of J)if(I4(X))return X;return null}async function _5($,W,Z,Y,J=t0.getInstance()){if(!u4.has($)||!Y.success)return;let X=W.file_path||W.path;if(!X)return;let V=Z.workspaceRoot||D(),H=[];try{let q=await J.verify(X,V);if(q&&!q.timedOut&&q.hasErrors){let w=m4(q.rawOutput,X);if(w.length>0){let E=w.slice(0,FW);H.push(`Type errors:
711
711
  ${E.join(`
712
712
  `)}`+(w.length>FW?`
713
713
  ... (+${w.length-FW} more)`:""))}}}catch(q){R5.debug(`[AutoVerify] type-check failed: ${q instanceof Error?q.message:String(q)}`)}if(X.endsWith(".ts")||X.endsWith(".tsx")||X.endsWith(".js")){let q=await c4(X,V);if(q){let w=q.split(`
714
714
  `).slice(0,5);H.push(`Lint errors:
715
715
  ${w.join(`
716
- `)}`)}}let B=X.includes(".test.")||X.includes(".spec."),K=B?X:i4(X);if(K){let q=await l4(K,V);if(q)H.push(`Test failures (${q0.basename(K)}):
717
- ${q}`);else if(!B&&K)H.push(`Related test: ${K}`)}if(H.length===0)return;let Q=`
716
+ `)}`)}}let K=X.includes(".test.")||X.includes(".spec."),B=K?X:i4(X);if(B){let q=await l4(B,V);if(q)H.push(`Test failures (${q0.basename(B)}):
717
+ ${q}`);else if(!K&&B)H.push(`Related test: ${B}`)}if(H.length===0)return;let U=`
718
718
 
719
719
  ---
720
720
  **Auto-Verify: issues in ${q0.basename(X)}:**
721
721
  \`\`\`
722
722
  `+H.join(`
723
723
 
724
- `)+"\n```",U=typeof Y.llmContent==="string"?Y.llmContent:Y.llmContent?JSON.stringify(Y.llmContent):"";Y.llmContent=`${U}${Q}`,R5.info(`[AutoVerify] injected ${H.length} diagnostic(s) (${q0.basename(X)})`)}var r4={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class h0{static instance=null;buckets;constructor($={}){let W={...r4,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:W.readonly,queue:[]},write:{inFlight:0,maxConcurrent:W.write,queue:[]},execute:{inFlight:0,maxConcurrent:W.execute,queue:[]}}}static getInstance(){if(!h0.instance)h0.instance=new h0;return h0.instance}static resetInstance(){h0.instance=null}schedule($,W){let Z=this.buckets[$];if(!Z)return W();if(Z.inFlight<Z.maxConcurrent)return this.runImmediately(Z,W);return new Promise((Y,J)=>{Z.queue.push({fn:W,resolve:Y,reject:J})})}async runImmediately($,W){$.inFlight++;try{return await W()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let W=$.queue.shift();$.inFlight++,W.fn().then(W.resolve,W.reject).finally(()=>{$.inFlight--,this.drain($)})}}getStats(){return{readonly:{inFlight:this.buckets["readonly"].inFlight,queued:this.buckets["readonly"].queue.length},write:{inFlight:this.buckets["write"].inFlight,queued:this.buckets["write"].queue.length},execute:{inFlight:this.buckets["execute"].inFlight,queued:this.buckets["execute"].queue.length}}}}var zW=P("Execution");class e0{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!e0.instance)e0.instance=new e0;return e0.instance}async acquireLock($,W){let Z=this.locks.get($);if(Z)try{await Z}catch{}let Y=this.executeWithLock($,W);return this.locks.set($,Y.then(()=>{return})),Y}async executeWithLock($,W){zW.debug(`获取文件锁: ${$}`);try{let Z=await W();return zW.debug(`释放文件锁: ${$}`),Z}catch(Z){throw zW.debug(`操作失败,释放文件锁: ${$}`),Z}}isLocked($){return this.locks.has($)}clearLock($){this.locks.delete($)}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){e0.instance=null}}import J1 from"picomatch";class z${config;constructor($){this.config=$}check($){let W=z$.buildSignature($),Z=$.toolName==="Bash"&&typeof $.params.command==="string",Y=Z?String($.params.command).trim():"",J=null;if(Z){let K=E$(s0(Y));if(K!==Y)J=`Bash(${K})`}let X=null;if(Z){let K=B5(s0(Y));if(K!==Y)X=`Bash(${K})`}let V=[W];if(X)V.push(X);for(let K of V){let Q=this.matchRules(K,this.config.deny);if(Q)return{result:"deny",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用被拒绝规则阻止: ${Q.rule}`}}let H=[W];if(J)H.push(J);for(let K of H){let Q=this.matchRules(K,this.config.allow);if(Q)return{result:"allow",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用符合允许规则: ${Q.rule}`}}let B=[W];if(X)B.push(X);for(let K of B){let Q=this.matchRules(K,this.config.ask);if(Q)return{result:"ask",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用需要用户确认: ${Q.rule}`}}return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:W,params:Z,tool:Y}=$;try{if(Y?.extractSignatureContent){let J=Y.extractSignatureContent(Z);return J?`${W}(${J})`:W}return W}catch(J){return console.warn(`Failed to build signature for ${W}:`,J instanceof Error?J.message:J),W}}static abstractPattern($){let{toolName:W,params:Z,tool:Y}=$;try{if(Y?.abstractPermissionRule){let J=Y.abstractPermissionRule(Z);if(J==="")return"";return J?`${W}(${J})`:W}return W}catch(J){return console.warn(`Failed to abstract pattern for ${W}:`,J instanceof Error?J.message:J),W}}matchRules($,W){for(let Z of W){let Y=this.matchRule($,Z);if(Y)return{rule:Z,type:Y}}return null}matchRule($,W){if($===W)return"exact";if(W==="*"||W==="**")return"wildcard";let Z=this.extractToolName($),Y=this.extractToolName(W);if(!Z||!Y)return null;if(Y.includes("*")){if(!J1.isMatch(Z,Y,{dot:!0,bash:!0}))return null}else if(Z!==Y)return null;if(W===Y)return"prefix";if(W.includes("*")){let J=this.extractParams($),X=this.extractParams(W);if(X==="*"||X==="**")return"wildcard";if(this.matchParams(J,X))return X.includes("**")?"glob":"wildcard";if(J1.isMatch($,W,{dot:!0,bash:!0}))return W.includes("**")?"glob":"wildcard"}return null}extractParams($){let W=$.match(/\(([\s\S]*)\)$/);return W?W[1]:""}matchParams($,W){if(!$||!W)return!1;let Z=this.parseParamPairs($),Y=this.parseParamPairs(W),J=Object.keys(Y).length>0,X=Object.keys(Z).length>0;if(J!==X)return!1;if(!J&&!X){if(W==="*"||W==="**")return!0;if(W.includes("*")||W.includes("{")||W.includes("?"))return J1.isMatch($,W,{dot:!0,bash:!0});return $===W}for(let[V,H]of Object.entries(Y)){let B=Z[V];if(B===void 0)return!1;if(H.includes("*")||H.includes("{")||H.includes("?")){if(H==="*"||H==="**")continue;if(!J1.isMatch(B,H,{dot:!0,bash:!0}))return!1}else if(B!==H)return!1}return!0}parseParamPairs($){let W={},Z=this.smartSplit($,",");for(let Y of Z){let J=this.findTopLevelDelimiter(Y,":");if(J>0){let X=Y.slice(0,J).trim(),V=Y.slice(J+1).trim();W[X]=V}}return W}smartSplit($,W){let Z=[],Y="",J=0,X=0,V=0,H=!1,B="",K=!1;for(let Q=0;Q<$.length;Q++){let U=$[Q];if(K){Y+=U,K=!1;continue}if(U==="\\"){Y+=U,K=!0;continue}if(!H&&U==="{")J++;else if(!H&&U==="}")J--;else if(!H&&U==="(")X++;else if(!H&&U===")")X--;else if(!H&&U==="[")V++;else if(!H&&U==="]")V--;if((U==='"'||U==="'")&&!H){H=!0,B=U,Y+=U;continue}else if(H&&U===B){H=!1,B="",Y+=U;continue}if(U===W&&J===0&&X===0&&V===0&&!H)Z.push(Y.trim()),Y="";else Y+=U}if(Y)Z.push(Y.trim());return Z}findTopLevelDelimiter($,W){let Z=0,Y=0,J=0,X=!1,V="",H=!1;for(let B=0;B<$.length;B++){let K=$[B];if(H){H=!1;continue}if(K==="\\"){H=!0;continue}if(!X&&K==="{")Z++;else if(!X&&K==="}")Z--;else if(!X&&K==="(")Y++;else if(!X&&K===")")Y--;else if(!X&&K==="[")J++;else if(!X&&K==="]")J--;if((K==='"'||K==="'")&&!X){X=!0,V=K;continue}else if(X&&K===V){X=!1,V="";continue}if(K===W&&Z===0&&Y===0&&J===0&&!X)return B}return-1}extractToolName($){let W=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return W?W[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}var RW={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},OW={"--since":"string","--after":"string","--until":"string","--before":"string"},DW={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},u1={"--max-count":"number","-n":"number"},p1={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},S$={"--color":"none","--no-color":"none"},d1={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},_5={"--author":"string","--committer":"string","--grep":"string"},g1={"--format":"string","--pretty":"string"},n4={"git diff":{safeFlags:{...p1,...S$,...d1,"--cached":"none","--staged":"none","--no-index":"none","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","-U":"number","--unified":"number","--compact-summary":"none","--ignore-space-change":"none","-b":"none","--ignore-all-space":"none","-w":"none","--ignore-blank-lines":"none","--src-prefix":"string","--dst-prefix":"string","--no-prefix":"none","-R":"none","--relative":"none","--histogram":"none","--patience":"none","--minimal":"none","--check":"none","--ext-diff":"none","--binary":"none","--abbrev":"none","--full-index":"none","--break-rewrites":"none","-B":"none","--find-renames":"none","-M":"none","--find-copies":"none","-C":"none","--diff-algorithm":"string"}},"git log":{safeFlags:{...RW,...OW,...DW,...u1,...p1,...S$,...d1,..._5,...g1,"--follow":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--simplify-by-decoration":"none","--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","--topo-order":"none","--diff-filter":"string","--skip":"number","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--walk-reflogs":"none","-g":"none","--boundary":"none","--source":"none"}},"git show":{safeFlags:{...p1,...S$,...d1,...g1,"--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","-U":"number","--unified":"number","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","--compact-summary":"none"}},"git shortlog":{safeFlags:{...RW,...OW,...u1,..._5,"-s":"none","--summary":"none","-n":"number","--numbered":"none","-e":"none","--email":"none","--group":"string","--format":"string"}},"git reflog":{safeFlags:{...DW,...u1,...S$,...g1,"--date":"string"},isDangerousCallback:($,W)=>{let Z=new Set(["expire","delete","exists"]);for(let Y of W)if(Z.has(Y))return!0;return!1}},"git stash list":{safeFlags:{...DW,...S$,...g1}},"git stash show":{safeFlags:{...p1,...S$,...d1,"-U":"number","--unified":"number","--include-untracked":"none","-u":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--quiet":"none","-q":"none","--get-url":"none","--sort":"string","--symref":"none"}},"git status":{safeFlags:{"--short":"none","-s":"none","--branch":"none","-b":"none","--porcelain":"none","--long":"none","--verbose":"none","-v":"none","--untracked-files":"none","-u":"none","--ignored":"none","--ignore-submodules":"none","--column":"none","--no-column":"none","--ahead-behind":"none","--no-ahead-behind":"none","--renames":"none","--no-renames":"none","--show-stash":"none"}},"git blame":{safeFlags:{"-L":"string","--line-porcelain":"none","--porcelain":"none","-p":"none","--show-name":"none","--show-number":"none","-n":"none","--show-email":"none","-e":"none","-w":"none","-M":"none","-C":"none","--date":"string","--color-lines":"none","--color-by-age":"none","--abbrev":"number","-s":"none","--score-debug":"none","--first-parent":"none","--root":"none","--since":"string"}},"git ls-files":{safeFlags:{"--cached":"none","-c":"none","--deleted":"none","-d":"none","--modified":"none","-m":"none","--others":"none","-o":"none","--ignored":"none","-i":"none","--stage":"none","-s":"none","--unmerged":"none","-u":"none","--killed":"none","-k":"none","--exclude":"string","-x":"string","--exclude-from":"string","-X":"string","--exclude-per-directory":"string","--exclude-standard":"none","--error-unmatch":"none","--full-name":"none","--recurse-submodules":"none","-z":"none","--eol":"none","--deduplicate":"none"}},"git config --get":{safeFlags:{"--global":"none","--system":"none","--local":"none","--worktree":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--show-scope":"none","-z":"none","--null":"none","--name-only":"none","--type":"string","--default":"string"}},"git remote show":{safeFlags:{"-n":"none"},isDangerousCallback:($,W)=>{let Z=W.filter((Y)=>!Y.startsWith("-"));if(Z.length!==1)return!0;return!/^[a-zA-Z0-9_.-]+$/.test(Z[0])}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},isDangerousCallback:($,W)=>{return W.filter((Y)=>!Y.startsWith("-")).length>0}},"git merge-base":{safeFlags:{"--all":"none","--octopus":"none","--is-ancestor":"none","--independent":"none","--fork-point":"none"}},"git rev-parse":{safeFlags:{"--verify":"none","--quiet":"none","-q":"none","--short":"none","--symbolic":"none","--symbolic-full-name":"none","--abbrev-ref":"none","--show-toplevel":"none","--show-cdup":"none","--show-prefix":"none","--show-superproject-working-tree":"none","--git-dir":"none","--git-common-dir":"none","--git-path":"string","--is-inside-git-dir":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--is-shallow-repository":"none","--absolute-git-dir":"none","--resolve-git-dir":"string","--all":"none","--branches":"none","--tags":"none","--remotes":"none","--glob":"string","--exclude":"string"}},"git rev-list":{safeFlags:{...RW,...OW,...u1,"--count":"none","--objects":"none","--no-walk":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--topo-order":"none","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--boundary":"none","--abbrev-commit":"none","--abbrev":"number","--header":"none","--skip":"number"}},"git describe":{safeFlags:{"--all":"none","--tags":"none","--contains":"none","--abbrev":"number","--long":"none","--first-parent":"none","--always":"none","--match":"string","--exclude":"string","--exact-match":"none","--dirty":"none","--broken":"none","--candidates":"number","--debug":"none"}},"git cat-file":{safeFlags:{"-t":"none","-s":"none","-e":"none","-p":"none","--batch":"none","--batch-check":"none","--batch-all-objects":"none","--textconv":"none","--filters":"none","--allow-unknown-type":"none","--buffer":"none","--unordered":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--sort":"string","--count":"number","--shell":"none","--perl":"none","--python":"none","--tcl":"none","--points-at":"string","--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string"}},"git grep":{safeFlags:{"-i":"none","--ignore-case":"none","-w":"none","--word-regexp":"none","-v":"none","--invert-match":"none","-n":"none","--line-number":"none","-l":"none","--files-with-matches":"none","--name-only":"none","-L":"none","--files-without-match":"none","-c":"none","--count":"none","--color":"none","--no-color":"none","-e":"string","-f":"string","--and":"none","--or":"none","--not":"none","--all-match":"none","-E":"none","--extended-regexp":"none","-G":"none","--basic-regexp":"none","-P":"none","--perl-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","--no-index":"none","--recurse-submodules":"none","--max-depth":"number","-h":"none","--no-filename":"none","-H":"none","--full-name":"none","-z":"none","--break":"none","--heading":"none","-p":"none","--show-function":"none","-W":"none","--function-context":"none","--threads":"number","-O":"string","--open-files-in-pager":"none","-A":"number","-B":"number","-C":"number","--context":"number"}},"git worktree list":{safeFlags:{"--porcelain":"none","-z":"none","-v":"none","--verbose":"none","--expire":"string"}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--sort":"string","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--format":"string","--color":"none","--no-color":"none"},isDangerousCallback:($,W)=>{if(W.some((J)=>J==="-l"||J==="--list"))return!1;return W.filter((J)=>!J.startsWith("-")).length>0}},"git branch":{safeFlags:{"-l":"none","--list":"none","-a":"none","--all":"none","-r":"none","--remotes":"none","-v":"none","--verbose":"none","-vv":"none","--sort":"string","--format":"string","--color":"none","--no-color":"none","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--abbrev":"number","--no-abbrev":"none","--show-current":"none"},isDangerousCallback:($,W)=>{let Z=new Set(["-l","--list","-a","--all","-r","--remotes","--show-current"]);if(W.some((V)=>Z.has(V)))return!1;let J=new Set(["-d","-D","-m","-M","-c","--copy","--delete","--move","--set-upstream-to","--unset-upstream","--edit-description"]);if(W.some((V)=>J.has(V.split("=")[0])))return!0;return W.filter((V)=>!V.startsWith("-")).length>0}}};function m($,W){for(let Z of W){if(Z.includes("://")||Z.includes("@"))return!0;if((Z.match(/\//g)||[]).length>=2)return!0}return!1}var c={"--json":"string","--jq":"string","--template":"string","-q":"none","--limit":"number","-L":"number","--web":"none","-w":"none","--comments":"none"},a4={"gh pr view":{safeFlags:{...c},isDangerousCallback:m},"gh pr list":{safeFlags:{...c,"--state":"string","-s":"string","--author":"string","--label":"string","--base":"string","--head":"string","--search":"string","--assignee":"string","--draft":"none"},isDangerousCallback:m},"gh pr diff":{safeFlags:{...c,"--color":"string","--patch":"none","--name-only":"none"},isDangerousCallback:m},"gh pr checks":{safeFlags:{...c,"--watch":"none","--fail-fast":"none","--required":"none"},isDangerousCallback:m},"gh pr status":{safeFlags:{...c},isDangerousCallback:m},"gh issue view":{safeFlags:{...c},isDangerousCallback:m},"gh issue list":{safeFlags:{...c,"--state":"string","-s":"string","--author":"string","--label":"string","--search":"string","--assignee":"string","--milestone":"string"},isDangerousCallback:m},"gh issue status":{safeFlags:{...c},isDangerousCallback:m},"gh repo view":{safeFlags:{...c},isDangerousCallback:m},"gh run list":{safeFlags:{...c,"--workflow":"string","-w":"string","--branch":"string","-b":"string","--status":"string","-s":"string","--user":"string","-u":"string","--event":"string","-e":"string"},isDangerousCallback:m},"gh run view":{safeFlags:{...c,"--log":"none","--log-failed":"none","--exit-status":"none","--verbose":"none","-v":"none","--job":"string","-j":"string"},isDangerousCallback:m},"gh auth status":{safeFlags:{"--hostname":"string","-h":"string","--active":"none"},isDangerousCallback:($,W)=>{return W.some((Z)=>Z==="--show-token"||Z==="-t")}},"gh release list":{safeFlags:{...c,"--exclude-drafts":"none","--exclude-pre-releases":"none"},isDangerousCallback:m},"gh release view":{safeFlags:{...c},isDangerousCallback:m},"gh workflow list":{safeFlags:{...c,"--all":"none","-a":"none"},isDangerousCallback:m},"gh workflow view":{safeFlags:{...c,"--yaml":"none","-y":"none","--ref":"string","-r":"string"},isDangerousCallback:m},"gh label list":{safeFlags:{...c,"--search":"string","--sort":"string","--order":"string"},isDangerousCallback:m},"gh search repos":{safeFlags:{...c,"--language":"string","--topic":"string","--sort":"string","--order":"string","--match":"string","--owner":"string","--visibility":"string"},isDangerousCallback:m},"gh search issues":{safeFlags:{...c,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:m},"gh search prs":{safeFlags:{...c,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:m},"gh search commits":{safeFlags:{...c,"--sort":"string","--order":"string","--author":"string","--committer":"string","--repo":"string"},isDangerousCallback:m},"gh search code":{safeFlags:{...c,"--language":"string","--filename":"string","--extension":"string","--repo":"string","--match":"string"},isDangerousCallback:m}},o4={"docker logs":{safeFlags:{"--follow":"none","-f":"none","--tail":"number","-n":"number","--timestamps":"none","-t":"none","--since":"string","--until":"string","--details":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","--type":"string","--size":"none","-s":"none"}}},s4={rg:{safeFlags:{"-e":"string","--regexp":"string","-F":"none","--fixed-strings":"none","-i":"none","--ignore-case":"none","-S":"none","--smart-case":"none","-s":"none","--case-sensitive":"none","-v":"none","--invert-match":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-P":"none","--pcre2":"none","--engine":"string","-m":"number","--max-count":"number","--max-depth":"number","--maxdepth":"number","-d":"number","--max-filesize":"string","--mmap":"none","--no-mmap":"none","-U":"none","--multiline":"none","--multiline-dotall":"none","--crlf":"none","--no-crlf":"none","-c":"none","--count":"none","--count-matches":"none","-l":"none","--files-with-matches":"none","--files-without-match":"none","-o":"none","--only-matching":"none","--vimgrep":"none","-r":"string","--replace":"string","-t":"string","--type":"string","-T":"string","--type-not":"string","-g":"string","--glob":"string","--iglob":"string","--type-add":"string","--type-clear":"string","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","--color":"string","--colors":"string","-n":"none","--line-number":"none","-N":"none","--no-line-number":"none","-H":"none","--with-filename":"none","--no-filename":"none","-p":"none","--pretty":"none","--heading":"none","--no-heading":"none","--column":"none","--no-column":"none","--byte-offset":"none","--trim":"none","-j":"number","--threads":"number","--sort":"string","--sortr":"string","--stats":"none","--no-ignore":"none","--no-ignore-vcs":"none","--no-ignore-parent":"none","--no-ignore-global":"none","--hidden":"none","--no-hidden":"none","-L":"none","--follow":"none","--one-file-system":"none","--null":"none","-0":"none","--path-separator":"string","--no-config":"none","--no-ignore-dot":"none","--no-ignore-exclude":"none","--no-unicode":"none","--pcre2-version":"none","-q":"none","--quiet":"none","--help":"none","-h":"none","--version":"none","-V":"none","--":"none","--json":"none","--auto-hybrid-regex":"none","--binary":"none","--block-buffered":"none","--line-buffered":"none","--debug":"none","--dfa-size-limit":"string","--encoding":"string","-E":"string","--no-messages":"none","--regex-size-limit":"string","--search-zip":"none","-z":"none","--type-list":"none","--unrestricted":"none","-u":"none"}}},t4={...n4,...a4,...o4,...s4,file:{safeFlags:{"-b":"none","--brief":"none","-i":"none","--mime":"none","--mime-type":"none","--mime-encoding":"none","-L":"none","-h":"none","--no-dereference":"none","-z":"none"}},sort:{safeFlags:{"-r":"none","--reverse":"none","-n":"none","--numeric-sort":"none","-u":"none","--unique":"none","-k":"string","--key":"string","-t":"string","--field-separator":"string","-f":"none","--ignore-case":"none","-s":"none","--stable":"none","-h":"none","--human-numeric-sort":"none","-V":"none","--version-sort":"none","-g":"none","--general-numeric-sort":"none","-M":"none","--month-sort":"none"}},grep:{safeFlags:{"-i":"none","--ignore-case":"none","-v":"none","--invert-match":"none","-c":"none","--count":"none","-l":"none","--files-with-matches":"none","-L":"none","--files-without-match":"none","-n":"none","--line-number":"none","-H":"none","--with-filename":"none","-h":"none","--no-filename":"none","-r":"none","-R":"none","--recursive":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","-P":"none","--perl-regexp":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","-m":"number","--max-count":"number","--color":"string","--colour":"string","-e":"string","--regexp":"string","--include":"string","--exclude":"string","--exclude-dir":"string","-o":"none","--only-matching":"none","-q":"none","--quiet":"none","--silent":"none","-s":"none","--no-messages":"none","-Z":"none","--null":"none"}},tree:{safeFlags:{"-L":"number","-d":"none","-a":"none","-f":"none","-i":"none","-l":"none","-s":"none","-h":"none","-p":"none","-u":"none","-g":"none","-D":"none","-r":"none","-t":"none","--noreport":"none","--dirsfirst":"none","-C":"none","--color":"none","-n":"none","-I":"string","-P":"string","--charset":"string","-o":"string","--prune":"none","-J":"none","-X":"none","-H":"string"}},date:{safeFlags:{"-u":"none","--utc":"none","-d":"string","--date":"string","-I":"none","--iso-8601":"none","-R":"none","--rfc-2822":"none","--rfc-3339":"string"}},ps:{safeFlags:{"-e":"none","-f":"none","-l":"none","-a":"none","-u":"none","-x":"none","-o":"string","--sort":"string","-p":"string","--pid":"string","-C":"string","--forest":"none","-H":"none","--headers":"none","--no-headers":"none","-w":"none","--width":"number"}},lsof:{safeFlags:{"-i":"string","-p":"string","-n":"none","-P":"none","-t":"none","-c":"string","-u":"string","-d":"string","-a":"none"}},netstat:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none"}},man:{safeFlags:{"-k":"string","--apropos":"string","-f":"string","--whatis":"string"}},sed:{safeFlags:{"-n":"none","--quiet":"none","--silent":"none","-E":"none","-r":"none","--regexp-extended":"none","-e":"string","--expression":"string"},isDangerousCallback:($,W)=>{for(let Z of W){if(Z==="-i"||Z.startsWith("-i")||Z==="--in-place")return!0;if(/\bw\s/.test(Z)||/\bw$/.test(Z))return!0}return!1}},base64:{safeFlags:{"-d":"none","--decode":"none","-w":"number","--wrap":"number","-i":"none","--ignore-garbage":"none"}},sha256sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","-t":"none","--text":"none","--tag":"none","--status":"none","-w":"none","--warn":"none","--strict":"none","--quiet":"none"}},sha1sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},md5sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},hostname:{safeFlags:{"-s":"none","-f":"none","--fqdn":"none","-d":"none","-i":"none","-I":"none","-a":"none"}},pgrep:{safeFlags:{"-l":"none","-a":"none","-f":"none","-x":"none","-n":"none","-o":"none","-c":"none","-d":"string","-u":"string","-U":"string","-P":"string","-G":"string","-t":"string"}},ss:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none","-4":"none","-6":"none","-m":"none","-Z":"none","-K":"none"}},fd:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none","--prune":"none","-u":"none","--unrestricted":"none","-S":"string","--size":"string","--changed-within":"string","--changed-before":"string","-j":"number","--threads":"number"}},fdfind:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none"}},tput:{safeFlags:{"-S":"none"}},help:{safeFlags:{}},info:{safeFlags:{}}};function e4($){let W=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${W}(?:\\s|$)[^<>()$\`|{}&;\\n\\r]*$`)}var $7=["docker ps","docker images","cal","uptime","cat","head","tail","wc","stat","strings","hexdump","od","nl","id","uname","free","df","du","locale","groups","nproc","basename","dirname","realpath","cut","paste","tr","column","tac","rev","fold","expand","unexpand","fmt","comm","cmp","numfmt","readlink","diff","true","false","sleep","which","type","expr","test","getconf","seq","tsort","pr"],W7=[/^echo(?:\s+(?:'[^']*'|"[^"$<>\n\r]*"|[^|;&`$(){}><#\\!"'\s]+))*(?:\s+2>&1)?\s*$/,/^uniq(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?|-[fsw]\s+\d+))*(?:\s|$)\s*$/,/^pwd$/,/^whoami$/,/^alias$/,/^node\s+(-v|--version)\s*$/,/^python\s+--version\s*$/,/^python3\s+--version\s*$/,/^bun\s+--version\s*$/,/^deno\s+--version\s*$/,/^history(?:\s+\d+)?\s*$/,/^arch(?:\s+(?:--help|-h))?\s*$/,/^ip\s+addr$/,/^ifconfig(?:\s+[a-zA-Z][a-zA-Z0-9_-]*)?\s*$/,/^ls(?:\s+[^<>()$`|{}&;\n\r]*)?\s*$/,/^cd(?:\s+(?:'[^']*'|"[^"]*"|[^\s;|&`$(){}><#\\]+))?$/,/^find(?:\s+(?:\\[()]|(?!-delete\b|-exec\b|-execdir\b|-ok\b|-okdir\b|-fprint0?\b|-fls\b|-fprintf\b)[^<>()$`|{}&;\n\r\s]|\s)+)?$/,/^jq(?!\s+.*(?:-f\b|--from-file|--rawfile|--slurpfile|--run-tests|-L\b|--library-path|\benv\b|\$ENV\b))(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?))*(?:\s+'[^'`]*'|\s+"[^"`]*"|\s+[^-\s'"][^\s]*)+\s*$/],Z7=[...$7.map(e4),...W7];function m1($,W){switch(W){case"none":return!1;case"number":return/^\d+$/.test($);case"string":return!0}}function Y7($,W,Z){let Y=W,J=Z.respectsDoubleDash!==!1;while(Y<$.length){let X=$[Y];if(X==="--"&&J)break;if(!X.startsWith("-")){Y++;continue}if(X.startsWith("--")){let K=X.indexOf("="),Q=K!==-1,U=Q?X.substring(0,K):X,q=Z.safeFlags[U];if(q===void 0)return!1;if(q==="none"){if(Q)return!1;Y++;continue}if(Q){let w=X.substring(K+1);if(!m1(w,q))return!1;Y++}else{if(Y++,Y>=$.length)return!1;let w=$[Y];if(q==="string"&&w.startsWith("-")){if(U!=="--sort")return!1}if(!m1(w,q))return!1;Y++}continue}let V=X;if(/^-\d+$/.test(V)){Y++;continue}let H=Z.safeFlags[V];if(H!==void 0){if(H==="none"){Y++;continue}if(Y++,Y>=$.length)return!1;let K=$[Y];if(!m1(K,H))return!1;Y++;continue}let B=V.indexOf("=");if(B!==-1){let K=V.substring(0,B),Q=Z.safeFlags[K];if(Q===void 0)return!1;let U=V.substring(B+1);if(Q!=="none"&&!m1(U,Q))return!1;Y++;continue}if(/^-[A-Za-z]\d+$/.test(V)){let K=V.substring(0,2);if(Z.safeFlags[K]==="number"){Y++;continue}}if(/^-[A-Za-z]{2,}$/.test(V)){let K=!0;for(let Q=1;Q<V.length;Q++){let U=`-${V[Q]}`;if(Z.safeFlags[U]!=="none"){K=!1;break}}if(K){Y++;continue}}return!1}return!0}function J7($){for(let W=Math.min(3,$.length);W>=1;W--){let Z=$.slice(0,W).join(" "),Y=t4[Z];if(Y)return[Z,Y,W]}return null}function X7($){let W=Q5($);if(W.length===0)return!1;let Z=J7(W);if(!Z)return!1;let[Y,J,X]=Z,V=W.slice(X);for(let H of V)if(H.includes("$"))return!1;for(let H of V)if(H.includes("{")&&(H.includes(",")||H.includes("..")))return!1;if(!Y7(W,X,J))return!1;if(J.regex&&!J.regex.test($))return!1;if(J.isDangerousCallback&&J.isDangerousCallback($,V))return!1;if(Y==="grep"||Y==="rg"){for(let H of V)if(H.includes(`
725
- `)||H.includes("\r"))return!1}return!0}function V7($){for(let W of Z7)if(W.test($))return!0;return!1}function H7($){let W=!1,Z=!1,Y=!1;for(let J=0;J<$.length;J++){let X=$[J];if(Y){Y=!1;continue}if(X==="\\"&&!W){Y=!0;continue}if(X==="'"&&!Z){W=!W;continue}if(X==='"'&&!W){Z=!Z;continue}if(W)continue;if(X==="$"){let V=$[J+1];if(V&&/[A-Za-z_@*#?!$0-9({-]/.test(V))return!0}if(X==="`")return!0}return!1}function B7($){let W=$.replace(/\s+2>&1\s*$/,"").trim();if(!W)return!1;if(H7(W))return!1;if(X7(W))return!0;if(V7(W)){if(/\bgit\b/.test(W)){if(/\s-c\s/.test(W)||/--exec-path/.test(W)||/--config-env/.test(W))return!1}return!0}return!1}function j5($){let W=$.trim();if(!W)return!1;let Z=K5(W);if(Z===null)return!1;if(Z.length>1){let Y=!1,J=!1;for(let X of Z){let V=E$(s0(X.trim()));if(/^cd\b/.test(V))Y=!0;if(/\bgit\b/.test(V))J=!0}if(Y&&J)return!1}for(let Y of Z){let J=Y.trim();if(!J)continue;let X=E$(s0(J));if(!X)return!1;if(!B7(X))return!1}return!0}import K7 from"node:os";import _W from"node:path";class jW{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let W=this.normalizePath($),Z=_W.basename(W);for(let Y of this.SENSITIVE_PATTERNS)if(this.matchPattern(Z,Y.pattern))return{isSensitive:!0,level:Y.level,matchedPattern:Y.pattern instanceof RegExp?Y.pattern.source:Y.pattern,reason:Y.description};for(let Y of this.SENSITIVE_PATHS)if(this.matchPattern(W,Y.path))return{isSensitive:!0,level:Y.level,matchedPattern:Y.path instanceof RegExp?Y.path.source:Y.path,reason:Y.description};return{isSensitive:!1}}static checkMultiple($){let W=new Map;for(let Z of $)W.set(Z,this.check(Z));return W}static filterSensitive($,W="low"){let Z={["high"]:3,["medium"]:2,["low"]:1},Y=Z[W];return $.map((J)=>({path:J,result:this.check(J)})).filter(({result:J})=>J.isSensitive&&J.level&&Z[J.level]>=Y)}static normalizePath($){if($.startsWith("~/")||$==="~")return _W.join(K7.homedir(),$.slice(1));return _W.resolve($)}static matchPattern($,W){if(W instanceof RegExp)return W.test($);let Z=W.replace(/\*/g,".*");return new RegExp(`^${Z}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class NW{sessionApprovals;defaultPermissionMode;permissionChecker;constructor($,W,Z){this.sessionApprovals=W;this.defaultPermissionMode=Z;this.permissionChecker=new z$($)}getPermissionChecker(){return this.permissionChecker}resolveRulePermission($,W,Z,Y){let J=W.getAffectedPaths(),X={toolName:$.name,params:Z,affectedPaths:J,tool:$},V=z$.buildSignature(X),H=this.permissionChecker.check(X);if(H.result==="ask"&&!H.matchedRule&&$.name==="Bash"&&typeof Z.command==="string"&&j5(Z.command))H={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"};if(H=this.applyModeOverrides($.kind,H,Y.permissionMode??this.defaultPermissionMode),H.result==="ask"&&this.sessionApprovals.has(V))H={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};return H=this.applySafetyOverrides(J,H),{decision:Q7(H),signature:V}}applyModeOverrides($,W,Z){if(Z==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(Z==="plan"&&!AW($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"};if(W.result!=="ask")return W;if(AW($))return{result:"allow",matchedRule:`mode:${Z}:readonly`,reason:"Read-only tools do not require confirmation"};if(Z==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return W}applySafetyOverrides($,W){if(!$?.length)return W;let Z=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],Y=$.filter((H)=>H.includes("..")||Z.some((B)=>H.includes(B)));if(Y.length>0)return{result:"deny",matchedRule:"safety:dangerous-system-path",reason:`Access to dangerous system paths denied: ${Y.join(", ")}`};let J=jW.filterSensitive($,"medium");if(J.length===0)return W;let X=J.map(({path:H,result:B})=>`${H} (${B.level}: ${B.reason})`);if(J.some(({result:H})=>H.level==="high")&&W.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
724
+ `)+"\n```",Q=typeof Y.llmContent==="string"?Y.llmContent:Y.llmContent?JSON.stringify(Y.llmContent):"";Y.llmContent=`${Q}${U}`,R5.info(`[AutoVerify] injected ${H.length} diagnostic(s) (${q0.basename(X)})`)}var r4={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class h0{static instance=null;buckets;constructor($={}){let W={...r4,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:W.readonly,queue:[]},write:{inFlight:0,maxConcurrent:W.write,queue:[]},execute:{inFlight:0,maxConcurrent:W.execute,queue:[]}}}static getInstance(){if(!h0.instance)h0.instance=new h0;return h0.instance}static resetInstance(){h0.instance=null}schedule($,W){let Z=this.buckets[$];if(!Z)return W();if(Z.inFlight<Z.maxConcurrent)return this.runImmediately(Z,W);return new Promise((Y,J)=>{Z.queue.push({fn:W,resolve:Y,reject:J})})}async runImmediately($,W){$.inFlight++;try{return await W()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let W=$.queue.shift();$.inFlight++,W.fn().then(W.resolve,W.reject).finally(()=>{$.inFlight--,this.drain($)})}}getStats(){return{readonly:{inFlight:this.buckets["readonly"].inFlight,queued:this.buckets["readonly"].queue.length},write:{inFlight:this.buckets["write"].inFlight,queued:this.buckets["write"].queue.length},execute:{inFlight:this.buckets["execute"].inFlight,queued:this.buckets["execute"].queue.length}}}}var zW=f("Execution");class e0{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!e0.instance)e0.instance=new e0;return e0.instance}async acquireLock($,W){let Z=this.locks.get($);if(Z)try{await Z}catch{}let Y=this.executeWithLock($,W);return this.locks.set($,Y.then(()=>{return})),Y}async executeWithLock($,W){zW.debug(`获取文件锁: ${$}`);try{let Z=await W();return zW.debug(`释放文件锁: ${$}`),Z}catch(Z){throw zW.debug(`操作失败,释放文件锁: ${$}`),Z}}isLocked($){return this.locks.has($)}clearLock($){this.locks.delete($)}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){e0.instance=null}}import J1 from"picomatch";class z${config;constructor($){this.config=$}check($){let W=z$.buildSignature($),Z=$.toolName==="Bash"&&typeof $.params.command==="string",Y=Z?String($.params.command).trim():"",J=null;if(Z){let B=E$(s0(Y));if(B!==Y)J=`Bash(${B})`}let X=null;if(Z){let B=B5(s0(Y));if(B!==Y)X=`Bash(${B})`}let V=[W];if(X)V.push(X);for(let B of V){let U=this.matchRules(B,this.config.deny);if(U)return{result:"deny",matchedRule:U.rule,matchType:U.type,reason:`工具调用被拒绝规则阻止: ${U.rule}`}}let H=[W];if(J)H.push(J);for(let B of H){let U=this.matchRules(B,this.config.allow);if(U)return{result:"allow",matchedRule:U.rule,matchType:U.type,reason:`工具调用符合允许规则: ${U.rule}`}}let K=[W];if(X)K.push(X);for(let B of K){let U=this.matchRules(B,this.config.ask);if(U)return{result:"ask",matchedRule:U.rule,matchType:U.type,reason:`工具调用需要用户确认: ${U.rule}`}}return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:W,params:Z,tool:Y}=$;try{if(Y?.extractSignatureContent){let J=Y.extractSignatureContent(Z);return J?`${W}(${J})`:W}return W}catch(J){return console.warn(`Failed to build signature for ${W}:`,J instanceof Error?J.message:J),W}}static abstractPattern($){let{toolName:W,params:Z,tool:Y}=$;try{if(Y?.abstractPermissionRule){let J=Y.abstractPermissionRule(Z);if(J==="")return"";return J?`${W}(${J})`:W}return W}catch(J){return console.warn(`Failed to abstract pattern for ${W}:`,J instanceof Error?J.message:J),W}}matchRules($,W){for(let Z of W){let Y=this.matchRule($,Z);if(Y)return{rule:Z,type:Y}}return null}matchRule($,W){if($===W)return"exact";if(W==="*"||W==="**")return"wildcard";let Z=this.extractToolName($),Y=this.extractToolName(W);if(!Z||!Y)return null;if(Y.includes("*")){if(!J1.isMatch(Z,Y,{dot:!0,bash:!0}))return null}else if(Z!==Y)return null;if(W===Y)return"prefix";if(W.includes("*")){let J=this.extractParams($),X=this.extractParams(W);if(X==="*"||X==="**")return"wildcard";if(this.matchParams(J,X))return X.includes("**")?"glob":"wildcard";if(J1.isMatch($,W,{dot:!0,bash:!0}))return W.includes("**")?"glob":"wildcard"}return null}extractParams($){let W=$.match(/\(([\s\S]*)\)$/);return W?W[1]:""}matchParams($,W){if(!$||!W)return!1;let Z=this.parseParamPairs($),Y=this.parseParamPairs(W),J=Object.keys(Y).length>0,X=Object.keys(Z).length>0;if(J!==X)return!1;if(!J&&!X){if(W==="*"||W==="**")return!0;if(W.includes("*")||W.includes("{")||W.includes("?"))return J1.isMatch($,W,{dot:!0,bash:!0});return $===W}for(let[V,H]of Object.entries(Y)){let K=Z[V];if(K===void 0)return!1;if(H.includes("*")||H.includes("{")||H.includes("?")){if(H==="*"||H==="**")continue;if(!J1.isMatch(K,H,{dot:!0,bash:!0}))return!1}else if(K!==H)return!1}return!0}parseParamPairs($){let W={},Z=this.smartSplit($,",");for(let Y of Z){let J=this.findTopLevelDelimiter(Y,":");if(J>0){let X=Y.slice(0,J).trim(),V=Y.slice(J+1).trim();W[X]=V}}return W}smartSplit($,W){let Z=[],Y="",J=0,X=0,V=0,H=!1,K="",B=!1;for(let U=0;U<$.length;U++){let Q=$[U];if(B){Y+=Q,B=!1;continue}if(Q==="\\"){Y+=Q,B=!0;continue}if(!H&&Q==="{")J++;else if(!H&&Q==="}")J--;else if(!H&&Q==="(")X++;else if(!H&&Q===")")X--;else if(!H&&Q==="[")V++;else if(!H&&Q==="]")V--;if((Q==='"'||Q==="'")&&!H){H=!0,K=Q,Y+=Q;continue}else if(H&&Q===K){H=!1,K="",Y+=Q;continue}if(Q===W&&J===0&&X===0&&V===0&&!H)Z.push(Y.trim()),Y="";else Y+=Q}if(Y)Z.push(Y.trim());return Z}findTopLevelDelimiter($,W){let Z=0,Y=0,J=0,X=!1,V="",H=!1;for(let K=0;K<$.length;K++){let B=$[K];if(H){H=!1;continue}if(B==="\\"){H=!0;continue}if(!X&&B==="{")Z++;else if(!X&&B==="}")Z--;else if(!X&&B==="(")Y++;else if(!X&&B===")")Y--;else if(!X&&B==="[")J++;else if(!X&&B==="]")J--;if((B==='"'||B==="'")&&!X){X=!0,V=B;continue}else if(X&&B===V){X=!1,V="";continue}if(B===W&&Z===0&&Y===0&&J===0&&!X)return K}return-1}extractToolName($){let W=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return W?W[1]:null}isAllowed($){return this.check($).result==="allow"}isDenied($){return this.check($).result==="deny"}needsConfirmation($){return this.check($).result==="ask"}updateConfig($){if($.allow)this.config.allow=[...this.config.allow,...$.allow];if($.ask)this.config.ask=[...this.config.ask,...$.ask];if($.deny)this.config.deny=[...this.config.deny,...$.deny]}replaceConfig($){this.config={...$}}getConfig(){return{...this.config}}}var RW={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},OW={"--since":"string","--after":"string","--until":"string","--before":"string"},_W={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},u1={"--max-count":"number","-n":"number"},p1={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},S$={"--color":"none","--no-color":"none"},d1={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},D5={"--author":"string","--committer":"string","--grep":"string"},g1={"--format":"string","--pretty":"string"},n4={"git diff":{safeFlags:{...p1,...S$,...d1,"--cached":"none","--staged":"none","--no-index":"none","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","-U":"number","--unified":"number","--compact-summary":"none","--ignore-space-change":"none","-b":"none","--ignore-all-space":"none","-w":"none","--ignore-blank-lines":"none","--src-prefix":"string","--dst-prefix":"string","--no-prefix":"none","-R":"none","--relative":"none","--histogram":"none","--patience":"none","--minimal":"none","--check":"none","--ext-diff":"none","--binary":"none","--abbrev":"none","--full-index":"none","--break-rewrites":"none","-B":"none","--find-renames":"none","-M":"none","--find-copies":"none","-C":"none","--diff-algorithm":"string"}},"git log":{safeFlags:{...RW,...OW,..._W,...u1,...p1,...S$,...d1,...D5,...g1,"--follow":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--simplify-by-decoration":"none","--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","--topo-order":"none","--diff-filter":"string","--skip":"number","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--walk-reflogs":"none","-g":"none","--boundary":"none","--source":"none"}},"git show":{safeFlags:{...p1,...S$,...d1,...g1,"--abbrev-commit":"none","--no-abbrev-commit":"none","--abbrev":"number","-U":"number","--unified":"number","--diff-filter":"string","--word-diff":"none","--word-diff-regex":"string","--compact-summary":"none"}},"git shortlog":{safeFlags:{...RW,...OW,...u1,...D5,"-s":"none","--summary":"none","-n":"number","--numbered":"none","-e":"none","--email":"none","--group":"string","--format":"string"}},"git reflog":{safeFlags:{..._W,...u1,...S$,...g1,"--date":"string"},isDangerousCallback:($,W)=>{let Z=new Set(["expire","delete","exists"]);for(let Y of W)if(Z.has(Y))return!0;return!1}},"git stash list":{safeFlags:{..._W,...S$,...g1}},"git stash show":{safeFlags:{...p1,...S$,...d1,"-U":"number","--unified":"number","--include-untracked":"none","-u":"none"}},"git ls-remote":{safeFlags:{"--heads":"none","--tags":"none","--refs":"none","--quiet":"none","-q":"none","--get-url":"none","--sort":"string","--symref":"none"}},"git status":{safeFlags:{"--short":"none","-s":"none","--branch":"none","-b":"none","--porcelain":"none","--long":"none","--verbose":"none","-v":"none","--untracked-files":"none","-u":"none","--ignored":"none","--ignore-submodules":"none","--column":"none","--no-column":"none","--ahead-behind":"none","--no-ahead-behind":"none","--renames":"none","--no-renames":"none","--show-stash":"none"}},"git blame":{safeFlags:{"-L":"string","--line-porcelain":"none","--porcelain":"none","-p":"none","--show-name":"none","--show-number":"none","-n":"none","--show-email":"none","-e":"none","-w":"none","-M":"none","-C":"none","--date":"string","--color-lines":"none","--color-by-age":"none","--abbrev":"number","-s":"none","--score-debug":"none","--first-parent":"none","--root":"none","--since":"string"}},"git ls-files":{safeFlags:{"--cached":"none","-c":"none","--deleted":"none","-d":"none","--modified":"none","-m":"none","--others":"none","-o":"none","--ignored":"none","-i":"none","--stage":"none","-s":"none","--unmerged":"none","-u":"none","--killed":"none","-k":"none","--exclude":"string","-x":"string","--exclude-from":"string","-X":"string","--exclude-per-directory":"string","--exclude-standard":"none","--error-unmatch":"none","--full-name":"none","--recurse-submodules":"none","-z":"none","--eol":"none","--deduplicate":"none"}},"git config --get":{safeFlags:{"--global":"none","--system":"none","--local":"none","--worktree":"none","--get-regexp":"none","--list":"none","-l":"none","--show-origin":"none","--show-scope":"none","-z":"none","--null":"none","--name-only":"none","--type":"string","--default":"string"}},"git remote show":{safeFlags:{"-n":"none"},isDangerousCallback:($,W)=>{let Z=W.filter((Y)=>!Y.startsWith("-"));if(Z.length!==1)return!0;return!/^[a-zA-Z0-9_.-]+$/.test(Z[0])}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},isDangerousCallback:($,W)=>{return W.filter((Y)=>!Y.startsWith("-")).length>0}},"git merge-base":{safeFlags:{"--all":"none","--octopus":"none","--is-ancestor":"none","--independent":"none","--fork-point":"none"}},"git rev-parse":{safeFlags:{"--verify":"none","--quiet":"none","-q":"none","--short":"none","--symbolic":"none","--symbolic-full-name":"none","--abbrev-ref":"none","--show-toplevel":"none","--show-cdup":"none","--show-prefix":"none","--show-superproject-working-tree":"none","--git-dir":"none","--git-common-dir":"none","--git-path":"string","--is-inside-git-dir":"none","--is-inside-work-tree":"none","--is-bare-repository":"none","--is-shallow-repository":"none","--absolute-git-dir":"none","--resolve-git-dir":"string","--all":"none","--branches":"none","--tags":"none","--remotes":"none","--glob":"string","--exclude":"string"}},"git rev-list":{safeFlags:{...RW,...OW,...u1,"--count":"none","--objects":"none","--no-walk":"none","--first-parent":"none","--merges":"none","--no-merges":"none","--reverse":"none","--ancestry-path":"none","--topo-order":"none","--left-right":"none","--cherry-pick":"none","--cherry-mark":"none","--cherry":"none","--boundary":"none","--abbrev-commit":"none","--abbrev":"number","--header":"none","--skip":"number"}},"git describe":{safeFlags:{"--all":"none","--tags":"none","--contains":"none","--abbrev":"number","--long":"none","--first-parent":"none","--always":"none","--match":"string","--exclude":"string","--exact-match":"none","--dirty":"none","--broken":"none","--candidates":"number","--debug":"none"}},"git cat-file":{safeFlags:{"-t":"none","-s":"none","-e":"none","-p":"none","--batch":"none","--batch-check":"none","--batch-all-objects":"none","--textconv":"none","--filters":"none","--allow-unknown-type":"none","--buffer":"none","--unordered":"none"}},"git for-each-ref":{safeFlags:{"--format":"string","--sort":"string","--count":"number","--shell":"none","--perl":"none","--python":"none","--tcl":"none","--points-at":"string","--merged":"string","--no-merged":"string","--contains":"string","--no-contains":"string"}},"git grep":{safeFlags:{"-i":"none","--ignore-case":"none","-w":"none","--word-regexp":"none","-v":"none","--invert-match":"none","-n":"none","--line-number":"none","-l":"none","--files-with-matches":"none","--name-only":"none","-L":"none","--files-without-match":"none","-c":"none","--count":"none","--color":"none","--no-color":"none","-e":"string","-f":"string","--and":"none","--or":"none","--not":"none","--all-match":"none","-E":"none","--extended-regexp":"none","-G":"none","--basic-regexp":"none","-P":"none","--perl-regexp":"none","-F":"none","--fixed-strings":"none","--cached":"none","--untracked":"none","--no-index":"none","--recurse-submodules":"none","--max-depth":"number","-h":"none","--no-filename":"none","-H":"none","--full-name":"none","-z":"none","--break":"none","--heading":"none","-p":"none","--show-function":"none","-W":"none","--function-context":"none","--threads":"number","-O":"string","--open-files-in-pager":"none","-A":"number","-B":"number","-C":"number","--context":"number"}},"git worktree list":{safeFlags:{"--porcelain":"none","-z":"none","-v":"none","--verbose":"none","--expire":"string"}},"git tag":{safeFlags:{"-l":"none","--list":"none","-n":"number","--sort":"string","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--format":"string","--color":"none","--no-color":"none"},isDangerousCallback:($,W)=>{if(W.some((J)=>J==="-l"||J==="--list"))return!1;return W.filter((J)=>!J.startsWith("-")).length>0}},"git branch":{safeFlags:{"-l":"none","--list":"none","-a":"none","--all":"none","-r":"none","--remotes":"none","-v":"none","--verbose":"none","-vv":"none","--sort":"string","--format":"string","--color":"none","--no-color":"none","--column":"none","--no-column":"none","--contains":"string","--no-contains":"string","--merged":"string","--no-merged":"string","--points-at":"string","--abbrev":"number","--no-abbrev":"none","--show-current":"none"},isDangerousCallback:($,W)=>{let Z=new Set(["-l","--list","-a","--all","-r","--remotes","--show-current"]);if(W.some((V)=>Z.has(V)))return!1;let J=new Set(["-d","-D","-m","-M","-c","--copy","--delete","--move","--set-upstream-to","--unset-upstream","--edit-description"]);if(W.some((V)=>J.has(V.split("=")[0])))return!0;return W.filter((V)=>!V.startsWith("-")).length>0}}};function m($,W){for(let Z of W){if(Z.includes("://")||Z.includes("@"))return!0;if((Z.match(/\//g)||[]).length>=2)return!0}return!1}var c={"--json":"string","--jq":"string","--template":"string","-q":"none","--limit":"number","-L":"number","--web":"none","-w":"none","--comments":"none"},a4={"gh pr view":{safeFlags:{...c},isDangerousCallback:m},"gh pr list":{safeFlags:{...c,"--state":"string","-s":"string","--author":"string","--label":"string","--base":"string","--head":"string","--search":"string","--assignee":"string","--draft":"none"},isDangerousCallback:m},"gh pr diff":{safeFlags:{...c,"--color":"string","--patch":"none","--name-only":"none"},isDangerousCallback:m},"gh pr checks":{safeFlags:{...c,"--watch":"none","--fail-fast":"none","--required":"none"},isDangerousCallback:m},"gh pr status":{safeFlags:{...c},isDangerousCallback:m},"gh issue view":{safeFlags:{...c},isDangerousCallback:m},"gh issue list":{safeFlags:{...c,"--state":"string","-s":"string","--author":"string","--label":"string","--search":"string","--assignee":"string","--milestone":"string"},isDangerousCallback:m},"gh issue status":{safeFlags:{...c},isDangerousCallback:m},"gh repo view":{safeFlags:{...c},isDangerousCallback:m},"gh run list":{safeFlags:{...c,"--workflow":"string","-w":"string","--branch":"string","-b":"string","--status":"string","-s":"string","--user":"string","-u":"string","--event":"string","-e":"string"},isDangerousCallback:m},"gh run view":{safeFlags:{...c,"--log":"none","--log-failed":"none","--exit-status":"none","--verbose":"none","-v":"none","--job":"string","-j":"string"},isDangerousCallback:m},"gh auth status":{safeFlags:{"--hostname":"string","-h":"string","--active":"none"},isDangerousCallback:($,W)=>{return W.some((Z)=>Z==="--show-token"||Z==="-t")}},"gh release list":{safeFlags:{...c,"--exclude-drafts":"none","--exclude-pre-releases":"none"},isDangerousCallback:m},"gh release view":{safeFlags:{...c},isDangerousCallback:m},"gh workflow list":{safeFlags:{...c,"--all":"none","-a":"none"},isDangerousCallback:m},"gh workflow view":{safeFlags:{...c,"--yaml":"none","-y":"none","--ref":"string","-r":"string"},isDangerousCallback:m},"gh label list":{safeFlags:{...c,"--search":"string","--sort":"string","--order":"string"},isDangerousCallback:m},"gh search repos":{safeFlags:{...c,"--language":"string","--topic":"string","--sort":"string","--order":"string","--match":"string","--owner":"string","--visibility":"string"},isDangerousCallback:m},"gh search issues":{safeFlags:{...c,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:m},"gh search prs":{safeFlags:{...c,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:m},"gh search commits":{safeFlags:{...c,"--sort":"string","--order":"string","--author":"string","--committer":"string","--repo":"string"},isDangerousCallback:m},"gh search code":{safeFlags:{...c,"--language":"string","--filename":"string","--extension":"string","--repo":"string","--match":"string"},isDangerousCallback:m}},o4={"docker logs":{safeFlags:{"--follow":"none","-f":"none","--tail":"number","-n":"number","--timestamps":"none","-t":"none","--since":"string","--until":"string","--details":"none"}},"docker inspect":{safeFlags:{"--format":"string","-f":"string","--type":"string","--size":"none","-s":"none"}}},s4={rg:{safeFlags:{"-e":"string","--regexp":"string","-F":"none","--fixed-strings":"none","-i":"none","--ignore-case":"none","-S":"none","--smart-case":"none","-s":"none","--case-sensitive":"none","-v":"none","--invert-match":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-P":"none","--pcre2":"none","--engine":"string","-m":"number","--max-count":"number","--max-depth":"number","--maxdepth":"number","-d":"number","--max-filesize":"string","--mmap":"none","--no-mmap":"none","-U":"none","--multiline":"none","--multiline-dotall":"none","--crlf":"none","--no-crlf":"none","-c":"none","--count":"none","--count-matches":"none","-l":"none","--files-with-matches":"none","--files-without-match":"none","-o":"none","--only-matching":"none","--vimgrep":"none","-r":"string","--replace":"string","-t":"string","--type":"string","-T":"string","--type-not":"string","-g":"string","--glob":"string","--iglob":"string","--type-add":"string","--type-clear":"string","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","--color":"string","--colors":"string","-n":"none","--line-number":"none","-N":"none","--no-line-number":"none","-H":"none","--with-filename":"none","--no-filename":"none","-p":"none","--pretty":"none","--heading":"none","--no-heading":"none","--column":"none","--no-column":"none","--byte-offset":"none","--trim":"none","-j":"number","--threads":"number","--sort":"string","--sortr":"string","--stats":"none","--no-ignore":"none","--no-ignore-vcs":"none","--no-ignore-parent":"none","--no-ignore-global":"none","--hidden":"none","--no-hidden":"none","-L":"none","--follow":"none","--one-file-system":"none","--null":"none","-0":"none","--path-separator":"string","--no-config":"none","--no-ignore-dot":"none","--no-ignore-exclude":"none","--no-unicode":"none","--pcre2-version":"none","-q":"none","--quiet":"none","--help":"none","-h":"none","--version":"none","-V":"none","--":"none","--json":"none","--auto-hybrid-regex":"none","--binary":"none","--block-buffered":"none","--line-buffered":"none","--debug":"none","--dfa-size-limit":"string","--encoding":"string","-E":"string","--no-messages":"none","--regex-size-limit":"string","--search-zip":"none","-z":"none","--type-list":"none","--unrestricted":"none","-u":"none"}}},t4={...n4,...a4,...o4,...s4,file:{safeFlags:{"-b":"none","--brief":"none","-i":"none","--mime":"none","--mime-type":"none","--mime-encoding":"none","-L":"none","-h":"none","--no-dereference":"none","-z":"none"}},sort:{safeFlags:{"-r":"none","--reverse":"none","-n":"none","--numeric-sort":"none","-u":"none","--unique":"none","-k":"string","--key":"string","-t":"string","--field-separator":"string","-f":"none","--ignore-case":"none","-s":"none","--stable":"none","-h":"none","--human-numeric-sort":"none","-V":"none","--version-sort":"none","-g":"none","--general-numeric-sort":"none","-M":"none","--month-sort":"none"}},grep:{safeFlags:{"-i":"none","--ignore-case":"none","-v":"none","--invert-match":"none","-c":"none","--count":"none","-l":"none","--files-with-matches":"none","-L":"none","--files-without-match":"none","-n":"none","--line-number":"none","-H":"none","--with-filename":"none","-h":"none","--no-filename":"none","-r":"none","-R":"none","--recursive":"none","-E":"none","--extended-regexp":"none","-F":"none","--fixed-strings":"none","-P":"none","--perl-regexp":"none","-w":"none","--word-regexp":"none","-x":"none","--line-regexp":"none","-A":"number","--after-context":"number","-B":"number","--before-context":"number","-C":"number","--context":"number","-m":"number","--max-count":"number","--color":"string","--colour":"string","-e":"string","--regexp":"string","--include":"string","--exclude":"string","--exclude-dir":"string","-o":"none","--only-matching":"none","-q":"none","--quiet":"none","--silent":"none","-s":"none","--no-messages":"none","-Z":"none","--null":"none"}},tree:{safeFlags:{"-L":"number","-d":"none","-a":"none","-f":"none","-i":"none","-l":"none","-s":"none","-h":"none","-p":"none","-u":"none","-g":"none","-D":"none","-r":"none","-t":"none","--noreport":"none","--dirsfirst":"none","-C":"none","--color":"none","-n":"none","-I":"string","-P":"string","--charset":"string","-o":"string","--prune":"none","-J":"none","-X":"none","-H":"string"}},date:{safeFlags:{"-u":"none","--utc":"none","-d":"string","--date":"string","-I":"none","--iso-8601":"none","-R":"none","--rfc-2822":"none","--rfc-3339":"string"}},ps:{safeFlags:{"-e":"none","-f":"none","-l":"none","-a":"none","-u":"none","-x":"none","-o":"string","--sort":"string","-p":"string","--pid":"string","-C":"string","--forest":"none","-H":"none","--headers":"none","--no-headers":"none","-w":"none","--width":"number"}},lsof:{safeFlags:{"-i":"string","-p":"string","-n":"none","-P":"none","-t":"none","-c":"string","-u":"string","-d":"string","-a":"none"}},netstat:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none"}},man:{safeFlags:{"-k":"string","--apropos":"string","-f":"string","--whatis":"string"}},sed:{safeFlags:{"-n":"none","--quiet":"none","--silent":"none","-E":"none","-r":"none","--regexp-extended":"none","-e":"string","--expression":"string"},isDangerousCallback:($,W)=>{for(let Z of W){if(Z==="-i"||Z.startsWith("-i")||Z==="--in-place")return!0;if(/\bw\s/.test(Z)||/\bw$/.test(Z))return!0}return!1}},base64:{safeFlags:{"-d":"none","--decode":"none","-w":"number","--wrap":"number","-i":"none","--ignore-garbage":"none"}},sha256sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","-t":"none","--text":"none","--tag":"none","--status":"none","-w":"none","--warn":"none","--strict":"none","--quiet":"none"}},sha1sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},md5sum:{safeFlags:{"-c":"none","--check":"none","-b":"none","--binary":"none","--tag":"none","--status":"none"}},hostname:{safeFlags:{"-s":"none","-f":"none","--fqdn":"none","-d":"none","-i":"none","-I":"none","-a":"none"}},pgrep:{safeFlags:{"-l":"none","-a":"none","-f":"none","-x":"none","-n":"none","-o":"none","-c":"none","-d":"string","-u":"string","-U":"string","-P":"string","-G":"string","-t":"string"}},ss:{safeFlags:{"-t":"none","-u":"none","-l":"none","-n":"none","-p":"none","-a":"none","-r":"none","-s":"none","-e":"none","-o":"none","-i":"none","-4":"none","-6":"none","-m":"none","-Z":"none","-K":"none"}},fd:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none","--prune":"none","-u":"none","--unrestricted":"none","-S":"string","--size":"string","--changed-within":"string","--changed-before":"string","-j":"number","--threads":"number"}},fdfind:{safeFlags:{"-t":"string","--type":"string","-e":"string","--extension":"string","-E":"string","--exclude":"string","-d":"number","--max-depth":"number","-H":"none","--hidden":"none","-I":"none","--no-ignore":"none","-s":"none","--case-sensitive":"none","-i":"none","--ignore-case":"none","-a":"none","--absolute-path":"none","-l":"none","--list-details":"none","-L":"none","--follow":"none","-p":"none","--full-path":"none","-0":"none","--print0":"none","-1":"none","--color":"string","--glob":"none","-g":"none","-F":"none","--fixed-strings":"none"}},tput:{safeFlags:{"-S":"none"}},help:{safeFlags:{}},info:{safeFlags:{}}};function e4($){let W=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${W}(?:\\s|$)[^<>()$\`|{}&;\\n\\r]*$`)}var $7=["docker ps","docker images","cal","uptime","cat","head","tail","wc","stat","strings","hexdump","od","nl","id","uname","free","df","du","locale","groups","nproc","basename","dirname","realpath","cut","paste","tr","column","tac","rev","fold","expand","unexpand","fmt","comm","cmp","numfmt","readlink","diff","true","false","sleep","which","type","expr","test","getconf","seq","tsort","pr"],W7=[/^echo(?:\s+(?:'[^']*'|"[^"$<>\n\r]*"|[^|;&`$(){}><#\\!"'\s]+))*(?:\s+2>&1)?\s*$/,/^uniq(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?|-[fsw]\s+\d+))*(?:\s|$)\s*$/,/^pwd$/,/^whoami$/,/^alias$/,/^node\s+(-v|--version)\s*$/,/^python\s+--version\s*$/,/^python3\s+--version\s*$/,/^bun\s+--version\s*$/,/^deno\s+--version\s*$/,/^history(?:\s+\d+)?\s*$/,/^arch(?:\s+(?:--help|-h))?\s*$/,/^ip\s+addr$/,/^ifconfig(?:\s+[a-zA-Z][a-zA-Z0-9_-]*)?\s*$/,/^ls(?:\s+[^<>()$`|{}&;\n\r]*)?\s*$/,/^cd(?:\s+(?:'[^']*'|"[^"]*"|[^\s;|&`$(){}><#\\]+))?$/,/^find(?:\s+(?:\\[()]|(?!-delete\b|-exec\b|-execdir\b|-ok\b|-okdir\b|-fprint0?\b|-fls\b|-fprintf\b)[^<>()$`|{}&;\n\r\s]|\s)+)?$/,/^jq(?!\s+.*(?:-f\b|--from-file|--rawfile|--slurpfile|--run-tests|-L\b|--library-path|\benv\b|\$ENV\b))(?:\s+(?:-[a-zA-Z]+|--[a-zA-Z-]+(?:=\S+)?))*(?:\s+'[^'`]*'|\s+"[^"`]*"|\s+[^-\s'"][^\s]*)+\s*$/],Z7=[...$7.map(e4),...W7];function m1($,W){switch(W){case"none":return!1;case"number":return/^\d+$/.test($);case"string":return!0}}function Y7($,W,Z){let Y=W,J=Z.respectsDoubleDash!==!1;while(Y<$.length){let X=$[Y];if(X==="--"&&J)break;if(!X.startsWith("-")){Y++;continue}if(X.startsWith("--")){let B=X.indexOf("="),U=B!==-1,Q=U?X.substring(0,B):X,q=Z.safeFlags[Q];if(q===void 0)return!1;if(q==="none"){if(U)return!1;Y++;continue}if(U){let w=X.substring(B+1);if(!m1(w,q))return!1;Y++}else{if(Y++,Y>=$.length)return!1;let w=$[Y];if(q==="string"&&w.startsWith("-")){if(Q!=="--sort")return!1}if(!m1(w,q))return!1;Y++}continue}let V=X;if(/^-\d+$/.test(V)){Y++;continue}let H=Z.safeFlags[V];if(H!==void 0){if(H==="none"){Y++;continue}if(Y++,Y>=$.length)return!1;let B=$[Y];if(!m1(B,H))return!1;Y++;continue}let K=V.indexOf("=");if(K!==-1){let B=V.substring(0,K),U=Z.safeFlags[B];if(U===void 0)return!1;let Q=V.substring(K+1);if(U!=="none"&&!m1(Q,U))return!1;Y++;continue}if(/^-[A-Za-z]\d+$/.test(V)){let B=V.substring(0,2);if(Z.safeFlags[B]==="number"){Y++;continue}}if(/^-[A-Za-z]{2,}$/.test(V)){let B=!0;for(let U=1;U<V.length;U++){let Q=`-${V[U]}`;if(Z.safeFlags[Q]!=="none"){B=!1;break}}if(B){Y++;continue}}return!1}return!0}function J7($){for(let W=Math.min(3,$.length);W>=1;W--){let Z=$.slice(0,W).join(" "),Y=t4[Z];if(Y)return[Z,Y,W]}return null}function X7($){let W=U5($);if(W.length===0)return!1;let Z=J7(W);if(!Z)return!1;let[Y,J,X]=Z,V=W.slice(X);for(let H of V)if(H.includes("$"))return!1;for(let H of V)if(H.includes("{")&&(H.includes(",")||H.includes("..")))return!1;if(!Y7(W,X,J))return!1;if(J.regex&&!J.regex.test($))return!1;if(J.isDangerousCallback&&J.isDangerousCallback($,V))return!1;if(Y==="grep"||Y==="rg"){for(let H of V)if(H.includes(`
725
+ `)||H.includes("\r"))return!1}return!0}function V7($){for(let W of Z7)if(W.test($))return!0;return!1}function H7($){let W=!1,Z=!1,Y=!1;for(let J=0;J<$.length;J++){let X=$[J];if(Y){Y=!1;continue}if(X==="\\"&&!W){Y=!0;continue}if(X==="'"&&!Z){W=!W;continue}if(X==='"'&&!W){Z=!Z;continue}if(W)continue;if(X==="$"){let V=$[J+1];if(V&&/[A-Za-z_@*#?!$0-9({-]/.test(V))return!0}if(X==="`")return!0}return!1}function B7($){let W=$.replace(/\s+2>&1\s*$/,"").trim();if(!W)return!1;if(H7(W))return!1;if(X7(W))return!0;if(V7(W)){if(/\bgit\b/.test(W)){if(/\s-c\s/.test(W)||/--exec-path/.test(W)||/--config-env/.test(W))return!1}return!0}return!1}function j5($){let W=$.trim();if(!W)return!1;let Z=K5(W);if(Z===null)return!1;if(Z.length>1){let Y=!1,J=!1;for(let X of Z){let V=E$(s0(X.trim()));if(/^cd\b/.test(V))Y=!0;if(/\bgit\b/.test(V))J=!0}if(Y&&J)return!1}for(let Y of Z){let J=Y.trim();if(!J)continue;let X=E$(s0(J));if(!X)return!1;if(!B7(X))return!1}return!0}import K7 from"node:os";import DW from"node:path";class jW{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let W=this.normalizePath($),Z=DW.basename(W);for(let Y of this.SENSITIVE_PATTERNS)if(this.matchPattern(Z,Y.pattern))return{isSensitive:!0,level:Y.level,matchedPattern:Y.pattern instanceof RegExp?Y.pattern.source:Y.pattern,reason:Y.description};for(let Y of this.SENSITIVE_PATHS)if(this.matchPattern(W,Y.path))return{isSensitive:!0,level:Y.level,matchedPattern:Y.path instanceof RegExp?Y.path.source:Y.path,reason:Y.description};return{isSensitive:!1}}static checkMultiple($){let W=new Map;for(let Z of $)W.set(Z,this.check(Z));return W}static filterSensitive($,W="low"){let Z={["high"]:3,["medium"]:2,["low"]:1},Y=Z[W];return $.map((J)=>({path:J,result:this.check(J)})).filter(({result:J})=>J.isSensitive&&J.level&&Z[J.level]>=Y)}static normalizePath($){if($.startsWith("~/")||$==="~")return DW.join(K7.homedir(),$.slice(1));return DW.resolve($)}static matchPattern($,W){if(W instanceof RegExp)return W.test($);let Z=W.replace(/\*/g,".*");return new RegExp(`^${Z}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class NW{sessionApprovals;defaultPermissionMode;permissionChecker;constructor($,W,Z){this.sessionApprovals=W;this.defaultPermissionMode=Z;this.permissionChecker=new z$($)}getPermissionChecker(){return this.permissionChecker}resolveRulePermission($,W,Z,Y){let J=W.getAffectedPaths(),X={toolName:$.name,params:Z,affectedPaths:J,tool:$},V=z$.buildSignature(X),H=this.permissionChecker.check(X);if(H.result==="ask"&&!H.matchedRule&&$.name==="Bash"&&typeof Z.command==="string"&&j5(Z.command))H={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"};if(H=this.applyModeOverrides($.kind,H,Y.permissionMode??this.defaultPermissionMode),H.result==="ask"&&this.sessionApprovals.has(V))H={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};return H=this.applySafetyOverrides(J,H),{decision:U7(H),signature:V}}applyModeOverrides($,W,Z){if(Z==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(Z==="plan"&&!AW($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"};if(W.result!=="ask")return W;if(AW($))return{result:"allow",matchedRule:`mode:${Z}:readonly`,reason:"Read-only tools do not require confirmation"};if(Z==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return W}applySafetyOverrides($,W){if(!$?.length)return W;let Z=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],Y=$.filter((H)=>H.includes("..")||Z.some((K)=>H.includes(K)));if(Y.length>0)return{result:"deny",matchedRule:"safety:dangerous-system-path",reason:`Access to dangerous system paths denied: ${Y.join(", ")}`};let J=jW.filterSensitive($,"medium");if(J.length===0)return W;let X=J.map(({path:H,result:K})=>`${H} (${K.level}: ${K.reason})`);if(J.some(({result:H})=>H.level==="high")&&W.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
726
726
  ${X.join(`
727
727
  `)}
728
728
 
@@ -730,7 +730,7 @@ If access is required, add an explicit allow rule in permissions.`};if(W.result=
730
730
  ${X.join(`
731
731
  `)}
732
732
 
733
- Confirm to proceed?`};return W}}function A5($,W){if($?.behavior==="deny")return $;if(W?.behavior==="deny")return W;if(W?.behavior==="ask")return W;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(W?.behavior==="allow")return W;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}function Q7($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}class X1{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}function s($,W={}){return{success:!1,llmContent:W.llmContent??`Tool execution aborted: ${$}`,error:{type:W.errorType??"execution_error",message:$},metadata:{summary:W.summary??`执行已中止: ${$}`,...W.shouldExitLoop?{shouldExitLoop:!0}:{},...W.abortedBeforeLaunch?{abortedBeforeLaunch:!0}:{}}}}function R$($){return s("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:$})}var TW=P("Execution");class LW{sessionApprovals;permissionChecker;constructor($,W){this.sessionApprovals=$;this.permissionChecker=W}async confirmIfNeeded($,W,Z,Y,J,X){if(Y.behavior!=="ask")return;try{let V=await this.runPermissionRequestHook($,Z,X);if(V==="approved")return;if(V)return V;let H={title:$.extractSignatureContent?$.extractSignatureContent(Z):$.name,message:Y.reason||"此操作需要用户确认",kind:$.kind,details:U7($.name,Z),risks:q7($.name,Z),affectedFiles:W.getAffectedPaths()||[]};TW.warn(`工具 "${$.name}" 需要用户确认: ${H.title}`);let B=X.confirmationHandler;if(!B){let Q=X.permissionMode||"default";if(Q==="yolo"){TW.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode");return}return s(`Non-interactive mode with "${Q}" permission: tool "${$.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{llmContent:`工具 "${$.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${Q}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"})}let K=await B.requestConfirmation(H);if(X.signal?.aborted)return s("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(!K.approved)return s(K.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"});if(K.scope==="session")this.sessionApprovals.add(J),await this.persistSessionApproval($,W,Z);return}catch(V){return s(`User confirmation failed: ${V instanceof Error?V.message:String(V)}`)}}async runPermissionRequestHook($,W,Z){let Y=w0.getInstance();if(!Y.isEnabled())return;let J=await Y.executePermissionRequestHooks($.name,Z.sessionId||"unknown",W,{projectDir:Z.workspaceRoot||D(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default"});if(J.decision==="approve")return"approved";if(J.decision==="deny")return s(J.reason||`PermissionRequest hook denied: ${$.name}`,{shouldExitLoop:!0,errorType:"permission_denied"});return}async persistSessionApproval($,W,Z){try{let Y={toolName:$.name,params:Z,affectedPaths:W.getAffectedPaths()||[],tool:$},J=z$.abstractPattern(Y);await a0().appendLocalPermissionAllowRule(J,{immediate:!0});let X=Y0();if(X?.permissions)this.permissionChecker.replaceConfig(X.permissions)}catch(Y){TW.warn(`Failed to persist permission rule: ${Y instanceof Error?Y.message:"Unknown error"}`)}}}function U7($,W){if($==="Edit"){let{old_string:Z,new_string:Y}=W;if(!Z&&!Y)return;return`**变更前:**
733
+ Confirm to proceed?`};return W}}function A5($,W){if($?.behavior==="deny")return $;if(W?.behavior==="deny")return W;if(W?.behavior==="ask")return W;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(W?.behavior==="allow")return W;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}function U7($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}class X1{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}function s($,W={}){return{success:!1,llmContent:W.llmContent??`Tool execution aborted: ${$}`,error:{type:W.errorType??"execution_error",message:$},metadata:{summary:W.summary??`执行已中止: ${$}`,...W.shouldExitLoop?{shouldExitLoop:!0}:{},...W.abortedBeforeLaunch?{abortedBeforeLaunch:!0}:{}}}}function R$($){return s("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:$})}var TW=f("Execution");class LW{sessionApprovals;permissionChecker;constructor($,W){this.sessionApprovals=$;this.permissionChecker=W}async confirmIfNeeded($,W,Z,Y,J,X){if(Y.behavior!=="ask")return;try{let V=await this.runPermissionRequestHook($,Z,X);if(V==="approved")return;if(V)return V;let H={title:$.extractSignatureContent?$.extractSignatureContent(Z):$.name,message:Y.reason||"此操作需要用户确认",kind:$.kind,details:Q7($.name,Z),risks:q7($.name,Z),affectedFiles:W.getAffectedPaths()||[]};TW.warn(`工具 "${$.name}" 需要用户确认: ${H.title}`);let K=X.confirmationHandler;if(!K){let U=X.permissionMode||"default";if(U==="yolo"){TW.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode");return}return s(`Non-interactive mode with "${U}" permission: tool "${$.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{llmContent:`工具 "${$.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${U}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"})}let B=await K.requestConfirmation(H);if(X.signal?.aborted)return s("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});if(!B.approved)return s(B.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"});if(B.scope==="session")this.sessionApprovals.add(J),await this.persistSessionApproval($,W,Z);return}catch(V){return s(`User confirmation failed: ${V instanceof Error?V.message:String(V)}`)}}async runPermissionRequestHook($,W,Z){let Y=w0.getInstance();if(!Y.isEnabled())return;let J=await Y.executePermissionRequestHooks($.name,Z.sessionId||"unknown",W,{projectDir:Z.workspaceRoot||D(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default"});if(J.decision==="approve")return"approved";if(J.decision==="deny")return s(J.reason||`PermissionRequest hook denied: ${$.name}`,{shouldExitLoop:!0,errorType:"permission_denied"});return}async persistSessionApproval($,W,Z){try{let Y={toolName:$.name,params:Z,affectedPaths:W.getAffectedPaths()||[],tool:$},J=z$.abstractPattern(Y);await a0().appendLocalPermissionAllowRule(J,{immediate:!0});let X=Y0();if(X?.permissions)this.permissionChecker.replaceConfig(X.permissions)}catch(Y){TW.warn(`Failed to persist permission rule: ${Y instanceof Error?Y.message:"Unknown error"}`)}}}function Q7($,W){if($==="Edit"){let{old_string:Z,new_string:Y}=W;if(!Z&&!Y)return;return`**变更前:**
734
734
  \`\`\`
735
735
  ${N5(Z||"(空)",20)}
736
736
  \`\`\`
@@ -751,38 +751,38 @@ ${X}
751
751
  ... (还有 ${J.length-30} 行)`}return}function N5($,W){let Z=$.split(`
752
752
  `);return Z.length<=W?$:`${Z.slice(0,W).join(`
753
753
  `)}
754
- ... (还有 ${Z.length-W} 行)`}function q7($,W){let Z=[];if($==="Bash"){let Y=W.command||"";if(Y.includes("rm"))Z.push("[WARN] 此命令可能删除文件");if(Y.includes("sudo"))Z.push("[WARN] 此命令需要管理员权限");if(Y.includes("git push"))Z.push("[WARN] 此命令将推送代码到远程仓库")}else if($==="Write"||$==="Edit")Z.push("此操作将修改文件内容");else if($==="Delete")Z.push("此操作将永久删除文件");return Z}function L5($,W,Z,Y){if(Y?.has($.name))return s(`Tool "${$.name}" is blocked by --disallowed-tools`);if(Z&&!Z.has($.name))return s(`Tool "${$.name}" is not in --allowed-tools whitelist`);try{return{invocation:$.build(W),params:W}}catch(J){return s(`Parameter validation failed: ${J instanceof Error?J.message:String(J)}`,{errorType:"validation_error"})}}async function kW($,W,Z){if(Z.worktreeActive)return w7($,W,Z);let Y=$.name==="Task"&&W.isolation==="worktree";if(!Z.worktreeIsolationRequired||$.name==="EnterWorktree"||Y||$.kind==="readonly"&&$.name!=="Task")return;return s("Blocked side-effecting tool outside the explicitly required worktree",{llmContent:"Worktree isolation is required. Call EnterWorktree and wait for it to succeed before using any write or execute tool.",summary:"Blocked until EnterWorktree succeeds",errorType:"permission_denied"})}async function w7($,W,Z){let J=($.kind==="write"?["file_path","notebook_path","path"]:$.name==="Bash"?["cwd"]:[]).map((V)=>W[V]).filter((V)=>typeof V==="string");if(J.length===0)return;let X=Z.workspaceRoot;if(!X)return T5(J[0],"workspace root is missing");for(let V of J)if(!await P0.isWithinWorkspaceResolved(V,X))return T5(V);return}function T5($,W){let Z=W?` (${W})`:"";return s(`Blocked path outside the active worktree: ${$}${Z}`,{llmContent:`The requested path "${$}" is outside the active worktree. Use a path under the current workspace root.`,summary:"Blocked path outside active worktree",errorType:"permission_denied"})}import{nanoid as k5}from"nanoid";async function b5($,W,Z,Y,J,X=w0.getInstance()){let V={params:W,invocation:Z,inputModified:!1};if(!X.isEnabled()||J.behavior==="deny")return V;try{let H=Y.messageId||`tool_${k5()}`,B=await X.executePreToolHooks($.name,H,W,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(B.warning)console.warn(`[Hook Warning] ${B.warning}`);let K={behavior:B.decision,source:"hook",reason:B.reason};if(!B.modifiedInput||B.decision==="deny")return{...V,decision:K,toolUseId:H};let Q={...W,...B.modifiedInput};try{return{params:Q,invocation:$.build(Q),decision:K,toolUseId:H,inputModified:!0}}catch(U){return{...V,decision:K,toolUseId:H,rejection:s(`Hook modified parameters are invalid: ${U instanceof Error?U.message:String(U)}`,{errorType:"validation_error"})}}}catch(H){return console.error("[ToolExecutionHooks] Error executing pre-tool hooks:",H),V}}async function M5($,W,Z,Y,J,X=w0.getInstance()){if(!X.isEnabled())return;try{let V=J||Y.messageId||`tool_${k5()}`,H=await X.executePostToolHooks($.name,V,W,Z,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(H.additionalContext){let B=typeof Z.llmContent==="string"?Z.llmContent:Z.llmContent?JSON.stringify(Z.llmContent):"";Z.llmContent=`${B}
754
+ ... (还有 ${Z.length-W} 行)`}function q7($,W){let Z=[];if($==="Bash"){let Y=W.command||"";if(Y.includes("rm"))Z.push("[WARN] 此命令可能删除文件");if(Y.includes("sudo"))Z.push("[WARN] 此命令需要管理员权限");if(Y.includes("git push"))Z.push("[WARN] 此命令将推送代码到远程仓库")}else if($==="Write"||$==="Edit")Z.push("此操作将修改文件内容");else if($==="Delete")Z.push("此操作将永久删除文件");return Z}function L5($,W,Z,Y){if(Y?.has($.name))return s(`Tool "${$.name}" is blocked by --disallowed-tools`);if(Z&&!Z.has($.name))return s(`Tool "${$.name}" is not in --allowed-tools whitelist`);try{return{invocation:$.build(W),params:W}}catch(J){return s(`Parameter validation failed: ${J instanceof Error?J.message:String(J)}`,{errorType:"validation_error"})}}async function kW($,W,Z){if(Z.worktreeActive)return w7($,W,Z);let Y=$.name==="Task"&&W.isolation==="worktree";if(!Z.worktreeIsolationRequired||$.name==="EnterWorktree"||Y||$.kind==="readonly"&&$.name!=="Task")return;return s("Blocked side-effecting tool outside the explicitly required worktree",{llmContent:"Worktree isolation is required. Call EnterWorktree and wait for it to succeed before using any write or execute tool.",summary:"Blocked until EnterWorktree succeeds",errorType:"permission_denied"})}async function w7($,W,Z){let J=($.kind==="write"?["file_path","notebook_path","path"]:$.name==="Bash"?["cwd"]:[]).map((V)=>W[V]).filter((V)=>typeof V==="string");if(J.length===0)return;let X=Z.workspaceRoot;if(!X)return T5(J[0],"workspace root is missing");for(let V of J)if(!await f0.isWithinWorkspaceResolved(V,X))return T5(V);return}function T5($,W){let Z=W?` (${W})`:"";return s(`Blocked path outside the active worktree: ${$}${Z}`,{llmContent:`The requested path "${$}" is outside the active worktree. Use a path under the current workspace root.`,summary:"Blocked path outside active worktree",errorType:"permission_denied"})}import{nanoid as k5}from"nanoid";async function b5($,W,Z,Y,J,X=w0.getInstance()){let V={params:W,invocation:Z,inputModified:!1};if(!X.isEnabled()||J.behavior==="deny")return V;try{let H=Y.messageId||`tool_${k5()}`,K=await X.executePreToolHooks($.name,H,W,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(K.warning)console.warn(`[Hook Warning] ${K.warning}`);let B={behavior:K.decision,source:"hook",reason:K.reason};if(!K.modifiedInput||K.decision==="deny")return{...V,decision:B,toolUseId:H};let U={...W,...K.modifiedInput};try{return{params:U,invocation:$.build(U),decision:B,toolUseId:H,inputModified:!0}}catch(Q){return{...V,decision:B,toolUseId:H,rejection:s(`Hook modified parameters are invalid: ${Q instanceof Error?Q.message:String(Q)}`,{errorType:"validation_error"})}}}catch(H){return console.error("[ToolExecutionHooks] Error executing pre-tool hooks:",H),V}}async function M5($,W,Z,Y,J,X=w0.getInstance()){if(!X.isEnabled())return;try{let V=J||Y.messageId||`tool_${k5()}`,H=await X.executePostToolHooks($.name,V,W,Z,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode??"default",abortSignal:Y.signal});if(H.additionalContext){let K=typeof Z.llmContent==="string"?Z.llmContent:Z.llmContent?JSON.stringify(Z.llmContent):"";Z.llmContent=`${K}
755
755
 
756
756
  ---
757
757
  **Hook Context:**
758
- `+H.additionalContext}if(G7(H.modifiedOutput))Object.assign(Z,H.modifiedOutput);if(H.warning)console.warn(`[PostToolUseHook Warning] ${H.warning}`)}catch(V){console.error("[ToolExecutionHooks] Error executing post-tool hooks:",V)}}function G7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var E7=["EBUSY","EAGAIN","EMFILE","ENFILE"];async function v5($,W){let Z=Date.now(),Y;for(let J=0;J<=2;J++)try{let X=await $.execute(W.signal??new AbortController().signal,W.onProgress,W);if(X.metadata??={},X.metadata.duration=Date.now()-Z,J>0)X.metadata.retriedAttempts=J;return X}catch(X){if(Y=X instanceof Error?X:Error(String(X)),J>=2||!E7.some((V)=>Y?.message.includes(V)))break;await F7(200*(J+1))}throw Y??Error("Tool execution failed")}function x5($,W,Z){if(!$.llmContent)$.llmContent="Execution completed";return $.metadata??={},$.metadata.executionId=W,$.metadata.toolName=Z,$.metadata.timestamp=Date.now(),$}function F7($){return new Promise((W)=>setTimeout(W,$))}class V1 extends R7{registry;executionHistory=[];maxHistorySize;scheduler;toolWhitelist;toolBlacklist;permissionResolver;approvalController;constructor($,W={}){super();this.registry=$;this.maxHistorySize=W.maxHistorySize??1000,this.toolWhitelist=W.toolWhitelist?.length?new Set(W.toolWhitelist):null,this.toolBlacklist=W.toolBlacklist?.length?new Set(W.toolBlacklist):null,this.scheduler=W.scheduler??(W.concurrencyLimits?new h0(W.concurrencyLimits):h0.getInstance());let Z=W.approvalStore??new X1;this.permissionResolver=new NW(W.permissionConfig??{allow:[],ask:[],deny:[]},Z,W.permissionMode??"default"),this.approvalController=new LW(Z,this.permissionResolver.getPermissionChecker())}async execute($,W,Z){let Y=Date.now(),J=`exec_${z7()}`,X={...Z,sessionId:Z.sessionId||J};return this.emit("executionStarted",{executionId:J,toolName:$,params:W,context:X,timestamp:Y}),this.executeFlow($,W,X,J,Y)}async executeFlow($,W,Z,Y,J){let X=W;try{let V=await this.runTool($,W,Z,Y,(H)=>{X=H});return this.completeExecution(Y,$,X,Z,V,J),V}catch(V){return this.failExecution(Y,$,X,Z,V,J)}}async runTool($,W,Z,Y,J){if(Z.signal?.aborted)return R$(!0);let X=this.registry.get($);if(!X)return s(`Tool "${$}" not found`,{errorType:"validation_error"});let V=L5(X,W,this.toolWhitelist,this.toolBlacklist);if("success"in V)return V;let{params:H,invocation:B}=V,K=await kW(X,H,Z);if(K)return K;let Q=this.permissionResolver.resolveRulePermission(X,B,H,Z),U=await b5(X,H,B,Z,Q.decision);if(U.rejection)return U.rejection;if(H=U.params,B=U.invocation,J(H),U.inputModified){let O=await kW(X,H,Z);if(O)return O;Q=this.permissionResolver.resolveRulePermission(X,B,H,Z)}let q=A5(Q.decision,U.decision);if(q.behavior==="deny")return s(q.reason||`Tool invocation denied by ${q.source}${q.matchedRule?` (${q.matchedRule})`:""}`,{errorType:"permission_denied"});let w=await this.approvalController.confirmIfNeeded(X,B,H,q,Q.signature,Z);if(w)return w;if(Z.signal?.aborted)return R$(!0);let E=!1,G=()=>{if(Z.signal?.aborted)return Promise.resolve(R$(!0));return E=!0,v5(B,Z)},F=!X.isConcurrencySafe&&H.file_path?()=>e0.getInstance().acquireLock(String(H.file_path),G):G,R=await this.scheduler.schedule(X.kind,F);if(Z.signal?.aborted)return R$(!E);if(await M5(X,H,R,Z,U.toolUseId),Z.signal?.aborted)return R$(!1);if(await D5(X.name,H,Z,R),Z.signal?.aborted)return R$(!1);return x5(R,Y,X.name)}completeExecution($,W,Z,Y,J,X){let V=Date.now();this.addToHistory({executionId:$,toolName:W,params:Z,result:J,startTime:X,endTime:V,context:Y}),this.emit("executionCompleted",{executionId:$,toolName:W,result:J,duration:V-X,timestamp:V})}async failExecution($,W,Z,Y,J,X){let V=J instanceof Error?J:Error(String(J)),H=Date.now(),B=V.message.includes("timeout")||V.name==="TimeoutError",K={success:!1,llmContent:`Tool execution failed: ${V.message}`,error:{type:B?"timeout_error":"execution_error",message:V.message}};try{let Q=await w0.getInstance().executePostToolUseFailureHooks(W,`tool_use_${$}`,Z,V.message,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode||"default",isInterrupt:!1,isTimeout:B,abortSignal:Y.signal});if(Q.additionalContext)K={...K,llmContent:`${K.llmContent}
758
+ `+H.additionalContext}if(G7(H.modifiedOutput))Object.assign(Z,H.modifiedOutput);if(H.warning)console.warn(`[PostToolUseHook Warning] ${H.warning}`)}catch(V){console.error("[ToolExecutionHooks] Error executing post-tool hooks:",V)}}function G7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var E7=["EBUSY","EAGAIN","EMFILE","ENFILE"];async function v5($,W){let Z=Date.now(),Y;for(let J=0;J<=2;J++)try{let X=await $.execute(W.signal??new AbortController().signal,W.onProgress,W);if(X.metadata??={},X.metadata.duration=Date.now()-Z,J>0)X.metadata.retriedAttempts=J;return X}catch(X){if(Y=X instanceof Error?X:Error(String(X)),J>=2||!E7.some((V)=>Y?.message.includes(V)))break;await F7(200*(J+1))}throw Y??Error("Tool execution failed")}function x5($,W,Z){if(!$.llmContent)$.llmContent="Execution completed";return $.metadata??={},$.metadata.executionId=W,$.metadata.toolName=Z,$.metadata.timestamp=Date.now(),$}function F7($){return new Promise((W)=>setTimeout(W,$))}class V1 extends R7{registry;executionHistory=[];maxHistorySize;scheduler;toolWhitelist;toolBlacklist;permissionResolver;approvalController;constructor($,W={}){super();this.registry=$;this.maxHistorySize=W.maxHistorySize??1000,this.toolWhitelist=W.toolWhitelist?.length?new Set(W.toolWhitelist):null,this.toolBlacklist=W.toolBlacklist?.length?new Set(W.toolBlacklist):null,this.scheduler=W.scheduler??(W.concurrencyLimits?new h0(W.concurrencyLimits):h0.getInstance());let Z=W.approvalStore??new X1;this.permissionResolver=new NW(W.permissionConfig??{allow:[],ask:[],deny:[]},Z,W.permissionMode??"default"),this.approvalController=new LW(Z,this.permissionResolver.getPermissionChecker())}async execute($,W,Z){let Y=Date.now(),J=`exec_${z7()}`,X={...Z,sessionId:Z.sessionId||J};return this.emit("executionStarted",{executionId:J,toolName:$,params:W,context:X,timestamp:Y}),this.executeFlow($,W,X,J,Y)}async executeFlow($,W,Z,Y,J){let X=W;try{let V=await this.runTool($,W,Z,Y,(H)=>{X=H});return this.completeExecution(Y,$,X,Z,V,J),V}catch(V){return this.failExecution(Y,$,X,Z,V,J)}}async runTool($,W,Z,Y,J){if(Z.signal?.aborted)return R$(!0);let X=this.registry.get($);if(!X)return s(`Tool "${$}" not found`,{errorType:"validation_error"});let V=L5(X,W,this.toolWhitelist,this.toolBlacklist);if("success"in V)return V;let{params:H,invocation:K}=V,B=await kW(X,H,Z);if(B)return B;let U=this.permissionResolver.resolveRulePermission(X,K,H,Z),Q=await b5(X,H,K,Z,U.decision);if(Q.rejection)return Q.rejection;if(H=Q.params,K=Q.invocation,J(H),Q.inputModified){let O=await kW(X,H,Z);if(O)return O;U=this.permissionResolver.resolveRulePermission(X,K,H,Z)}let q=A5(U.decision,Q.decision);if(q.behavior==="deny")return s(q.reason||`Tool invocation denied by ${q.source}${q.matchedRule?` (${q.matchedRule})`:""}`,{errorType:"permission_denied"});let w=await this.approvalController.confirmIfNeeded(X,K,H,q,U.signature,Z);if(w)return w;if(Z.signal?.aborted)return R$(!0);let E=!1,G=()=>{if(Z.signal?.aborted)return Promise.resolve(R$(!0));return E=!0,v5(K,Z)},F=!X.isConcurrencySafe&&H.file_path?()=>e0.getInstance().acquireLock(String(H.file_path),G):G,z=await this.scheduler.schedule(X.kind,F);if(Z.signal?.aborted)return R$(!E);if(await M5(X,H,z,Z,Q.toolUseId),Z.signal?.aborted)return R$(!1);if(await _5(X.name,H,Z,z),Z.signal?.aborted)return R$(!1);return x5(z,Y,X.name)}completeExecution($,W,Z,Y,J,X){let V=Date.now();this.addToHistory({executionId:$,toolName:W,params:Z,result:J,startTime:X,endTime:V,context:Y}),this.emit("executionCompleted",{executionId:$,toolName:W,result:J,duration:V-X,timestamp:V})}async failExecution($,W,Z,Y,J,X){let V=J instanceof Error?J:Error(String(J)),H=Date.now(),K=V.message.includes("timeout")||V.name==="TimeoutError",B={success:!1,llmContent:`Tool execution failed: ${V.message}`,error:{type:K?"timeout_error":"execution_error",message:V.message}};try{let U=await w0.getInstance().executePostToolUseFailureHooks(W,`tool_use_${$}`,Z,V.message,{projectDir:Y.workspaceRoot||D(),sessionId:Y.sessionId||"unknown",permissionMode:Y.permissionMode||"default",isInterrupt:!1,isTimeout:K,abortSignal:Y.signal});if(U.additionalContext)B={...B,llmContent:`${B.llmContent}
759
759
 
760
- ${Q.additionalContext}`};if(Q.warning)console.warn(`[ToolExecutor] PostToolUseFailure hook warning: ${Q.warning}`)}catch(Q){console.warn("[ToolExecutor] PostToolUseFailure hook execution failed:",Q)}return this.addToHistory({executionId:$,toolName:W,params:Z,result:K,startTime:X,endTime:H,context:Y}),this.emit("executionFailed",{executionId:$,toolName:W,error:V,duration:H-X,timestamp:H}),K}async executeAll($){return Promise.all($.map((W)=>this.execute(W.toolName,W.params,W.context)))}async executeParallel($,W=5){let Z=W>0?W:Number.POSITIVE_INFINITY;if(!Number.isFinite(Z)||Z>=$.length)return this.executeAll($);let Y=Array($.length),J=0,X=async()=>{while(J<$.length){let V=J++,H=$[V];Y[V]=await this.execute(H.toolName,H.params,H.context)}};return await Promise.all(Array.from({length:Math.min(Z,$.length)},()=>X())),Y}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)},W=0;for(let Z of this.executionHistory){if(Z.result.success)$.successfulExecutions++;else $.failedExecutions++;W+=Z.endTime-Z.startTime,$.toolUsage.set(Z.toolName,($.toolUsage.get(Z.toolName)||0)+1)}return $.averageDuration=$.totalExecutions>0?W/$.totalExecutions:0,$}getRegistry(){return this.registry}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory.splice(0,this.executionHistory.length-this.maxHistorySize)}}import{EventEmitter as O7}from"events";var bW=new Set(["Read","Edit","Write","Glob","Grep","Bash","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree"]);class MW{loadedTools=new Set(bW);deferredTools=new Set;register($){if(bW.has($))this.loadedTools.add($);else this.deferredTools.add($)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,W){return $.filter((Z)=>this.isLoaded(Z.name)).map((Z)=>Z.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
761
- `)}reset(){this.loadedTools=new Set(bW),this.deferredTools.clear()}}class O$ extends O7{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new MW;constructor(){super()}get deferredToolManager(){return this._deferredManager}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 W=[];for(let Z of $)try{this.register(Z)}catch(Y){W.push(`${Z.name}: ${Y.message}`)}if(W.length>0)throw Error(`批量注册失败: ${W.join(", ")}`)}unregister($){let W=this.tools.get($);if(!W)return!1;return this.tools.delete($),this.removeFromIndexes(W),this.emit("toolUnregistered",{type:"builtin",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 W=this.categories.get($);if(!W)return[];return Array.from(W).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}getByTag($){let W=this.tags.get($);if(!W)return[];return Array.from(W).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}search($){let W=$.toLowerCase();return this.getAll().filter((Z)=>{let Y=typeof Z.description==="string"?Z.description:Z.description.short;return Z.name.toLowerCase().includes(W)||Y.toLowerCase().includes(W)||Z.displayName.toLowerCase().includes(W)||Z.category&&Z.category.toLowerCase().includes(W)||Z.tags.some((J)=>J.toLowerCase().includes(W))})}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(([$,W])=>[$,W.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new O$;for(let W of this.tools.values())$.register(W);for(let W of this.mcpTools.values())$.registerMcpTool(W);return $}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let W=0,Z=`mcp__${$}__`;for(let[Y,J]of this.mcpTools.entries())if(Y.startsWith(Z))this.mcpTools.delete(Y),this.removeFromIndexes(J),W++,this.emit("toolUnregistered",{type:"mcp",toolName:Y,serverName:$,timestamp:Date.now()});return W}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let W of $.tags){if(!this.tags.has(W))this.tags.set(W,new Set);this.tags.get(W).add($.name)}}removeFromIndexes($){if($.category){let W=this.categories.get($.category);if(W){if(W.delete($.name),W.size===0)this.categories.delete($.category)}}for(let W of $.tags){let Z=this.tags.get(W);if(Z){if(Z.delete($.name),Z.size===0)this.tags.delete(W)}}}}var D7=[/deepseek.*r1/i,/deepseek.*reasoner/i,/o1-preview/i,/o1-mini/i,/o1/i,/qwen.*qwq/i,/qwen.*think/i,/kimi.*k1/i,/moonshot.*think/i,/k1-32k/i,/doubao.*think/i,/doubao.*pro.*think/i,/claude.*opus.*4/i,/glm-4\.7/i];function _7($){return D7.some((W)=>W.test($))}function j7($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:_7($.model),thinkingBudget:void 0}}function c1($){return j7($).supportsThinking}import*as f5 from"crypto";import{nanoid as P5}from"nanoid";class vW{assemble($){if($.length===0)return null;let W=this.assembleSession($),Z=this.assembleConversation($),Y=this.assembleToolCalls($);return{session:W,conversation:Z,toolCalls:Y}}assembleContextData($,W,Z){let Y=this.assemble($);if(!Y)return null;return{layers:{system:W,session:Y.session,conversation:Y.conversation,tool:{recentCalls:Y.toolCalls,toolStates:{},dependencies:{}},workspace:Z},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let W=$.find((V)=>V.type==="session_created"),Z=W?.sessionId??$[0].sessionId,Y=new Date(W?.timestamp??$[0].timestamp).getTime(),J=$.filter((V)=>V.type==="session_updated"),X=J.length>0?J[J.length-1]:null;return{sessionId:Z,userId:void 0,preferences:{},configuration:X?.data??{},startTime:Y}}assembleConversation($){let W=new Map,Z;for(let V of $){if(V.type==="message_created")W.set(V.data.messageId,{id:V.data.messageId,role:V.data.role,content:"",timestamp:new Date(V.timestamp).getTime(),metadata:V.data.model||V.data.inboxMessageId?{...V.data.model?{model:V.data.model}:{},...V.data.inboxMessageId?{inboxMessageId:V.data.inboxMessageId}:{}}:void 0});if(V.type==="part_created"){let{partType:H,messageId:B,payload:K}=V.data,Q=W.get(B);if(H==="text"&&Q){let U=K;Q.content=U.text??""}if(H==="image"&&Q)Q.content=Q.content?`${Q.content}
762
- [Image]`:"[Image]";if(H==="summary"){let U=K;if(U.text)Z=U.text}}if(V.type==="part_updated"){let{partType:H,messageId:B,payload:K}=V.data,Q=W.get(B);if(H==="text"&&Q){let U=K;Q.content=U.text??""}}}let Y=Array.from(W.values()),J=$[$.length-1],X=new Date(J.timestamp).getTime();return{messages:Y,summary:Z,topics:[],lastActivity:X}}assembleToolCalls($){let W=new Map;for(let Z of $){if(Z.type!=="part_created")continue;let{partType:Y,partId:J,payload:X}=Z.data;if(Y==="tool_call"){let V=X,H=V.toolCallId??J;W.set(H,{id:H,name:V.toolName??"unknown",input:V.input??null,timestamp:new Date(Z.timestamp).getTime(),status:"pending"})}if(Y==="tool_result"){let V=X,H=V.toolCallId??J,B=W.get(H);if(B)B.output=V.output??void 0,B.status=V.error?"error":"success",B.error=V.error??void 0;else W.set(H,{id:H,name:V.toolName??"unknown",input:null,output:V.output??void 0,timestamp:new Date(Z.timestamp).getTime(),status:V.error?"error":"success",error:V.error??void 0})}}return Array.from(W.values())}}class xW{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,W=10,Z=20){this.maxSummaryLength=$,this.keyPointsLimit=W,this.recentMessagesLimit=Z}async compress($){let W=$.layers.conversation.messages,Z=$.layers.tool.recentCalls,Y=W.filter((U)=>U.role==="system"),J=W.filter((U)=>U.role!=="system"),X=this.getRecentMessages(J),V=J.slice(0,-this.recentMessagesLimit),H=await this.generateSummary(V),B=this.extractKeyPoints(V,Z),K=this.generateToolSummary(Z),Q=this.estimateTokenCount(H,B,X,K);return{summary:H,keyPoints:B,recentMessages:[...Y,...X],toolSummary:K,tokenCount:Q}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let W=new Set,Z=new Set,Y=new Set;for(let X of $){let V=X.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((Q)=>{if(V.includes(Q)){let U=this.extractContext(V,Q,50);if(U)W.add(U)}}),["创建","删除","修改","更新","实现","开发"].forEach((Q)=>{if(V.includes(Q)){let U=this.extractContext(V,Q,30);if(U)Z.add(U)}}),["决定","选择","确定","采用","使用"].forEach((Q)=>{if(V.includes(Q)){let U=this.extractContext(V,Q,40);if(U)Y.add(U)}})}let J=`对话涉及 ${$.length} 条消息。`;if(W.size>0)J+=` 主要讨论:${Array.from(W).slice(0,3).join("、")}。`;if(Z.size>0)J+=` 执行操作:${Array.from(Z).slice(0,3).join("、")}。`;if(Y.size>0)J+=` 关键决策:${Array.from(Y).slice(0,2).join("、")}。`;return J.length>this.maxSummaryLength?J.substring(0,this.maxSummaryLength)+"...":J}extractKeyPoints($,W){let Z=new Set;for(let J of $)if(J.role==="user")this.extractQuestions(J.content).forEach((H)=>Z.add(`用户问题:${H}`)),this.extractRequests(J.content).forEach((H)=>Z.add(`用户请求:${H}`));else if(J.role==="assistant")this.extractSolutions(J.content).forEach((V)=>Z.add(`解决方案:${V}`));return this.summarizeToolUsage(W).forEach((J)=>Z.add(`工具使用:${J}`)),Array.from(Z).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let W=new Map,Z=Date.now()-600000;for(let J of $){let X=W.get(J.name)||{count:0,success:0,recent:0};if(X.count++,J.status==="success")X.success++;if(J.timestamp>Z)X.recent++;W.set(J.name,X)}let Y=[];for(let[J,X]of Array.from(W.entries())){let V=Math.round(X.success/X.count*100);Y.push(`${J}(${X.count}次,成功率${V}%)`)}return`工具调用:${Y.join("、")}`}estimateTokenCount($,W,Z,Y){let J=$.length+W.join(" ").length;if(Y)J+=Y.length;for(let X of Z)J+=X.content.length;return Math.ceil(J/4)}extractContext($,W,Z){let Y=$.indexOf(W);if(Y===-1)return null;let J=Math.max(0,Y-Z/2),X=Math.min($.length,Y+Z/2);return $.substring(J,X).trim()}extractQuestions($){let W=[],Z=["?","?","如何","怎么","什么","为什么"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>5&&X.length<100)W.push(X)}return W.slice(0,3)}extractRequests($){let W=[],Z=["请","帮我","需要","想要","希望","能否"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>5&&X.length<100)W.push(X)}return W.slice(0,3)}extractSolutions($){let W=[],Z=["可以","建议","推荐","应该","最好","解决方案"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>10&&X.length<150)W.push(X)}return W.slice(0,3)}summarizeToolUsage($){let W=[],Z=$.filter((Y)=>Date.now()-Y.timestamp<1800000);if(Z.length>0){let Y=new Map;Z.forEach((J)=>{let X=Y.get(J.name)||[];X.push(J),Y.set(J.name,X)});for(let[J,X]of Array.from(Y.entries())){let V=X.filter((H)=>H.status==="success").length;W.push(`${J}(${X.length}次,${V}成功)`)}}return W.slice(0,5)}shouldCompress($,W){return this.estimateCurrentTokens($)>W*0.8}estimateCurrentTokens($){let Z=$.layers.conversation.messages.reduce((Y,J)=>Y+J.content.length,0);return Math.ceil(Z/4)}}class D${defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,W){let Z={...this.defaultOptions,...W},Y={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,Z),tool:Z.includeTools?this.filterTools($.layers.tool,Z):{recentCalls:[],toolStates:{},dependencies:{}},workspace:Z.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Y.metadata.totalTokens=this.estimateTokens(Y),Y}filterConversation($,W){let Z=[...$.messages];if(W.timeWindow>0){let Y=Date.now()-W.timeWindow;Z=Z.filter((J)=>J.timestamp>=Y||J.role==="system")}if(W.priority>1)Z=this.filterByPriority(Z,W.priority);if(W.maxMessages>0)Z=this.limitMessages(Z,W.maxMessages);if(W.maxTokens>0)Z=this.limitByTokens(Z,W.maxTokens);return{messages:Z,summary:$.summary,topics:this.updateTopics(Z,$.topics),lastActivity:$.lastActivity}}filterTools($,W){let Z=[...$.recentCalls];if(W.timeWindow>0){let B=Date.now()-W.timeWindow;Z=Z.filter((K)=>K.timestamp>=B)}let Y=Z.filter((B)=>B.status==="success"),J=Z.filter((B)=>B.status==="error"),X=Math.min(20,Y.length),V=Math.min(10,J.length);return{recentCalls:[...Y.slice(-X),...J.slice(-V)].sort((B,K)=>B.timestamp-K.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,W){return $.filter((Z)=>{if(Z.role==="system")return!0;return this.calculateMessagePriority(Z)>=W})}calculateMessagePriority($){let W=1;if($.role==="system")W+=3;else if($.role==="assistant")W+=1;let Z=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((X)=>Z.includes(X)))W+=2;if(Z.includes("```")||Z.includes("function")||Z.includes("class"))W+=1;let J=(Date.now()-$.timestamp)/3600000;if(J<1)W+=2;else if(J<6)W+=1;return W}limitMessages($,W){if($.length<=W)return $;let Z=$.filter((V)=>V.role==="system"),Y=$.filter((V)=>V.role!=="system"),J=W-Z.length,X=J>0?Y.slice(-J):[];return[...Z,...X].sort((V,H)=>V.timestamp-H.timestamp)}limitByTokens($,W){if(W<=0)return $;let Z=0,Y=[];for(let J=$.length-1;J>=0;J--){let X=$[J],V=this.estimateMessageTokens(X);if(X.role==="system")if(Z+V<=W)Y.unshift(X),Z+=V;else{let H=this.compressMessage(X,W-Z);Y.unshift(H),Z+=this.estimateMessageTokens(H)}else if(Z+V<=W)Y.unshift(X),Z+=V;else break}return Y.sort((J,X)=>J.timestamp-X.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,W){let Z=W*4;if($.content.length<=Z)return $;let Y=$.content.substring(0,Z-3)+"...";return{...$,content:Y,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,W){let Z=new Set(W);for(let Y of $)this.extractTopicsFromMessage(Y).forEach((X)=>Z.add(X));return Array.from(Z).slice(0,10)}extractTopicsFromMessage($){let W=$.content.toLowerCase(),Z=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((J)=>{if(W.includes(J))Z.push(J)}),Z}estimateTokens($){let W=0;for(let Y of $.layers.conversation.messages)W+=this.estimateMessageTokens(Y);let Z=JSON.stringify($.layers.system);if(W+=Math.ceil(Z.length/4),$.layers.tool.recentCalls.length>0){let Y=JSON.stringify($.layers.tool);W+=Math.ceil(Y.length/8)}return W}static createPresets(){return{lightweight:new D$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new D$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new D$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new D$({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class CW{cache=new Map;maxSize;defaultTTL;constructor($=100,W=300000){this.maxSize=$,this.defaultTTL=W}set($,W,Z){let Y=Date.now(),J={data:W,timestamp:Y,accessCount:0,lastAccess:Y,ttl:Z||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,J)}get($){let W=this.cache.get($);if(!W)return null;let Z=Date.now();if(Z-W.timestamp>W.ttl)return this.cache.delete($),null;return W.accessCount++,W.lastAccess=Z,W.data}has($){let W=this.cache.get($);if(!W)return!1;if(Date.now()-W.timestamp>W.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($,W,Z){let Y=`summary:${$}:${W.length}`;this.set(Y,{summary:Z,messageCount:W.length,lastMessage:W[W.length-1]?.timestamp||0},600000)}getMessageSummary($,W){let Z=`summary:${$}:${W}`;return this.get(Z)}cacheToolResult($,W,Z){let Y=this.hashInput(W),J=`tool:${$}:${Y}`;this.set(J,Z,1800000)}getToolResult($,W){let Z=this.hashInput(W),Y=`tool:${$}:${Z}`;return this.get(Y)}cacheCompressedContext($,W){let Z=`compressed:${$}`;this.set(Z,W,900000)}getCompressedContext($){let W=`compressed:${$}`;return this.get(W)}getStats(){this.cleanExpired();let $=0,W=0,Z=[];for(let[Y,J]of Array.from(this.cache.entries()))$+=J.accessCount,W+=this.estimateItemSize(J),Z.push({key:Y,accessCount:J.accessCount,lastAccess:J.lastAccess});return Z.sort((Y,J)=>J.accessCount-Y.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:W,topKeys:Z.slice(0,10)}}cleanExpired(){let $=Date.now(),W=[];for(let[Z,Y]of Array.from(this.cache.entries()))if($-Y.timestamp>Y.ttl)W.push(Z);W.forEach((Z)=>this.cache.delete(Z))}evictLeastUsed(){let $=null,W=1/0,Z=Date.now();for(let[Y,J]of Array.from(this.cache.entries())){let X=1/(Z-J.lastAccess+1),V=J.accessCount,H=X*V;if(H<W)W=H,$=Y}if($)this.cache.delete($)}hashInput($){let W=JSON.stringify($),Z=0;for(let Y=0;Y<W.length;Y++){let J=W.charCodeAt(Y);Z=(Z<<5)-Z+J,Z=Z&Z}return Math.abs(Z).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,W){let Z=this.cache.get($);if(Z)return Z.ttl=W,Z.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let W=this.cache.get($);if(!W)return-1;let Z=W.ttl-(Date.now()-W.timestamp);return Math.max(0,Z)}warmup($){$.forEach(({key:W,value:Z,ttl:Y})=>{this.set(W,Z,Y)})}}class yW{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 W=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),W.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($,W){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=W,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 W=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-W)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as _0}from"nanoid";import*as x0 from"node:fs/promises";import*as y5 from"node:path";import*as l1 from"node:fs";import{createReadStream as A7}from"node:fs";import*as t from"node:fs/promises";import*as PW from"node:path";import{createInterface as N7}from"node:readline";var T7=65536;function L7($,W,Z){let Y=$.trim();if(!Y)return;try{return JSON.parse(Y)}catch(J){throw Error(`Invalid session JSONL in ${Z} at line ${W}`,{cause:J})}}function _$($,W="session transcript"){let Z=$.split(`
760
+ ${U.additionalContext}`};if(U.warning)console.warn(`[ToolExecutor] PostToolUseFailure hook warning: ${U.warning}`)}catch(U){console.warn("[ToolExecutor] PostToolUseFailure hook execution failed:",U)}return this.addToHistory({executionId:$,toolName:W,params:Z,result:B,startTime:X,endTime:H,context:Y}),this.emit("executionFailed",{executionId:$,toolName:W,error:V,duration:H-X,timestamp:H}),B}async executeAll($){return Promise.all($.map((W)=>this.execute(W.toolName,W.params,W.context)))}async executeParallel($,W=5){let Z=W>0?W:Number.POSITIVE_INFINITY;if(!Number.isFinite(Z)||Z>=$.length)return this.executeAll($);let Y=Array($.length),J=0,X=async()=>{while(J<$.length){let V=J++,H=$[V];Y[V]=await this.execute(H.toolName,H.params,H.context)}};return await Promise.all(Array.from({length:Math.min(Z,$.length)},()=>X())),Y}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)},W=0;for(let Z of this.executionHistory){if(Z.result.success)$.successfulExecutions++;else $.failedExecutions++;W+=Z.endTime-Z.startTime,$.toolUsage.set(Z.toolName,($.toolUsage.get(Z.toolName)||0)+1)}return $.averageDuration=$.totalExecutions>0?W/$.totalExecutions:0,$}getRegistry(){return this.registry}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory.splice(0,this.executionHistory.length-this.maxHistorySize)}}import{EventEmitter as O7}from"events";var bW=new Set(["Read","Edit","Write","Glob","Grep","Bash","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode","EnterWorktree","ExitWorktree"]);class MW{loadedTools=new Set(bW);deferredTools=new Set;register($){if(bW.has($))this.loadedTools.add($);else this.deferredTools.add($)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,W){return $.filter((Z)=>this.isLoaded(Z.name)).map((Z)=>Z.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
761
+ `)}reset(){this.loadedTools=new Set(bW),this.deferredTools.clear()}}class O$ extends O7{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new MW;constructor(){super()}get deferredToolManager(){return this._deferredManager}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 W=[];for(let Z of $)try{this.register(Z)}catch(Y){W.push(`${Z.name}: ${Y.message}`)}if(W.length>0)throw Error(`批量注册失败: ${W.join(", ")}`)}unregister($){let W=this.tools.get($);if(!W)return!1;return this.tools.delete($),this.removeFromIndexes(W),this.emit("toolUnregistered",{type:"builtin",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 W=this.categories.get($);if(!W)return[];return Array.from(W).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}getByTag($){let W=this.tags.get($);if(!W)return[];return Array.from(W).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}search($){let W=$.toLowerCase();return this.getAll().filter((Z)=>{let Y=typeof Z.description==="string"?Z.description:Z.description.short;return Z.name.toLowerCase().includes(W)||Y.toLowerCase().includes(W)||Z.displayName.toLowerCase().includes(W)||Z.category&&Z.category.toLowerCase().includes(W)||Z.tags.some((J)=>J.toLowerCase().includes(W))})}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(([$,W])=>[$,W.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new O$;for(let W of this.tools.values())$.register(W);for(let W of this.mcpTools.values())$.registerMcpTool(W);return $}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this._deferredManager.register($.name),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let W=0,Z=`mcp__${$}__`;for(let[Y,J]of this.mcpTools.entries())if(Y.startsWith(Z))this.mcpTools.delete(Y),this.removeFromIndexes(J),W++,this.emit("toolUnregistered",{type:"mcp",toolName:Y,serverName:$,timestamp:Date.now()});return W}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let W of $.tags){if(!this.tags.has(W))this.tags.set(W,new Set);this.tags.get(W).add($.name)}}removeFromIndexes($){if($.category){let W=this.categories.get($.category);if(W){if(W.delete($.name),W.size===0)this.categories.delete($.category)}}for(let W of $.tags){let Z=this.tags.get(W);if(Z){if(Z.delete($.name),Z.size===0)this.tags.delete(W)}}}}var _7=[/deepseek.*r1/i,/deepseek.*reasoner/i,/o1-preview/i,/o1-mini/i,/o1/i,/qwen.*qwq/i,/qwen.*think/i,/kimi.*k1/i,/moonshot.*think/i,/k1-32k/i,/doubao.*think/i,/doubao.*pro.*think/i,/claude.*opus.*4/i,/glm-4\.7/i];function D7($){return _7.some((W)=>W.test($))}function j7($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:D7($.model),thinkingBudget:void 0}}function c1($){return j7($).supportsThinking}import*as P5 from"crypto";import{nanoid as f5}from"nanoid";class vW{assemble($){if($.length===0)return null;let W=this.assembleSession($),Z=this.assembleConversation($),Y=this.assembleToolCalls($);return{session:W,conversation:Z,toolCalls:Y}}assembleContextData($,W,Z){let Y=this.assemble($);if(!Y)return null;return{layers:{system:W,session:Y.session,conversation:Y.conversation,tool:{recentCalls:Y.toolCalls,toolStates:{},dependencies:{}},workspace:Z},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let W=$.find((V)=>V.type==="session_created"),Z=W?.sessionId??$[0].sessionId,Y=new Date(W?.timestamp??$[0].timestamp).getTime(),J=$.filter((V)=>V.type==="session_updated"),X=J.length>0?J[J.length-1]:null;return{sessionId:Z,userId:void 0,preferences:{},configuration:X?.data??{},startTime:Y}}assembleConversation($){let W=new Map,Z;for(let V of $){if(V.type==="message_created")W.set(V.data.messageId,{id:V.data.messageId,role:V.data.role,content:"",timestamp:new Date(V.timestamp).getTime(),metadata:V.data.model||V.data.inboxMessageId?{...V.data.model?{model:V.data.model}:{},...V.data.inboxMessageId?{inboxMessageId:V.data.inboxMessageId}:{}}:void 0});if(V.type==="part_created"){let{partType:H,messageId:K,payload:B}=V.data,U=W.get(K);if(H==="text"&&U){let Q=B;U.content=Q.text??""}if(H==="image"&&U)U.content=U.content?`${U.content}
762
+ [Image]`:"[Image]";if(H==="summary"){let Q=B;if(Q.text)Z=Q.text}}if(V.type==="part_updated"){let{partType:H,messageId:K,payload:B}=V.data,U=W.get(K);if(H==="text"&&U){let Q=B;U.content=Q.text??""}}}let Y=Array.from(W.values()),J=$[$.length-1],X=new Date(J.timestamp).getTime();return{messages:Y,summary:Z,topics:[],lastActivity:X}}assembleToolCalls($){let W=new Map;for(let Z of $){if(Z.type!=="part_created")continue;let{partType:Y,partId:J,payload:X}=Z.data;if(Y==="tool_call"){let V=X,H=V.toolCallId??J;W.set(H,{id:H,name:V.toolName??"unknown",input:V.input??null,timestamp:new Date(Z.timestamp).getTime(),status:"pending"})}if(Y==="tool_result"){let V=X,H=V.toolCallId??J,K=W.get(H);if(K)K.output=V.output??void 0,K.status=V.error?"error":"success",K.error=V.error??void 0;else W.set(H,{id:H,name:V.toolName??"unknown",input:null,output:V.output??void 0,timestamp:new Date(Z.timestamp).getTime(),status:V.error?"error":"success",error:V.error??void 0})}}return Array.from(W.values())}}class xW{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,W=10,Z=20){this.maxSummaryLength=$,this.keyPointsLimit=W,this.recentMessagesLimit=Z}async compress($){let W=$.layers.conversation.messages,Z=$.layers.tool.recentCalls,Y=W.filter((Q)=>Q.role==="system"),J=W.filter((Q)=>Q.role!=="system"),X=this.getRecentMessages(J),V=J.slice(0,-this.recentMessagesLimit),H=await this.generateSummary(V),K=this.extractKeyPoints(V,Z),B=this.generateToolSummary(Z),U=this.estimateTokenCount(H,K,X,B);return{summary:H,keyPoints:K,recentMessages:[...Y,...X],toolSummary:B,tokenCount:U}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let W=new Set,Z=new Set,Y=new Set;for(let X of $){let V=X.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((U)=>{if(V.includes(U)){let Q=this.extractContext(V,U,50);if(Q)W.add(Q)}}),["创建","删除","修改","更新","实现","开发"].forEach((U)=>{if(V.includes(U)){let Q=this.extractContext(V,U,30);if(Q)Z.add(Q)}}),["决定","选择","确定","采用","使用"].forEach((U)=>{if(V.includes(U)){let Q=this.extractContext(V,U,40);if(Q)Y.add(Q)}})}let J=`对话涉及 ${$.length} 条消息。`;if(W.size>0)J+=` 主要讨论:${Array.from(W).slice(0,3).join("、")}。`;if(Z.size>0)J+=` 执行操作:${Array.from(Z).slice(0,3).join("、")}。`;if(Y.size>0)J+=` 关键决策:${Array.from(Y).slice(0,2).join("、")}。`;return J.length>this.maxSummaryLength?J.substring(0,this.maxSummaryLength)+"...":J}extractKeyPoints($,W){let Z=new Set;for(let J of $)if(J.role==="user")this.extractQuestions(J.content).forEach((H)=>Z.add(`用户问题:${H}`)),this.extractRequests(J.content).forEach((H)=>Z.add(`用户请求:${H}`));else if(J.role==="assistant")this.extractSolutions(J.content).forEach((V)=>Z.add(`解决方案:${V}`));return this.summarizeToolUsage(W).forEach((J)=>Z.add(`工具使用:${J}`)),Array.from(Z).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let W=new Map,Z=Date.now()-600000;for(let J of $){let X=W.get(J.name)||{count:0,success:0,recent:0};if(X.count++,J.status==="success")X.success++;if(J.timestamp>Z)X.recent++;W.set(J.name,X)}let Y=[];for(let[J,X]of Array.from(W.entries())){let V=Math.round(X.success/X.count*100);Y.push(`${J}(${X.count}次,成功率${V}%)`)}return`工具调用:${Y.join("、")}`}estimateTokenCount($,W,Z,Y){let J=$.length+W.join(" ").length;if(Y)J+=Y.length;for(let X of Z)J+=X.content.length;return Math.ceil(J/4)}extractContext($,W,Z){let Y=$.indexOf(W);if(Y===-1)return null;let J=Math.max(0,Y-Z/2),X=Math.min($.length,Y+Z/2);return $.substring(J,X).trim()}extractQuestions($){let W=[],Z=["?","?","如何","怎么","什么","为什么"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>5&&X.length<100)W.push(X)}return W.slice(0,3)}extractRequests($){let W=[],Z=["请","帮我","需要","想要","希望","能否"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>5&&X.length<100)W.push(X)}return W.slice(0,3)}extractSolutions($){let W=[],Z=["可以","建议","推荐","应该","最好","解决方案"],Y=$.split(/[。!.!]/);for(let J of Y)if(Z.some((X)=>J.includes(X))){let X=J.trim();if(X.length>10&&X.length<150)W.push(X)}return W.slice(0,3)}summarizeToolUsage($){let W=[],Z=$.filter((Y)=>Date.now()-Y.timestamp<1800000);if(Z.length>0){let Y=new Map;Z.forEach((J)=>{let X=Y.get(J.name)||[];X.push(J),Y.set(J.name,X)});for(let[J,X]of Array.from(Y.entries())){let V=X.filter((H)=>H.status==="success").length;W.push(`${J}(${X.length}次,${V}成功)`)}}return W.slice(0,5)}shouldCompress($,W){return this.estimateCurrentTokens($)>W*0.8}estimateCurrentTokens($){let Z=$.layers.conversation.messages.reduce((Y,J)=>Y+J.content.length,0);return Math.ceil(Z/4)}}class _${defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,W){let Z={...this.defaultOptions,...W},Y={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,Z),tool:Z.includeTools?this.filterTools($.layers.tool,Z):{recentCalls:[],toolStates:{},dependencies:{}},workspace:Z.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return Y.metadata.totalTokens=this.estimateTokens(Y),Y}filterConversation($,W){let Z=[...$.messages];if(W.timeWindow>0){let Y=Date.now()-W.timeWindow;Z=Z.filter((J)=>J.timestamp>=Y||J.role==="system")}if(W.priority>1)Z=this.filterByPriority(Z,W.priority);if(W.maxMessages>0)Z=this.limitMessages(Z,W.maxMessages);if(W.maxTokens>0)Z=this.limitByTokens(Z,W.maxTokens);return{messages:Z,summary:$.summary,topics:this.updateTopics(Z,$.topics),lastActivity:$.lastActivity}}filterTools($,W){let Z=[...$.recentCalls];if(W.timeWindow>0){let K=Date.now()-W.timeWindow;Z=Z.filter((B)=>B.timestamp>=K)}let Y=Z.filter((K)=>K.status==="success"),J=Z.filter((K)=>K.status==="error"),X=Math.min(20,Y.length),V=Math.min(10,J.length);return{recentCalls:[...Y.slice(-X),...J.slice(-V)].sort((K,B)=>K.timestamp-B.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,W){return $.filter((Z)=>{if(Z.role==="system")return!0;return this.calculateMessagePriority(Z)>=W})}calculateMessagePriority($){let W=1;if($.role==="system")W+=3;else if($.role==="assistant")W+=1;let Z=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((X)=>Z.includes(X)))W+=2;if(Z.includes("```")||Z.includes("function")||Z.includes("class"))W+=1;let J=(Date.now()-$.timestamp)/3600000;if(J<1)W+=2;else if(J<6)W+=1;return W}limitMessages($,W){if($.length<=W)return $;let Z=$.filter((V)=>V.role==="system"),Y=$.filter((V)=>V.role!=="system"),J=W-Z.length,X=J>0?Y.slice(-J):[];return[...Z,...X].sort((V,H)=>V.timestamp-H.timestamp)}limitByTokens($,W){if(W<=0)return $;let Z=0,Y=[];for(let J=$.length-1;J>=0;J--){let X=$[J],V=this.estimateMessageTokens(X);if(X.role==="system")if(Z+V<=W)Y.unshift(X),Z+=V;else{let H=this.compressMessage(X,W-Z);Y.unshift(H),Z+=this.estimateMessageTokens(H)}else if(Z+V<=W)Y.unshift(X),Z+=V;else break}return Y.sort((J,X)=>J.timestamp-X.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,W){let Z=W*4;if($.content.length<=Z)return $;let Y=$.content.substring(0,Z-3)+"...";return{...$,content:Y,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,W){let Z=new Set(W);for(let Y of $)this.extractTopicsFromMessage(Y).forEach((X)=>Z.add(X));return Array.from(Z).slice(0,10)}extractTopicsFromMessage($){let W=$.content.toLowerCase(),Z=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((J)=>{if(W.includes(J))Z.push(J)}),Z}estimateTokens($){let W=0;for(let Y of $.layers.conversation.messages)W+=this.estimateMessageTokens(Y);let Z=JSON.stringify($.layers.system);if(W+=Math.ceil(Z.length/4),$.layers.tool.recentCalls.length>0){let Y=JSON.stringify($.layers.tool);W+=Math.ceil(Y.length/8)}return W}static createPresets(){return{lightweight:new _$({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new _$({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new _$({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new _$({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class CW{cache=new Map;maxSize;defaultTTL;constructor($=100,W=300000){this.maxSize=$,this.defaultTTL=W}set($,W,Z){let Y=Date.now(),J={data:W,timestamp:Y,accessCount:0,lastAccess:Y,ttl:Z||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,J)}get($){let W=this.cache.get($);if(!W)return null;let Z=Date.now();if(Z-W.timestamp>W.ttl)return this.cache.delete($),null;return W.accessCount++,W.lastAccess=Z,W.data}has($){let W=this.cache.get($);if(!W)return!1;if(Date.now()-W.timestamp>W.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($,W,Z){let Y=`summary:${$}:${W.length}`;this.set(Y,{summary:Z,messageCount:W.length,lastMessage:W[W.length-1]?.timestamp||0},600000)}getMessageSummary($,W){let Z=`summary:${$}:${W}`;return this.get(Z)}cacheToolResult($,W,Z){let Y=this.hashInput(W),J=`tool:${$}:${Y}`;this.set(J,Z,1800000)}getToolResult($,W){let Z=this.hashInput(W),Y=`tool:${$}:${Z}`;return this.get(Y)}cacheCompressedContext($,W){let Z=`compressed:${$}`;this.set(Z,W,900000)}getCompressedContext($){let W=`compressed:${$}`;return this.get(W)}getStats(){this.cleanExpired();let $=0,W=0,Z=[];for(let[Y,J]of Array.from(this.cache.entries()))$+=J.accessCount,W+=this.estimateItemSize(J),Z.push({key:Y,accessCount:J.accessCount,lastAccess:J.lastAccess});return Z.sort((Y,J)=>J.accessCount-Y.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:W,topKeys:Z.slice(0,10)}}cleanExpired(){let $=Date.now(),W=[];for(let[Z,Y]of Array.from(this.cache.entries()))if($-Y.timestamp>Y.ttl)W.push(Z);W.forEach((Z)=>this.cache.delete(Z))}evictLeastUsed(){let $=null,W=1/0,Z=Date.now();for(let[Y,J]of Array.from(this.cache.entries())){let X=1/(Z-J.lastAccess+1),V=J.accessCount,H=X*V;if(H<W)W=H,$=Y}if($)this.cache.delete($)}hashInput($){let W=JSON.stringify($),Z=0;for(let Y=0;Y<W.length;Y++){let J=W.charCodeAt(Y);Z=(Z<<5)-Z+J,Z=Z&Z}return Math.abs(Z).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,W){let Z=this.cache.get($);if(Z)return Z.ttl=W,Z.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let W=this.cache.get($);if(!W)return-1;let Z=W.ttl-(Date.now()-W.timestamp);return Math.max(0,Z)}warmup($){$.forEach(({key:W,value:Z,ttl:Y})=>{this.set(W,Z,Y)})}}class yW{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 W=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),W.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($,W){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=W,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 W=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-W)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as D0}from"nanoid";import*as x0 from"node:fs/promises";import*as y5 from"node:path";import*as l1 from"node:fs";import{createReadStream as A7}from"node:fs";import*as t from"node:fs/promises";import*as fW from"node:path";import{createInterface as N7}from"node:readline";var T7=65536;function L7($,W,Z){let Y=$.trim();if(!Y)return;try{return JSON.parse(Y)}catch(J){throw Error(`Invalid session JSONL in ${Z} at line ${W}`,{cause:J})}}function D$($,W="session transcript"){let Z=$.split(`
763
763
  `),Y=!$.endsWith(`
764
764
  `),J=[];for(let[X,V]of Z.entries())try{let H=L7(V,X+1,W);if(H)J.push(H)}catch(H){if(Y&&X===Z.length-1)break;throw H}return J}class n{static appendQueues=new Map;filePath;constructor($){this.filePath=$}async append($){try{let W=JSON.stringify($)+`
765
765
  `;await this.appendSerialized(W)}catch(W){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,W),W}}async appendBatch($){try{let W=$.map((Z)=>JSON.stringify(Z)).join(`
766
766
  `)+`
767
- `;await this.appendSerialized(W)}catch(W){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,W),W}}async createExclusive($){if($.length===0)throw Error("Cannot create an empty session transcript");await t.mkdir(PW.dirname(this.filePath),{recursive:!0,mode:493});let W;try{W=await t.open(this.filePath,"wx",384);let Z=`${$.map((Y)=>JSON.stringify(Y)).join(`
767
+ `;await this.appendSerialized(W)}catch(W){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,W),W}}async createExclusive($){if($.length===0)throw Error("Cannot create an empty session transcript");await t.mkdir(fW.dirname(this.filePath),{recursive:!0,mode:493});let W;try{W=await t.open(this.filePath,"wx",384);let Z=`${$.map((Y)=>JSON.stringify(Y)).join(`
768
768
  `)}
769
- `;await W.writeFile(Z,"utf-8"),await W.sync()}catch(Z){if(W)await W.close(),W=void 0,await t.unlink(this.filePath).catch(()=>{return});throw Z}finally{await W?.close()}}async readAll(){if(!l1.existsSync(this.filePath))return[];let $=await t.readFile(this.filePath,"utf-8");return _$($,this.filePath)}async readStream($){return new Promise((W,Z)=>{if(!l1.existsSync(this.filePath)){W();return}let Y=A7(this.filePath,"utf-8"),J=N7({input:Y,crlfDelay:Number.POSITIVE_INFINITY});J.on("line",async(X)=>{let V=X.trim();if(V.length===0)return;try{let H=JSON.parse(V);await $(H)}catch(H){console.warn(`[JSONLStore] 解析 JSON 行失败: ${V}`,H)}}),J.on("close",()=>W()),J.on("error",Z),Y.on("error",Z)})}async filter($){let W=[];return await this.readStream((Z)=>{if($(Z))W.push(Z)}),W}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!l1.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await t.stat(this.filePath),Z=(await t.readFile(this.filePath,"utf-8")).split(`
770
- `).filter((Y)=>Y.trim().length>0).length;return{exists:!0,size:$.size,lineCount:Z}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await t.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await t.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}async appendSerialized($){let Z=(n.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(async()=>{await t.mkdir(PW.dirname(this.filePath),{recursive:!0,mode:493});let Y=await this.repairIncompleteTail();await t.appendFile(this.filePath,Y+$,"utf-8")});n.appendQueues.set(this.filePath,Z);try{await Z}finally{if(n.appendQueues.get(this.filePath)===Z)n.appendQueues.delete(this.filePath)}}async repairIncompleteTail(){let $;try{$=await t.open(this.filePath,"r+")}catch(W){if(W instanceof Error&&"code"in W&&W.code==="ENOENT")return"";throw W}try{let{size:W}=await $.stat();if(W===0)return"";let Z=Buffer.allocUnsafe(1);if(await $.read(Z,0,1,W-1),Z[0]===10)return"";let Y=await this.findTailStart($,W),J=Buffer.allocUnsafe(W-Y);await $.read(J,0,J.length,Y);try{return JSON.parse(J.toString("utf8").trim()),`
771
- `}catch{return await $.truncate(Y),""}}finally{await $.close()}}async findTailStart($,W){let Z=W;while(Z>0){let Y=Math.max(0,Z-T7),J=Buffer.allocUnsafe(Z-Y);await $.read(J,0,J.length,Y);let X=J.lastIndexOf(10);if(X>=0)return Y+X+1;Z=Y}return 0}}class fW{projectPath;maxSessions;version;constructor($=D(),W=100,Z=h$()){this.projectPath=$,this.maxSessions=W,this.version=Z}createEvent($,W,Z){return{id:_0(),sessionId:W,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:i1(this.projectPath),version:this.version,data:Z}}async ensureSessionCreated($,W){let Z=o(this.projectPath,$),Y=new n(Z);if((await Y.readAll()).length>0)return;let X=new Date().toISOString(),V={sessionId:$,rootId:W?.parentSessionId??$,parentId:W?.parentSessionId,relationType:W?"subagent":void 0,title:void 0,status:"running",agentType:W?.subagentType,model:void 0,permission:void 0,createdAt:X,updatedAt:X},H=this.createEvent("session_created",$,V);await Y.append(H)}buildCompactionMetadata($){let W={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)W.postTokens=$.postTokens;if($.filesIncluded)W.filesIncluded=$.filesIncluded;return W}async initialize(){try{let $=$$(this.projectPath);await x0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,W,Z,Y=null,J,X){try{let V=o(this.projectPath,$),H=new n(V);await this.ensureSessionCreated($,X);let B=new Date().toISOString(),K=_0(),Q={messageId:K,role:W,parentMessageId:Y??void 0,inboxMessageId:J?.inboxMessageId,createdAt:B,model:J?.model,usage:J?.usage},U=this.createEvent("message_created",$,Q),q=typeof Z==="string"?[this.createEvent("part_created",$,{partId:_0(),messageId:K,partType:"text",payload:{text:Z},createdAt:B})]:Z.map((w)=>this.createEvent("part_created",$,{partId:_0(),messageId:K,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:k7(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:B}));return await H.appendBatch([U,...q]),K}catch(V){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,V),V}}async acknowledgeInboxMessages($,W){if(W.length===0)return;let Z=o(this.projectPath,$),Y=new n(Z);await this.ensureSessionCreated($);let J=new Date().toISOString();await Y.append(this.createEvent("inbox_acknowledged",$,{messageIds:[...W],acknowledgedAt:J}))}async saveToolUse($,W,Z,Y=null,J){try{let X=o(this.projectPath,$),V=new n(X);await this.ensureSessionCreated($,J);let H=new Date().toISOString(),B=Y??_0(),K=[];if(!Y){let q={messageId:B,role:"assistant",parentMessageId:void 0,createdAt:H};K.push(this.createEvent("message_created",$,q))}let Q=_0(),U={partId:Q,messageId:B,partType:"tool_call",payload:{toolCallId:Q,toolName:W,input:Z},createdAt:H};if(K.push(this.createEvent("part_created",$,U)),W==="Task"&&Z&&typeof Z==="object"){let q=Z,w=typeof q.subagent_session_id==="string"?q.subagent_session_id:void 0,E=typeof q.subagent_type==="string"?q.subagent_type:void 0;if(w&&E){let G={partId:_0(),messageId:B,partType:"subtask_ref",payload:{childSessionId:w,agentType:E,status:"running",summary:typeof q.description==="string"?q.description:"",startedAt:H},createdAt:H};K.push(this.createEvent("part_created",$,G))}}return await V.appendBatch(K),Q}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,W,Z,Y,J=null,X,V,H){try{let B=o(this.projectPath,$),K=new n(B);await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),U=J??_0(),q=[];if(!J){let E={messageId:U,role:"assistant",parentMessageId:void 0,createdAt:Q};q.push(this.createEvent("message_created",$,E))}let w={partId:W,messageId:U,partType:"tool_result",payload:{toolCallId:W,toolName:Z,output:Y,error:X??null},createdAt:Q};if(q.push(this.createEvent("part_created",$,w)),H){let E=H.subagentStatus==="running"?null:Q,G={partId:_0(),messageId:U,partType:"subtask_ref",payload:{childSessionId:H.subagentSessionId,agentType:H.subagentType,status:H.subagentStatus,summary:H.subagentSummary??"",startedAt:Q,finishedAt:E},createdAt:Q};q.push(this.createEvent("part_created",$,G))}return await K.appendBatch(q),W}catch(B){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,B),B}}async saveCompaction($,W,Z,Y=null){try{let J=o(this.projectPath,$),X=new n(J);await this.ensureSessionCreated($);let V=new Date().toISOString(),H=_0(),B={messageId:H,role:"system",parentMessageId:Y??void 0,createdAt:V},K=this.buildCompactionMetadata(Z),Q={partId:_0(),messageId:H,partType:"summary",payload:{text:W,metadata:K},createdAt:V},U=[this.createEvent("message_created",$,B),this.createEvent("part_created",$,Q)];return await X.appendBatch(U),H}catch(J){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,J),J}}async initSession($){await this.ensureSessionCreated($)}async loadEvents($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();return Y.length>0?Y:null}catch{return null}}async loadSession($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();if(Y.length===0)return null;let J=Y.find((X)=>X.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Y[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();if(Y.length===0)return null;let J=new Map;for(let B of Y){if(B.type==="message_created")J.set(B.data.messageId,{id:B.data.messageId,role:B.data.role,content:"",timestamp:new Date(B.timestamp).getTime()});if(B.type==="part_created"&&B.data.partType==="text"){let K=J.get(B.data.messageId);if(K){let Q=B.data.payload;K.content=Q.text??""}}if(B.type==="part_created"&&B.data.partType==="image"){let K=J.get(B.data.messageId);if(K)K.content=K.content?`${K.content}
772
- [Image]`:"[Image]"}}let X=Array.from(J.values()),V=Y[Y.length-1],H=new Date(V.timestamp).getTime();return{messages:X,topics:[],lastActivity:H}}catch{return null}}async listSessions(){try{let $=$$(this.projectPath);return(await x0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let W=o(this.projectPath,$),Z=new n(W);if(!(await Z.getStats()).exists)return null;let J=await Z.readAll();if(J.length===0)return null;let X=J[J.length-1],V=J.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:V,topics:[]}}catch{return null}}async deleteSession($){try{let W=o(this.projectPath,$);await new n(W).delete(),await x0.unlink(I$(this.projectPath,$)).catch((Y)=>{if(Y.code!=="ENOENT")throw Y})}catch(W){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,W)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((J)=>this.getSessionSummary(J)))).filter((J)=>J!==null).sort((J,X)=>X.lastActivity-J.lastActivity).slice(this.maxSessions).map((J)=>J.sessionId);await Promise.all(Y.map((J)=>this.deleteSession(J))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),W=0;for(let Z of $){let Y=o(this.projectPath,Z),X=await new n(Y).getStats();W+=X.size}return{totalSessions:$.length,totalSize:W,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=$$(this.projectPath);await x0.mkdir($,{recursive:!0,mode:493});let W=y5.join($,".health-check");return await x0.writeFile(W,"test","utf-8"),await x0.unlink(W),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return C5()}}function k7($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class H1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let W=$.storage?.persistentPath||V0();this.options={projectPath:$.projectPath||D(),storage:{maxMemorySize:1000,persistentPath:W,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new yW(this.options.storage.maxMemorySize),this.persistent=new fW(this.options.projectPath,100),this.cache=new CW(this.options.storage.cacheSize,300000),this.compressor=new xW,this.filter=new D$(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($,W={},Z={}){let Y=Z.sessionId||this.generateSessionId(),J=Date.now(),X={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:W,configuration:Z,startTime:J},conversation:{messages:[],topics:[],lastActivity:J},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:J}};return this.memory.setContext(X),await this.persistent.initSession(Y),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let W=this.memory.getContext();if(!W||W.layers.session.sessionId!==$){let Z=await this.persistent.loadEvents($);if(!Z||Z.length===0)return!1;if(W=new vW().assembleContextData(Z,await this.createSystemContext(),await this.createWorkspaceContext()),!W)return!1;this.memory.setContext(W)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(W){return console.error("加载会话失败:",W),!1}}async addMessage($,W,Z){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:W,timestamp:Date.now(),metadata:Z};this.memory.addMessage(Y);let J=this.memory.getContext();if(J&&this.shouldCompress(J))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($,W,Z,Y=null,J,X){return this.persistent.saveMessage($,W,Z,Y,J,X)}async saveToolUse($,W,Z,Y=null,J){return this.persistent.saveToolUse($,W,Z,Y,J)}async saveToolResult($,W,Z,Y,J=null,X,V,H){return this.persistent.saveToolResult($,W,Z,Y,J,X,V,H)}async saveCompaction($,W,Z,Y=null){return this.persistent.saveCompaction($,W,Z,Y)}updateToolState($,W){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,W)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let W=this.memory.getContext();if(!W)throw Error("没有可用的上下文数据");let Z=this.filter.filter(W,$),Y=this.shouldCompress(Z),J;if(Y){let X=this.hashContext(Z);if(J=this.cache.getCompressedContext(X)??void 0,!J)J=await this.compressor.compress(Z),this.cache.cacheCompressedContext(X,J)}return{context:Z,compressed:J,tokenCount:J?J.tokenCount:Z.metadata.totalTokens}}async searchSessions($,W=10){let Z=await this.persistent.listSessions(),Y=[];for(let J of Z){let X=await this.persistent.getSessionSummary(J);if(X){let V=this.calculateRelevance($,X.topics);if(V>0)Y.push({sessionId:J,summary:`${X.messageCount}条消息,主题:${X.topics.join("、")}`,lastActivity:X.lastActivity,relevanceScore:V})}}return Y.sort((J,X)=>X.relevanceScore-J.relevanceScore).slice(0,W)}getCachedToolResult($,W){return this.cache.getToolResult($,W)}async getStats(){let[$,W,Z]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:W,storage:Z}}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 P5()}generateMessageId(){return P5()}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 W=await this.compressor.compress($);$.layers.conversation.summary=W.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let W=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return f5.createHash("md5").update(W).digest("hex")}calculateRelevance($,W){let Z=$.toLowerCase(),Y=0;for(let J of W)if(Z.includes(J.toLowerCase())||J.toLowerCase().includes(Z))Y+=1;return Y}}class B1{chatService;contextManager;memoryAdapter;constructor($,W,Z){this.chatService=$,this.contextManager=W||new H1({projectPath:Z||D()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(W)=>{$.push(W)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let W=[{role:"user",content:$.prompt}],Z=await this.chatService.chat(W);return{taskId:$.id,content:Z.content,metadata:{taskType:$.type}}}}var v=P("Agent");class B0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;constructor($,W={},Z,Y){this.config=$,this.runtimeOptions=W,this.toolExecutor=Z||this.createDefaultToolExecutor(),this.sessionRuntime=Y}createDefaultToolExecutor(){let $=new O$,W={...this.config.permissions,...this.runtimeOptions.permissions},Z=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new V1($,{permissionConfig:W,permissionMode:Z,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let W=$&&$!=="inherit"?$:void 0,Z=W?K1(W):j0();if(!Z)throw Error(`模型配置未找到: ${W??"current"}`);return Z}async applyModelConfig($,W){this.log(`${W} ${$.name} (${$.model})`);let Z=c1($),Y=a1(),J=Z&&Y;if(Z&&!Y)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(J)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await o1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:$.timeout??this.config.timeout,supportsThinking:J,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let X=this.executionEngine?.getContextManager();this.executionEngine=new B1(this.chatService,X),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let W=K1($);if(!W){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(W,"切换模型")}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 n1(),W$().length===0)throw Error(`没有可用的模型配置
769
+ `;await W.writeFile(Z,"utf-8"),await W.sync()}catch(Z){if(W)await W.close(),W=void 0,await t.unlink(this.filePath).catch(()=>{return});throw Z}finally{await W?.close()}}async readAll(){if(!l1.existsSync(this.filePath))return[];let $=await t.readFile(this.filePath,"utf-8");return D$($,this.filePath)}async readStream($){return new Promise((W,Z)=>{if(!l1.existsSync(this.filePath)){W();return}let Y=A7(this.filePath,"utf-8"),J=N7({input:Y,crlfDelay:Number.POSITIVE_INFINITY});J.on("line",async(X)=>{let V=X.trim();if(V.length===0)return;try{let H=JSON.parse(V);await $(H)}catch(H){console.warn(`[JSONLStore] 解析 JSON 行失败: ${V}`,H)}}),J.on("close",()=>W()),J.on("error",Z),Y.on("error",Z)})}async filter($){let W=[];return await this.readStream((Z)=>{if($(Z))W.push(Z)}),W}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!l1.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await t.stat(this.filePath),Z=(await t.readFile(this.filePath,"utf-8")).split(`
770
+ `).filter((Y)=>Y.trim().length>0).length;return{exists:!0,size:$.size,lineCount:Z}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await t.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await t.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}async appendSerialized($){let Z=(n.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(async()=>{await t.mkdir(fW.dirname(this.filePath),{recursive:!0,mode:493});let Y=await this.repairIncompleteTail();await t.appendFile(this.filePath,Y+$,"utf-8")});n.appendQueues.set(this.filePath,Z);try{await Z}finally{if(n.appendQueues.get(this.filePath)===Z)n.appendQueues.delete(this.filePath)}}async repairIncompleteTail(){let $;try{$=await t.open(this.filePath,"r+")}catch(W){if(W instanceof Error&&"code"in W&&W.code==="ENOENT")return"";throw W}try{let{size:W}=await $.stat();if(W===0)return"";let Z=Buffer.allocUnsafe(1);if(await $.read(Z,0,1,W-1),Z[0]===10)return"";let Y=await this.findTailStart($,W),J=Buffer.allocUnsafe(W-Y);await $.read(J,0,J.length,Y);try{return JSON.parse(J.toString("utf8").trim()),`
771
+ `}catch{return await $.truncate(Y),""}}finally{await $.close()}}async findTailStart($,W){let Z=W;while(Z>0){let Y=Math.max(0,Z-T7),J=Buffer.allocUnsafe(Z-Y);await $.read(J,0,J.length,Y);let X=J.lastIndexOf(10);if(X>=0)return Y+X+1;Z=Y}return 0}}class PW{projectPath;maxSessions;version;constructor($=D(),W=100,Z=h$()){this.projectPath=$,this.maxSessions=W,this.version=Z}createEvent($,W,Z){return{id:D0(),sessionId:W,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:i1(this.projectPath),version:this.version,data:Z}}async ensureSessionCreated($,W){let Z=o(this.projectPath,$),Y=new n(Z);if((await Y.readAll()).length>0)return;let X=new Date().toISOString(),V={sessionId:$,rootId:W?.parentSessionId??$,parentId:W?.parentSessionId,relationType:W?"subagent":void 0,title:void 0,status:"running",agentType:W?.subagentType,model:void 0,permission:void 0,createdAt:X,updatedAt:X},H=this.createEvent("session_created",$,V);await Y.append(H)}buildCompactionMetadata($){let W={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)W.postTokens=$.postTokens;if($.filesIncluded)W.filesIncluded=$.filesIncluded;return W}async initialize(){try{let $=$$(this.projectPath);await x0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,W,Z,Y=null,J,X){try{let V=o(this.projectPath,$),H=new n(V);await this.ensureSessionCreated($,X);let K=new Date().toISOString(),B=D0(),U={messageId:B,role:W,parentMessageId:Y??void 0,inboxMessageId:J?.inboxMessageId,createdAt:K,model:J?.model,usage:J?.usage},Q=this.createEvent("message_created",$,U),q=typeof Z==="string"?[this.createEvent("part_created",$,{partId:D0(),messageId:B,partType:"text",payload:{text:Z},createdAt:K})]:Z.map((w)=>this.createEvent("part_created",$,{partId:D0(),messageId:B,partType:w.type==="text"?"text":"image",payload:w.type==="text"?{text:w.text}:{mimeType:k7(w.image_url.url)??"image/png",dataUrl:w.image_url.url},createdAt:K}));return await H.appendBatch([Q,...q]),B}catch(V){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,V),V}}async acknowledgeInboxMessages($,W){if(W.length===0)return;let Z=o(this.projectPath,$),Y=new n(Z);await this.ensureSessionCreated($);let J=new Date().toISOString();await Y.append(this.createEvent("inbox_acknowledged",$,{messageIds:[...W],acknowledgedAt:J}))}async saveToolUse($,W,Z,Y=null,J){try{let X=o(this.projectPath,$),V=new n(X);await this.ensureSessionCreated($,J);let H=new Date().toISOString(),K=Y??D0(),B=[];if(!Y){let q={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:H};B.push(this.createEvent("message_created",$,q))}let U=D0(),Q={partId:U,messageId:K,partType:"tool_call",payload:{toolCallId:U,toolName:W,input:Z},createdAt:H};if(B.push(this.createEvent("part_created",$,Q)),W==="Task"&&Z&&typeof Z==="object"){let q=Z,w=typeof q.subagent_session_id==="string"?q.subagent_session_id:void 0,E=typeof q.subagent_type==="string"?q.subagent_type:void 0;if(w&&E){let G={partId:D0(),messageId:K,partType:"subtask_ref",payload:{childSessionId:w,agentType:E,status:"running",summary:typeof q.description==="string"?q.description:"",startedAt:H},createdAt:H};B.push(this.createEvent("part_created",$,G))}}return await V.appendBatch(B),U}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,W,Z,Y,J=null,X,V,H){try{let K=o(this.projectPath,$),B=new n(K);await this.ensureSessionCreated($,V);let U=new Date().toISOString(),Q=J??D0(),q=[];if(!J){let E={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:U};q.push(this.createEvent("message_created",$,E))}let w={partId:W,messageId:Q,partType:"tool_result",payload:{toolCallId:W,toolName:Z,output:Y,error:X??null},createdAt:U};if(q.push(this.createEvent("part_created",$,w)),H){let E=H.subagentStatus==="running"?null:U,G={partId:D0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:H.subagentSessionId,agentType:H.subagentType,status:H.subagentStatus,summary:H.subagentSummary??"",startedAt:U,finishedAt:E},createdAt:U};q.push(this.createEvent("part_created",$,G))}return await B.appendBatch(q),W}catch(K){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,K),K}}async saveCompaction($,W,Z,Y=null){try{let J=o(this.projectPath,$),X=new n(J);await this.ensureSessionCreated($);let V=new Date().toISOString(),H=D0(),K={messageId:H,role:"system",parentMessageId:Y??void 0,createdAt:V},B=this.buildCompactionMetadata(Z),U={partId:D0(),messageId:H,partType:"summary",payload:{text:W,metadata:B},createdAt:V},Q=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,U)];return await X.appendBatch(Q),H}catch(J){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,J),J}}async initSession($){await this.ensureSessionCreated($)}async loadEvents($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();return Y.length>0?Y:null}catch{return null}}async loadSession($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();if(Y.length===0)return null;let J=Y.find((X)=>X.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Y[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let W=o(this.projectPath,$),Y=await new n(W).readAll();if(Y.length===0)return null;let J=new Map;for(let K of Y){if(K.type==="message_created")J.set(K.data.messageId,{id:K.data.messageId,role:K.data.role,content:"",timestamp:new Date(K.timestamp).getTime()});if(K.type==="part_created"&&K.data.partType==="text"){let B=J.get(K.data.messageId);if(B){let U=K.data.payload;B.content=U.text??""}}if(K.type==="part_created"&&K.data.partType==="image"){let B=J.get(K.data.messageId);if(B)B.content=B.content?`${B.content}
772
+ [Image]`:"[Image]"}}let X=Array.from(J.values()),V=Y[Y.length-1],H=new Date(V.timestamp).getTime();return{messages:X,topics:[],lastActivity:H}}catch{return null}}async listSessions(){try{let $=$$(this.projectPath);return(await x0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let W=o(this.projectPath,$),Z=new n(W);if(!(await Z.getStats()).exists)return null;let J=await Z.readAll();if(J.length===0)return null;let X=J[J.length-1],V=J.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:V,topics:[]}}catch{return null}}async deleteSession($){try{let W=o(this.projectPath,$);await new n(W).delete(),await x0.unlink(I$(this.projectPath,$)).catch((Y)=>{if(Y.code!=="ENOENT")throw Y})}catch(W){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,W)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let Y=(await Promise.all($.map((J)=>this.getSessionSummary(J)))).filter((J)=>J!==null).sort((J,X)=>X.lastActivity-J.lastActivity).slice(this.maxSessions).map((J)=>J.sessionId);await Promise.all(Y.map((J)=>this.deleteSession(J))),console.log(`[PersistentStore] 已清理 ${Y.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),W=0;for(let Z of $){let Y=o(this.projectPath,Z),X=await new n(Y).getStats();W+=X.size}return{totalSessions:$.length,totalSize:W,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=$$(this.projectPath);await x0.mkdir($,{recursive:!0,mode:493});let W=y5.join($,".health-check");return await x0.writeFile(W,"test","utf-8"),await x0.unlink(W),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return C5()}}function k7($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class H1{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let W=$.storage?.persistentPath||V0();this.options={projectPath:$.projectPath||D(),storage:{maxMemorySize:1000,persistentPath:W,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new yW(this.options.storage.maxMemorySize),this.persistent=new PW(this.options.projectPath,100),this.cache=new CW(this.options.storage.cacheSize,300000),this.compressor=new xW,this.filter=new _$(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($,W={},Z={}){let Y=Z.sessionId||this.generateSessionId(),J=Date.now(),X={layers:{system:await this.createSystemContext(),session:{sessionId:Y,userId:$,preferences:W,configuration:Z,startTime:J},conversation:{messages:[],topics:[],lastActivity:J},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:J}};return this.memory.setContext(X),await this.persistent.initSession(Y),this.currentSessionId=Y,console.log(`新会话已创建: ${Y}`),Y}async loadSession($){try{let W=this.memory.getContext();if(!W||W.layers.session.sessionId!==$){let Z=await this.persistent.loadEvents($);if(!Z||Z.length===0)return!1;if(W=new vW().assembleContextData(Z,await this.createSystemContext(),await this.createWorkspaceContext()),!W)return!1;this.memory.setContext(W)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(W){return console.error("加载会话失败:",W),!1}}async addMessage($,W,Z){if(!this.currentSessionId)throw Error("没有活动会话");let Y={id:this.generateMessageId(),role:$,content:W,timestamp:Date.now(),metadata:Z};this.memory.addMessage(Y);let J=this.memory.getContext();if(J&&this.shouldCompress(J))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($,W,Z,Y=null,J,X){return this.persistent.saveMessage($,W,Z,Y,J,X)}async saveToolUse($,W,Z,Y=null,J){return this.persistent.saveToolUse($,W,Z,Y,J)}async saveToolResult($,W,Z,Y,J=null,X,V,H){return this.persistent.saveToolResult($,W,Z,Y,J,X,V,H)}async saveCompaction($,W,Z,Y=null){return this.persistent.saveCompaction($,W,Z,Y)}updateToolState($,W){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,W)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let W=this.memory.getContext();if(!W)throw Error("没有可用的上下文数据");let Z=this.filter.filter(W,$),Y=this.shouldCompress(Z),J;if(Y){let X=this.hashContext(Z);if(J=this.cache.getCompressedContext(X)??void 0,!J)J=await this.compressor.compress(Z),this.cache.cacheCompressedContext(X,J)}return{context:Z,compressed:J,tokenCount:J?J.tokenCount:Z.metadata.totalTokens}}async searchSessions($,W=10){let Z=await this.persistent.listSessions(),Y=[];for(let J of Z){let X=await this.persistent.getSessionSummary(J);if(X){let V=this.calculateRelevance($,X.topics);if(V>0)Y.push({sessionId:J,summary:`${X.messageCount}条消息,主题:${X.topics.join("、")}`,lastActivity:X.lastActivity,relevanceScore:V})}}return Y.sort((J,X)=>X.relevanceScore-J.relevanceScore).slice(0,W)}getCachedToolResult($,W){return this.cache.getToolResult($,W)}async getStats(){let[$,W,Z]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:W,storage:Z}}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 f5()}generateMessageId(){return f5()}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 W=await this.compressor.compress($);$.layers.conversation.summary=W.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let W=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return P5.createHash("md5").update(W).digest("hex")}calculateRelevance($,W){let Z=$.toLowerCase(),Y=0;for(let J of W)if(Z.includes(J.toLowerCase())||J.toLowerCase().includes(Z))Y+=1;return Y}}class B1{chatService;contextManager;memoryAdapter;constructor($,W,Z){this.chatService=$,this.contextManager=W||new H1({projectPath:Z||D()}),this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(W)=>{$.push(W)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let W=[{role:"user",content:$.prompt}],Z=await this.chatService.chat(W);return{taskId:$.id,content:Z.content,metadata:{taskType:$.type}}}}var v=f("Agent");class B0{config;runtimeOptions;isInitialized=!1;activeTask;toolExecutor;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;constructor($,W={},Z,Y){this.config=$,this.runtimeOptions=W,this.toolExecutor=Z||this.createDefaultToolExecutor(),this.sessionRuntime=Y}createDefaultToolExecutor(){let $=new O$,W={...this.config.permissions,...this.runtimeOptions.permissions},Z=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new V1($,{permissionConfig:W,permissionMode:Z,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let W=$&&$!=="inherit"?$:void 0,Z=W?K1(W):j0();if(!Z)throw Error(`模型配置未找到: ${W??"current"}`);return Z}async applyModelConfig($,W){this.log(`${W} ${$.name} (${$.model})`);let Z=c1($),Y=a1(),J=Z&&Y;if(Z&&!Y)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(J)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await o1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:$.timeout??this.config.timeout,supportsThinking:J,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let X=this.executionEngine?.getContextManager();this.executionEngine=new B1(this.chatService,X),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let W=K1($);if(!W){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(W,"切换模型")}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 n1(),W$().length===0)throw Error(`没有可用的模型配置
773
773
 
774
774
  `+`请先使用以下命令添加模型:
775
775
  `+` /model add
776
776
 
777
777
  `+`或运行初始化向导:
778
- `+" /init");let Z=Y0();if(!Z)throw Error("配置未初始化,请确保应用已正确启动");r1.getInstance().validateConfig(Z);let J={...$};if(!J.toolWhitelist&&Z.allowedTools?.length)J.toolWhitelist=Z.allowedTools;if(!J.toolBlacklist&&Z.disallowedTools?.length)J.toolBlacklist=Z.disallowedTools;let X=new B0(Z,J);if(await X.initialize(),J.toolWhitelist&&J.toolWhitelist.length>0)X.applyToolWhitelist(J.toolWhitelist);if(J.toolBlacklist&&J.toolBlacklist.length>0)X.applyToolBlacklist(J.toolBlacklist);return X}static async createWithRuntime($,W={}){let Z=Y0(),Y={...W};if(!Y.toolWhitelist&&Z?.allowedTools?.length)Y.toolWhitelist=Z.allowedTools;if(!Y.toolBlacklist&&Z?.disallowedTools?.length)Y.toolBlacklist=Z.disallowedTools;let J=new B0($.getConfig(),Y,$.createToolExecutor(Y),$);return await J.initialize(),J}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.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"使用模型:"),this.attachmentCollector=new e$({cwd:D(),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 W=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),W}catch(W){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,W),W}}async*chatStream($,W,Z){if(!this.isInitialized)throw Error("Agent未初始化");if(W?.workspaceRoot)this.attachmentCollector?.setCwd(W.workspaceRoot);let Y=await this.processAtMentionsForContent($);if(W){let H=Y,B=W,K=Z?.pendingInputOnly===!0;if(this.sessionRuntime&&!K&&!this.sessionRuntime.hasTurnOwner()&&this.sessionRuntime.getPendingSteeringCount()>0){let w=await this.sessionRuntime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Pending user input queue is full":"Pending user input could not be queued");K=!0,H=""}let Q=this.sessionRuntime?K?await this.sessionRuntime.beginPendingTurn():this.sessionRuntime.beginTurn():void 0,U=0;if(K&&this.sessionRuntime&&!Q)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let q=()=>this.sessionRuntime.getPendingSteeringMessages().map((w)=>({...w,persisted:B.messages.some((E)=>{let G=E.metadata;return G!==null&&typeof G==="object"&&!Array.isArray(G)&&G.inboxMessageId===w.id})}));try{if(K&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:q()};while(!0){let w=Q,E={...Z,pendingInputOnly:K,signal:B.signal,turnSteering:this.sessionRuntime&&w?{drain:()=>this.sessionRuntime.drainSteering(w),drainOrSeal:()=>this.sessionRuntime.drainSteeringOrSeal(w)}:void 0},G;if(B.permissionMode==="plan")G=yield*this.runPlanLoop(H,B,E);else G=yield*this.runLoop(H,B,E);if(G.success&&G.metadata?.targetMode&&B.permissionMode==="plan"){let R=G.metadata.targetMode,O=G.metadata.planContent;v.debug(`Plan 模式已批准,切换到 ${R} 模式并重新执行`),await a0().setPermissionMode(R),B={...B,permissionMode:R};let _=H;if(O){let z=`
778
+ `+" /init");let Z=Y0();if(!Z)throw Error("配置未初始化,请确保应用已正确启动");r1.getInstance().validateConfig(Z);let J={...$};if(!J.toolWhitelist&&Z.allowedTools?.length)J.toolWhitelist=Z.allowedTools;if(!J.toolBlacklist&&Z.disallowedTools?.length)J.toolBlacklist=Z.disallowedTools;let X=new B0(Z,J);if(await X.initialize(),J.toolWhitelist&&J.toolWhitelist.length>0)X.applyToolWhitelist(J.toolWhitelist);if(J.toolBlacklist&&J.toolBlacklist.length>0)X.applyToolBlacklist(J.toolBlacklist);return X}static async createWithRuntime($,W={}){let Z=Y0(),Y={...W};if(!Y.toolWhitelist&&Z?.allowedTools?.length)Y.toolWhitelist=Z.allowedTools;if(!Y.toolBlacklist&&Z?.disallowedTools?.length)Y.toolBlacklist=Z.disallowedTools;let J=new B0($.getConfig(),Y,$.createToolExecutor(Y),$);return await J.initialize(),J}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.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills();let $=this.resolveModelConfig(this.runtimeOptions.modelId);await this.applyModelConfig($,"使用模型:"),this.attachmentCollector=new e$({cwd:D(),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 W=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),W}catch(W){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,W),W}}async*chatStream($,W,Z){if(!this.isInitialized)throw Error("Agent未初始化");if(W?.workspaceRoot)this.attachmentCollector?.setCwd(W.workspaceRoot);let Y=Z?.pendingInputOnly===!0;if(Y&&Z?.preparedInputTurn)throw Error("preparedInputTurn cannot be combined with pendingInputOnly");if(!W&&Z?.preparedInputTurn)throw Error("preparedInputTurn requires a ChatContext");let J=Z?.preparedInputTurn;if(W&&this.sessionRuntime&&!Y){if(!J){let B=await this.sessionRuntime.prepareInputTurn($);if(!B.accepted)throw Error(B.reason==="queue_full"?"Pending user input queue is full":"Session already has an active turn");J=B}}let X=$;if(!Y&&J?.mode!=="pending")try{X=await this.processAtMentionsForContent($)}catch(B){if(this.sessionRuntime&&J)await this.sessionRuntime.finishTurn(J.handle).catch(()=>{return});throw B}else if(!W||!this.sessionRuntime)X=await this.processAtMentionsForContent($);if(W){let B=X,U=W,Q=Y,q,w;if(this.sessionRuntime)if(Q)w=await this.sessionRuntime.beginPendingTurn();else{let z=J;if(w=z.handle,z.mode==="pending")Q=!0,B="";else q=z.messageId}let E=0;if(Q&&this.sessionRuntime&&!w)return{success:!0,finalMessage:"",metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let G=()=>this.sessionRuntime.getPendingSteeringMessages().map((z)=>({...z,persisted:U.messages.some((O)=>{let _=O.metadata;return _!==null&&typeof _==="object"&&!Array.isArray(_)&&_.inboxMessageId===z.id})})),F=async(z)=>Promise.all(z.map(async(O)=>({...O,content:await this.processAtMentionsForContent(O.content)})));try{if(Q&&this.sessionRuntime)yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:G()};while(!0){let z=w,O={...Z,pendingInputOnly:Q,preparedInputTurn:void 0,inputMessageId:Q?void 0:q,signal:U.signal,turnSteering:this.sessionRuntime&&z?{drain:async()=>F(await this.sessionRuntime.drainSteering(z)),drainOrSeal:async()=>{let j=await this.sessionRuntime.drainSteeringOrSeal(z);return{...j,messages:await F(j.messages)}}}:void 0},_;if(U.permissionMode==="plan")_=yield*this.runPlanLoop(B,U,O);else _=yield*this.runLoop(B,U,O);if(_.success&&_.metadata?.targetMode&&U.permissionMode==="plan"){let j=_.metadata.targetMode,A=_.metadata.planContent;v.debug(`Plan 模式已批准,切换到 ${j} 模式并重新执行`),await a0().setPermissionMode(j),U={...U,permissionMode:j};let L=B;if(A){let b=`
779
779
 
780
780
  <approved-plan>
781
- ${O}
781
+ ${A}
782
782
  </approved-plan>
783
783
 
784
- IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")_=H+z;else _=[...H,{type:"text",text:z}]}G=yield*this.runLoop(_,B,E)}if(!this.sessionRuntime||!w)return G;if(G.success&&!B.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(w);let F=!B.signal?.aborted&&U<20;if(Q=await this.sessionRuntime.finishTurn(w,{continuePending:F}),!Q)return G;U++,K=!0,H="",yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:q()}}}finally{if(this.sessionRuntime&&Q)await this.sessionRuntime.finishTurn(Q)}}let J=typeof Y==="string"?Y:Y.filter((H)=>H.type==="text").map((H)=>H.text).join(`
785
- `),X={id:this.generateTaskId(),type:"simple",prompt:J};return{success:!0,finalMessage:(await this.executeTask(X)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,W,Z){let{drainLoop:Y}=await import("./chunk-jpry8h07.js");return Y(this.chatStream($,W,Z))}async*runPlanLoop($,W,Z){v.debug("Processing Plan mode message...");let{prompt:Y}=await q$({projectPath:W.workspaceRoot||D(),mode:"plan",includeEnvironment:!0,language:this.config.language}),J;if(typeof $==="string")J=s$($);else{let X=$.filter((V)=>V.type==="text");if(X.length>0){let V=X[0];J=$.map((H)=>H===V?{type:"text",text:s$(V.text)}:H)}else J=[{type:"text",text:s$("")},...$]}return yield*this.executeLoop(J,W,Z,Y)}async*runLoop($,W,Z){v.debug("Processing enhanced chat message...");let Y=W.systemPrompt??await this.buildSystemPromptOnDemand(W.workspaceRoot||D());return yield*this.executeLoop($,W,Z,Y)}async buildSystemPromptOnDemand($){let W=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await q$({projectPath:$,replaceDefault:W,append:Z,includeEnvironment:!0,language:this.config.language})).prompt}executeLoop($,W,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let J=this.buildLoopDependencies();return S5(J,$,W,Z,Y)}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=$,v.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($)}}async chatWithSystem($,W){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:W}];return(await this.chatService.chat(Z)).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 W=this.toolExecutor.getRegistry(),Y=W.getAll().filter((J)=>!$.includes(J.name));for(let J of Y)W.unregister(J.name);v.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let W=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of W.getAll())if(Z.has(Y.name))W.unregister(Y.name);v.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),W=new Map;return $.forEach((Z)=>{let Y=W.get(Z.kind)||0;W.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(W),toolNames:$.map((Z)=>Z.name)}}async destroy(){this.log("销毁Agent...");try{this.isInitialized=!1,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}}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($,W){v.debug(`[MainAgent] ${$}`,W||"")}error($,W){v.error(`[MainAgent] ${$}`,W||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,W=this.runtimeOptions.appendSystemPrompt,Z=await q$({projectPath:this.sessionRuntime?.workspaceRoot??D(),replaceDefault:$,append:W,includeEnvironment:!1,language:this.config.language});if(Z.prompt)this.log("系统提示配置验证成功"),v.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await s1({sessionId:"default",configDir:h5.join(I5.homedir(),".blade")});v.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let W=this.toolExecutor.getRegistry().getAll().length;v.debug(`Builtin tools registered: ${W} tools`),v.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw v.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{if(this.runtimeOptions.mcpConfig&&this.runtimeOptions.mcpConfig.length>0)await M1(this.runtimeOptions.mcpConfig);let $=k0();if(Object.keys($).length===0){v.debug("No MCP servers configured");return}let W=G0.getInstance();for(let[Y,J]of Object.entries($))try{v.debug(`Connecting to MCP server: ${Y}`),await W.registerServer(Y,J),v.debug(`MCP server "${Y}" connected`)}catch(X){v.warn(`Warning: MCP server "${Y}" connection failed:`,X)}let Z=await W.getAvailableTools();if(Z.length>0)this.toolExecutor.getRegistry().registerAll(Z),v.debug(`Registered ${Z.length} MCP tools`),v.debug(`[MCP Tools] ${Z.map((Y)=>Y.name).join(", ")}`)}catch($){v.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(f.getAllNames().length>0){v.debug(`Subagents already loaded: ${f.getAllNames().join(", ")}`);return}try{let $=f.loadFromStandardLocations();if($>0)v.debug(`Loaded ${$} subagents: ${f.getAllNames().join(", ")}`);else v.debug("No subagents configured")}catch($){v.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await u$({cwd:D()});if($.skills.length>0)v.debug(`Discovered ${$.skills.length} skills: ${$.skills.map((W)=>W.name).join(", ")}`);else v.debug("No skills configured");for(let W of $.errors)v.warn(`Warning: Skill loading error at ${W.path}: ${W.error}`)}catch($){v.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let W=this.activeSkillContext.allowedTools;v.debug(`Applying Skill tool restrictions: ${W.join(", ")}`);let Z=$.filter((Y)=>{return W.some((J)=>{if(J===Y.name)return!0;let X=J.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return v.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)v.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let W=[];for(let Y of $)if(Y.type==="text")W.push(Y.text);if(W.length===0)return $;let Z=W.join(`
784
+ IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof B==="string")L=B+b;else L=[...B,{type:"text",text:b}]}_=yield*this.runLoop(L,U,{...O,inputMessageId:void 0})}if(!this.sessionRuntime||!z)return _;if(_.success&&!U.signal?.aborted)await this.sessionRuntime.acknowledgeTurn(z);let R=_.success&&!U.signal?.aborted&&E<20;if(w=await this.sessionRuntime.finishTurn(z,{continuePending:R}),!w)return _;E++,Q=!0,B="",yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:G()}}}finally{if(this.sessionRuntime&&w)await this.sessionRuntime.finishTurn(w)}}let V=typeof X==="string"?X:X.filter((B)=>B.type==="text").map((B)=>B.text).join(`
785
+ `),H={id:this.generateTaskId(),type:"simple",prompt:V};return{success:!0,finalMessage:(await this.executeTask(H)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,W,Z){let{drainLoop:Y}=await import("./chunk-g1eb7f4q.js");return Y(this.chatStream($,W,Z))}async*runPlanLoop($,W,Z){v.debug("Processing Plan mode message...");let{prompt:Y}=await q$({projectPath:W.workspaceRoot||D(),mode:"plan",includeEnvironment:!0,language:this.config.language}),J;if(typeof $==="string")J=s$($);else{let X=$.filter((V)=>V.type==="text");if(X.length>0){let V=X[0];J=$.map((H)=>H===V?{type:"text",text:s$(V.text)}:H)}else J=[{type:"text",text:s$("")},...$]}return yield*this.executeLoop(J,W,Z,Y)}async*runLoop($,W,Z){v.debug("Processing enhanced chat message...");let Y=W.systemPrompt??await this.buildSystemPromptOnDemand(W.workspaceRoot||D());return yield*this.executeLoop($,W,Z,Y)}async buildSystemPromptOnDemand($){let W=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await q$({projectPath:$,replaceDefault:W,append:Z,includeEnvironment:!0,language:this.config.language})).prompt}executeLoop($,W,Z,Y){if(!this.isInitialized)throw Error("Agent未初始化");let J=this.buildLoopDependencies();return S5(J,$,W,Z,Y)}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=$,v.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($)}}async chatWithSystem($,W){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:W}];return(await this.chatService.chat(Z)).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 W=this.toolExecutor.getRegistry(),Y=W.getAll().filter((J)=>!$.includes(J.name));for(let J of Y)W.unregister(J.name);v.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let W=this.toolExecutor.getRegistry(),Z=new Set($);for(let Y of W.getAll())if(Z.has(Y.name))W.unregister(Y.name);v.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),W=new Map;return $.forEach((Z)=>{let Y=W.get(Z.kind)||0;W.set(Z.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(W),toolNames:$.map((Z)=>Z.name)}}async destroy(){this.log("销毁Agent...");try{this.isInitialized=!1,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}}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($,W){v.debug(`[MainAgent] ${$}`,W||"")}error($,W){v.error(`[MainAgent] ${$}`,W||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,W=this.runtimeOptions.appendSystemPrompt,Z=await q$({projectPath:this.sessionRuntime?.workspaceRoot??D(),replaceDefault:$,append:W,includeEnvironment:!1,language:this.config.language});if(Z.prompt)this.log("系统提示配置验证成功"),v.debug(`[SystemPrompt] 可用来源: ${Z.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await s1({sessionId:"default",configDir:h5.join(I5.homedir(),".blade")});v.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let W=this.toolExecutor.getRegistry().getAll().length;v.debug(`Builtin tools registered: ${W} tools`),v.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw v.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{if(this.runtimeOptions.mcpConfig&&this.runtimeOptions.mcpConfig.length>0)await M1(this.runtimeOptions.mcpConfig);let $=k0();if(Object.keys($).length===0){v.debug("No MCP servers configured");return}let W=G0.getInstance();for(let[Y,J]of Object.entries($))try{v.debug(`Connecting to MCP server: ${Y}`),await W.registerServer(Y,J),v.debug(`MCP server "${Y}" connected`)}catch(X){v.warn(`Warning: MCP server "${Y}" connection failed:`,X)}let Z=await W.getAvailableTools();if(Z.length>0)this.toolExecutor.getRegistry().registerAll(Z),v.debug(`Registered ${Z.length} MCP tools`),v.debug(`[MCP Tools] ${Z.map((Y)=>Y.name).join(", ")}`)}catch($){v.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0){v.debug(`Subagents already loaded: ${P.getAllNames().join(", ")}`);return}try{let $=P.loadFromStandardLocations();if($>0)v.debug(`Loaded ${$} subagents: ${P.getAllNames().join(", ")}`);else v.debug("No subagents configured")}catch($){v.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await u$({cwd:D()});if($.skills.length>0)v.debug(`Discovered ${$.skills.length} skills: ${$.skills.map((W)=>W.name).join(", ")}`);else v.debug("No skills configured");for(let W of $.errors)v.warn(`Warning: Skill loading error at ${W.path}: ${W.error}`)}catch($){v.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let W=this.activeSkillContext.allowedTools;v.debug(`Applying Skill tool restrictions: ${W.join(", ")}`);let Z=$.filter((Y)=>{return W.some((J)=>{if(J===Y.name)return!0;let X=J.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return v.debug(`Filtered tools: ${Z.map((Y)=>Y.name).join(", ")} (${Z.length}/${$.length})`),Z}clearSkillContext(){if(this.activeSkillContext)v.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let W=[];for(let Y of $)if(Y.type==="text")W.push(Y.text);if(W.length===0)return $;let Z=W.join(`
786
786
  `);try{let Y=await this.attachmentCollector.collect(Z);if(Y.length===0)return $;v.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let J=this.buildAttachmentText(Y);if(!J)return $;return[...$,{type:"text",text:J}]}catch(Y){return v.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let W=[],Z=[];for(let J of $)if(J.type==="file"){let X=J.metadata?.lineRange?` (lines ${J.metadata.lineRange.start}${J.metadata.lineRange.end?`-${J.metadata.lineRange.end}`:""})`:"";W.push(`<file path="${J.path}"${X?` range="${X}"`:""}>`,J.content,"</file>")}else if(J.type==="directory")W.push(`<directory path="${J.path}">`,J.content,"</directory>");else if(J.type==="error")Z.push(`- @${J.path}: ${J.error}`);let Y="";if(W.length>0)Y+=`
787
787
 
788
788
  <system-reminder>
@@ -805,9 +805,9 @@ Warning: Some files could not be loaded:
805
805
 
806
806
  Warning: Some files could not be loaded:
807
807
  `,J+=Y.join(`
808
- `);return J}}import Z$ from"node:fs";var b7=/^[A-Za-z]:\//;function SW($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(b7,(W)=>W.toUpperCase())}var M7=/^[/\\]{2}/,v7=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,x7=/^[A-Za-z]:$/,u5=/^\/([A-Za-z]:)?$/;var p5=function($){if($.length===0)return".";$=SW($);let W=$.match(M7),Z=j$($),Y=$[$.length-1]==="/";if($=IW($,!Z),$.length===0){if(Z)return"/";return Y?"./":"."}if(Y)$+="/";if(x7.test($))$+="/";if(W){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!j$($)?`/${$}`:$},p0=function(...$){let W="";for(let Z of $){if(!Z)continue;if(W.length>0){let Y=W[W.length-1]==="/",J=Z[0]==="/";if(Y&&J)W+=Z.slice(1);else W+=Y||J?Z:`/${Z}`}else W+=Z}return p5(W)};function C7(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}var u0=function(...$){$=$.map((Y)=>SW(Y));let W="",Z=!1;for(let Y=$.length-1;Y>=-1&&!Z;Y--){let J=Y>=0?$[Y]:C7();if(!J||J.length===0)continue;W=`${J}/${W}`,Z=j$(J)}if(W=IW(W,!Z),Z&&!j$(W))return`/${W}`;return W.length>0?W:"."};function IW($,W){let Z="",Y=0,J=-1,X=0,V=null;for(let H=0;H<=$.length;++H){if(H<$.length)V=$[H];else if(V==="/")break;else V="/";if(V==="/"){if(J===H-1||X===1);else if(X===2){if(Z.length<2||Y!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let B=Z.lastIndexOf("/");if(B===-1)Z="",Y=0;else Z=Z.slice(0,B),Y=Z.length-1-Z.lastIndexOf("/");J=H,X=0;continue}else if(Z.length>0){Z="",Y=0,J=H,X=0;continue}}if(W)Z+=Z.length>0?"/..":"..",Y=2}else{if(Z.length>0)Z+=`/${$.slice(J+1,H)}`;else Z=$.slice(J+1,H);Y=H-J-1}J=H,X=0}else if(V==="."&&X!==-1)++X;else X=-1}return Z}var j$=function($){return v7.test($)};var hW=function($,W){let Z=u0($).replace(u5,"$1").split("/"),Y=u0(W).replace(u5,"$1").split("/");if(Y[0][1]===":"&&Z[0][1]===":"&&Z[0]!==Y[0])return Y.join("/");let J=[...Z];for(let X of J){if(Y[0]!==X)break;Z.shift(),Y.shift()}return[...Z.map(()=>".."),...Y].join("/")};var uW=function($,W){let Z=SW($).split("/"),Y="";for(let J=Z.length-1;J>=0;J--){let X=Z[J];if(X){Y=X;break}}return W&&Y.endsWith(W)?Y.slice(0,-W.length):Y};var p$=P("Agent");class A${static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=p0(V0(),"agents","sessions"),this.ensureDirectory()}static getInstance(){if(!A$.instance)A$.instance=new A$;return A$.instance}ensureDirectory(){if(!Z$.existsSync(this.sessionsDir))Z$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let W=$.replace(/[^a-zA-Z0-9_-]/g,"_");return p0(this.sessionsDir,`${W}.json`)}saveSession($){try{let W=this.getSessionPath($.id),Z=JSON.stringify($,null,2);Z$.writeFileSync(W,Z,"utf-8"),this.cache.set($.id,$),p$.debug(`Session saved: ${$.id}`)}catch(W){p$.warn(`Failed to save session ${$.id}:`,W)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let W=this.getSessionPath($);if(!Z$.existsSync(W))return;let Z=Z$.readFileSync(W,"utf-8"),Y=JSON.parse(Z);return this.cache.set($,Y),Y}catch(W){p$.warn(`Failed to load session ${$}:`,W);return}}updateSession($,W){let Z=this.loadSession($);if(!Z)return;let Y={...Z,...W,lastActiveAt:Date.now()};return this.saveSession(Y),Y}appendMessages($,W){let Z=this.loadSession($);if(!Z)return;return this.updateSession($,{messages:[...Z.messages,...W]})}markCompleted($,W,Z){return this.updateSession($,{status:W.success?"completed":"failed",result:W,stats:Z,completedAt:Date.now()})}deleteSession($){try{let W=this.getSessionPath($);if(Z$.existsSync(W))Z$.unlinkSync(W);return this.cache.delete($),!0}catch(W){return p$.warn(`Failed to delete session ${$}:`,W),!1}}listSessions(){try{let $=Z$.readdirSync(this.sessionsDir),W=[];for(let Z of $){if(!Z.endsWith(".json"))continue;let Y=Z.replace(".json",""),J=this.loadSession(Y);if(J)W.push(J)}return W.sort((Z,Y)=>Y.lastActiveAt-Z.lastActiveAt)}catch($){return p$.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let W=Date.now(),Z=this.listSessions(),Y=0;for(let J of Z){if(J.status==="running")continue;if(W-J.lastActiveAt>$){if(this.deleteSession(J.id))Y++}}if(Y>0)p$.info(`Cleaned up ${Y} expired agent sessions`);return Y}clearCache(){this.cache.clear()}}import{execFile as y7}from"node:child_process";import{createHash as P7,randomBytes as f7}from"node:crypto";import{mkdir as S7,readdir as I7,realpath as d0,stat as h7}from"node:fs/promises";import{Mutex as u7}from"async-mutex";var d5=64,p7=/^[a-zA-Z0-9._-]+$/,d7=/^agent\+[a-zA-Z0-9_-]{1,40}$/,g7=2592000000;function g5($){if(!$||$.length>d5)throw Error(`Worktree name must contain 1-${d5} characters`);for(let W of $.split("/"))if(W==="."||W===".."||!p7.test(W))throw Error(`Invalid worktree name "${$}": use letters, digits, dots, underscores, dashes, and optional "/" separators`)}function m5($,W=12){return P7("sha256").update($).digest("hex").slice(0,W)}function m7($){return $.replaceAll("/","+")}async function l($,W){return new Promise((Z)=>{y7("git",W,{cwd:$,encoding:"utf-8",maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""}},(Y,J,X)=>{Z({code:Y==null?0:typeof Y.code==="number"?Y.code:1,stdout:J||"",stderr:X||""})})})}function A0($,W){if($.code!==0)throw Error(`${W} failed: ${$.stderr.trim()||$.stdout.trim()||"unknown git error"}`);return $.stdout.trim()}class c5{storageRoot;sessions=new Map;sessionLocks=new Map;constructor($={}){this.storageRoot=$.storageRoot??V0()}getActiveSession($){return this.sessions.get($)}getManagedRoot($){let W=u0($),Z=`${uW(W)}-${m5(W)}`;return p0(this.storageRoot,"worktrees",Z)}async enter($){return this.getSessionLock($.sessionId).runExclusive(async()=>{if(this.sessions.has($.sessionId))throw Error("This session is already inside a managed worktree");let W=u0($.workspaceRoot),Z=await l(W,["rev-parse","--show-toplevel"]),[Y,J]=await Promise.all([d0(W),d0(A0(Z,"Resolve repository root"))]),X=hW(J,Y);if(X===".."||X.startsWith("../")||j$(X))throw Error("Workspace is outside the resolved git repository");let V=$.name??`session-${Date.now().toString(36)}-${f7(3).toString("hex")}`;g5(V);let[H,B,K]=await Promise.all([l(J,["rev-parse","HEAD"]),l(J,["branch","--show-current"]),l(J,["status","--porcelain"])]),Q=A0(H,"Resolve worktree base commit"),U=A0(B,"Resolve current branch");A0(K,"Inspect source worktree");let q=m7(V),w=`blade-worktree-${q}-${m5($.sessionId,8)}`,E=this.getManagedRoot(J),G=p0(E,q);await S7(E,{recursive:!0});let F=await l(J,["worktree","add","-b",w,G,Q]);A0(F,"Create worktree");let R={sessionId:$.sessionId,name:V,branch:w,baseCommit:Q,originalBranch:U,repositoryRoot:J,originalWorkspaceRoot:Y,worktreeRoot:G,workspaceRoot:X?p0(G,X):G,sourceHadChanges:K.stdout.trim().length>0};return this.sessions.set($.sessionId,R),R})}async restoreSession($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let W=this.sessions.get($.sessionId);if(W)return W;g5($.name);let[Z,Y,J]=await Promise.all([d0($.worktreeRoot),d0($.workspaceRoot),d0($.repositoryRoot)]),[X,V,H,B]=await Promise.all([l(Z,["rev-parse","--show-toplevel"]),l(Z,["branch","--show-current"]),l(Z,["cat-file","-e",`${$.baseCommit}^{commit}`]),l(J,["worktree","list","--porcelain"])]),K=await d0(A0(X,"Resolve restored worktree")),Q=A0(V,"Resolve restored branch");if(A0(H,"Resolve restored base commit"),A0(B,"List restored worktrees"),K!==Z||Q!==$.branch)throw Error("Persisted worktree metadata does not match Git state");if(!B.stdout.split(`
809
- `).filter((w)=>w.startsWith("worktree ")).map((w)=>w.slice(9)).includes(Z))throw Error("Persisted worktree is no longer registered");let q={...$,repositoryRoot:J,worktreeRoot:Z,workspaceRoot:Y};return this.sessions.set($.sessionId,q),q})}async getChangeSummary($){let W=this.sessions.get($);if(!W)return;return this.inspectChanges(W)}async cleanupStaleAgentWorktrees($){let W={scanned:0,removed:0,preserved:0,skipped:0,errors:[]},Z=$.maxAgeMs??g7;if(!Number.isFinite(Z)||Z<0)throw Error("maxAgeMs must be a finite non-negative number");let Y=await l(u0($.workspaceRoot),["rev-parse","--show-toplevel"]);if(Y.code!==0){let K=Y.stderr.trim()||Y.stdout.trim();if(!/not a git repository|not a git work tree/i.test(K))W.errors.push(`Resolve cleanup repository failed: ${K}`);return W}let J;try{J=await d0(Y.stdout.trim())}catch(K){return W.errors.push(`Resolve cleanup repository path failed: ${K instanceof Error?K.message:String(K)}`),W}let X=this.getManagedRoot(J),V;try{V=await I7(X,{withFileTypes:!0})}catch(K){if(K.code!=="ENOENT")W.errors.push(`Read managed worktrees failed: ${K instanceof Error?K.message:String(K)}`);return W}let H=new Set([...this.sessions.values()].map((K)=>u0(K.worktreeRoot))),B=($.now??Date.now())-Z;for(let K of V){if(!K.isDirectory()||!d7.test(K.name)){W.skipped++;continue}let Q=p0(X,K.name);if(W.scanned++,H.has(u0(Q))){W.skipped++;continue}let U;try{U=(await h7(Q)).mtimeMs}catch(N){W.errors.push(`Inspect stale worktree "${K.name}" failed: ${N instanceof Error?N.message:String(N)}`);continue}if(U>=B){W.skipped++;continue}let[q,w,E,G]=await Promise.all([l(Q,["rev-parse","--show-toplevel"]),l(Q,["branch","--show-current"]),l(Q,["--no-optional-locks","status","--porcelain"]),l(Q,["rev-list","--max-count=1","HEAD","--not","--remotes"])]);if(q.code!==0||w.code!==0||E.code!==0||G.code!==0){W.errors.push(`Git inspection failed for stale worktree "${K.name}"`);continue}let F=w.stdout.trim(),R,O;try{[R,O]=await Promise.all([d0(Q),d0(q.stdout.trim())])}catch(N){W.errors.push(`Canonical path inspection failed for "${K.name}": ${N instanceof Error?N.message:String(N)}`);continue}if(R!==O||!F.startsWith("blade-worktree-agent+")){W.errors.push(`Managed worktree identity mismatch for "${K.name}"`);continue}if(E.stdout.trim().length>0||G.stdout.trim().length>0){W.preserved++;continue}let _=await l(J,["worktree","remove","--force",Q]);if(_.code!==0){W.errors.push(`Remove stale worktree "${K.name}" failed: ${_.stderr.trim()||_.stdout.trim()}`);continue}W.removed++;let z=await l(J,["branch","-D",F]);if(z.code!==0)W.errors.push(`Delete stale branch "${F}" failed: ${z.stderr.trim()||z.stdout.trim()}`)}if(W.removed>0){let K=await l(J,["worktree","prune"]);if(K.code!==0)W.errors.push(`Prune stale worktree registrations failed: ${K.stderr.trim()||K.stdout.trim()}`)}return W}async exit($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let W=this.sessions.get($.sessionId);if(!W)return{action:$.action,workspaceRoot:$.workspaceRoot??"",removed:!1,noop:!0};if($.action==="keep")return this.sessions.delete($.sessionId),{action:"keep",workspaceRoot:W.originalWorkspaceRoot,worktreeRoot:W.worktreeRoot,branch:W.branch,removed:!1};let Z=await this.inspectChanges(W);if(!Z&&!$.discardChanges)throw Error("Could not verify worktree state. Refusing removal without discard_changes=true");let{changedFiles:Y,commits:J}=Z??{changedFiles:0,commits:0};if(!$.discardChanges&&(Y>0||J>0)){let B=[Y>0?`${Y} uncommitted ${Y===1?"file":"files"}`:"",J>0?`${J} unmerged ${J===1?"commit":"commits"}`:""].filter(Boolean);throw Error(`Worktree has ${B.join(" and ")}. Use action="keep" or confirm discard_changes=true`)}let X=["worktree","remove"];if($.discardChanges)X.push("--force");X.push(W.worktreeRoot);let V=await l(W.repositoryRoot,X);A0(V,"Remove worktree");let H=await l(W.repositoryRoot,["branch","-D",W.branch]);return this.sessions.delete($.sessionId),A0(H,"Delete worktree branch"),{action:"remove",workspaceRoot:W.originalWorkspaceRoot,worktreeRoot:W.worktreeRoot,branch:W.branch,removed:!0,discardedFiles:$.discardChanges?Y:void 0,discardedCommits:$.discardChanges?J:void 0}})}releaseSession($){this.sessions.delete($)}getSessionLock($){let W=this.sessionLocks.get($);if(!W)W=new u7,this.sessionLocks.set($,W);return W}async inspectChanges($){let[W,Z]=await Promise.all([l($.worktreeRoot,["status","--porcelain"]),l($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`])]);if(W.code!==0||Z.code!==0)return null;return{changedFiles:W.stdout.split(`
810
- `).filter((Y)=>Y.trim().length>0).length,commits:Number.parseInt(Z.stdout.trim(),10)||0}}}var N$=new c5;function c7($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class l5{manager;constructor($=N$){this.manager=$}async prepare($){let W=$.isolation??"none";if(W!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot};let Z=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:c7($.agentId)});return{isolation:W,workspaceRoot:Z.workspaceRoot,worktree:Z}}async finalize($){let{worktree:W}=$.lease;if(!W)return{preserved:!1,removed:!1};let Z=await this.manager.getChangeSummary($.agentId);if($.success&&this.isClean(Z))return await this.manager.exit({sessionId:$.agentId,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:$.agentId,action:"keep"}),{preserved:!0,removed:!1,worktreePath:W.worktreeRoot,worktreeBranch:W.branch,worktree:W,changedFiles:Z?.changedFiles,commits:Z?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var d$=new l5;var g0=P("Agent");class e{static instance=null;runningAgents=new Map;sessionStore=A$.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!e.instance)e.instance=new e;return e.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),W=Date.now(),Z=1800000;for(let Y of $)if(Y.status==="running"){let J=this.runningAgents.has(Y.id),X=W-Y.lastActiveAt;if(!J||X>1800000)g0.warn(`Cleaning up orphaned agent session: ${Y.id}`),this.sessionStore.updateSession(Y.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:W})}}startBackgroundAgent($){let{config:W,description:Z,prompt:Y,parentSessionId:J,permissionMode:X,agentId:V,existingMessages:H,taskListId:B,workspaceRoot:K=D(),isolation:Q=W.isolation??"none",restoredWorktree:U}=$,q=V||l7(),w=new AbortController,E={id:q,subagentType:W.name,description:Z,prompt:Y,messages:H||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:J,taskListId:B,workspaceRoot:K,isolation:Q,worktree:U};this.sessionStore.saveSession(E);let G=Date.now(),F=this.executeAgent(q,W,Y,J,X,w.signal,H,B,K,Q,U);return this.runningAgents.set(q,{id:q,promise:F,abortController:w,startTime:G}),F.finally(()=>{this.runningAgents.delete(q)}),g0.info(`Background agent started: ${q} (${W.name})`),q}async executeAgent($,W,Z,Y,J,X,V,H,B=D(),K="none",Q){let U=Date.now(),q,w,E=!1,G=async(F)=>{if(!w||E)return;let R=await d$.finalize({agentId:$,lease:w,success:F});return E=!0,this.sessionStore.updateSession($,{worktree:R.worktree}),R};try{if(X.aborted)throw Error("Agent execution was cancelled");w=await d$.prepare({agentId:$,sourceWorkspaceRoot:B,isolation:K,restoredWorktree:Q}),this.sessionStore.updateSession($,{worktree:w.worktree});let F=W.systemPrompt?.trim(),R=W.model&&W.model!=="inherit"?W.model:void 0,O=W.permissionMode??J;q=await e1.create({sessionId:$,workspaceRoot:w.workspaceRoot,modelId:R});let _=await B0.createWithRuntime(q,{sessionId:$,toolWhitelist:W.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...W.disallowedTools??[]],modelId:R,maxTurns:W.maxTurns,permissionMode:O,...F?{appendSystemPrompt:F}:{}}),z={messages:V||[],userId:"subagent",sessionId:$,taskListId:H,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),permissionMode:O,subagentInfo:{parentSessionId:Y||"",subagentType:W.name,isSidechain:!1}},N=new Set,A=await N0(_.chatStream(Z,z,{signal:X}),(x)=>{if(x.kind==="tool_result"&&"function"in x.toolCall)t1(N,x.toolCall.function.name,x.result)});this.sessionStore.updateSession($,{messages:z.messages});let k=Date.now()-U,M=A.success?{success:!0,message:A.finalMessage||"",agentId:$,verificationCommands:[...N],stats:{tokens:A.metadata?.tokensUsed||0,toolCalls:A.metadata?.toolCallsCount||0,duration:k}}:{success:!1,message:"",agentId:$,error:A.error?.message||"Unknown error",stats:{duration:k}},y=await G(M.success);if(y?.preserved)M.worktreePath=y.worktreePath,M.worktreeBranch=y.worktreeBranch,M.worktree=y.worktree;return this.sessionStore.markCompleted($,{success:M.success,message:M.message,error:M.error,verificationCommands:M.verificationCommands},M.stats),g0.info(`Background agent completed: ${$} (success=${M.success})`),M}catch(F){let R=Date.now()-U,O=F instanceof Error?F.message:String(F),_;try{_=await G(!1)}catch(z){g0.warn(`Failed to preserve worktree for background agent ${$}`,z)}return this.sessionStore.markCompleted($,{success:!1,message:"",error:O},{duration:R}),g0.warn(`Background agent failed: ${$}`,F),{success:!1,message:"",agentId:$,error:O,stats:{duration:R},worktreePath:_?.worktreePath,worktreeBranch:_?.worktreeBranch,worktree:_?.worktree}}finally{await q?.dispose()}}getAgent($,W){let Z=this.sessionStore.loadSession($);if(W!==void 0&&Z?.parentSessionId!==W)return;return Z}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,W=30000,Z){if(Z!==void 0&&!this.getAgent($,Z))return;let Y=this.runningAgents.get($);if(!Y)return this.getAgent($,Z);if(W>0){let J=new Promise((V)=>setTimeout(()=>V("timeout"),W));if(await Promise.race([Y.promise,J])==="timeout")return this.getAgent($,Z)}else await Y.promise;return this.getAgent($,Z)}resumeAgent($,W,Z,Y,J){let X=this.sessionStore.loadSession($);if(!X){g0.warn(`Cannot resume agent ${$}: session not found`);return}if(Y!==void 0&&X.parentSessionId!==Y){g0.warn(`Cannot resume agent ${$}: parent session mismatch`);return}if(this.isRunning($)){g0.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:Z,description:X.description,prompt:W,parentSessionId:Y||X.parentSessionId,permissionMode:J,agentId:$,existingMessages:X.messages,taskListId:X.taskListId,workspaceRoot:X.workspaceRoot,isolation:X.isolation,restoredWorktree:X.worktree})}killAgent($){let W=this.runningAgents.get($);if(!W){let Z=this.sessionStore.loadSession($);if(Z&&Z.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return W.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),g0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((W)=>W.parentSessionId===$)}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,W=604800000){let Z=Date.now(),Y=0;for(let J of this.listForSession($)){if(J.status==="running")continue;if(Z-J.lastActiveAt<=W)continue;if(this.sessionStore.deleteSession(J.id))Y++}return Y}}import{nanoid as i7}from"nanoid";class pW{config;constructor($){this.config=$}async execute($){let W=Date.now(),Z=$.subagentSessionId??i7();try{let Y=this.getAppendSystemPrompt(),J=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,X=this.config.permissionMode??$.permissionMode,V=await B0.create({toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:J,maxTurns:this.config.maxTurns,permissionMode:X,...Y?{appendSystemPrompt:Y}:{}}),H="",B=0,K=0,Q=new Set,U={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1},q=async(G)=>{if(G.kind==="tool_result"&&"function"in G.toolCall)t1(Q,G.toolCall.function.name,G.result);await $.onEvent?.(G)},w=await N0(V.chatStream($.prompt,{messages:[],userId:"subagent",sessionId:Z,workspaceRoot:$.workspaceRoot||D(),completionRequirements:Y,worktreeActive:$.worktreeActive,permissionMode:X,subagentInfo:U}),q);if(w.success)H=w.finalMessage||"",B=w.metadata?.toolCallsCount||0,K=w.metadata?.tokensUsed||0;else throw Error(w.error?.message||"Subagent execution failed");let E=Date.now()-W;return{success:!0,message:H,agentId:Z,verificationCommands:[...Q],stats:{tokens:K,toolCalls:B,duration:E}}}catch(Y){let J=Date.now()-W;return{success:!1,message:"",agentId:Z,error:Y instanceof Error?Y.message:String(Y),stats:{duration:J}}}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{EventEmitter as r7}from"events";class g$ extends r7{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!g$.instance)g$.instance=new g$;return g$.instance}publish($,W,Z){this.emit("event",{sessionId:$,type:W,properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var T$=g$.getInstance();import{basename as Y$}from"node:path";function dW($,W){switch($){case"Write":{let Z=W.file_path;return`Writing ${Z?Y$(Z):"file"}`}case"Edit":{let Z=W.file_path;return`Editing ${Z?Y$(Z):"file"}`}case"Read":{let Z=W.file_path;return`Reading ${Z?Y$(Z):"file"}`}case"Bash":{let{command:Z,description:Y}=W;if(Y)return`${Y}`;return`Running: ${Z?Z.substring(0,40):"command"}${Z&&Z.length>40?"...":""}`}case"Glob":return`Searching files: ${W.pattern}`;case"Grep":{let{pattern:Z,path:Y}=W,J=Z&&Z.length>30?Z.substring(0,30)+"...":Z;if(Y){let X=Y$(Y);return`Searching "${J}" in ${X}`}return`Searching "${J}"`}case"WebFetch":{let Z=W.url;if(Z)try{return`Fetching ${new URL(Z).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let Z=W.query;return`Searching: "${Z&&Z.length>40?Z.substring(0,40)+"...":Z}"`}case"TaskCreate":return`Creating task: ${W.subject||"task"}`;case"TaskGet":return`Reading task ${W.taskId||""}`.trim();case"TaskUpdate":{let{status:Z,taskId:Y}=W;return Z?`Updating task ${Y||""}: ${Z}`.trim():`Updating task ${Y||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let Z=W.file_path;return`Undoing changes to ${Z?Y$(Z):"file"}`}case"Skill":return`Invoking skill: ${W.skill}`;case"Task":{let{description:Z,subagent_type:Y}=W;if(Z)return`${Y||"Agent"}: ${Z}`;return`Running ${Y||"agent"}`}case"LSP":{let{operation:Z,filePath:Y}=W,J=Y?Y$(Y):"file";return`LSP ${Z} in ${J}`}case"NotebookEdit":{let Z=W.notebook_path;return`Editing notebook: ${Z?Y$(Z):"notebook"}`}default:return`${$}`}}function n7($,W){if(!W?.success&&!W?.metadata)return!1;switch($){case"Write":case"Edit":case"Read":case"Glob":case"Grep":case"Bash":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!W.metadata?.detail}}function a7($,W){if(!W?.success)return null;switch($){case"Glob":{if(!i5(W.metadata))return null;let{matches:Z}=W.metadata;if(!Z?.length)return null;let Y=5,J=Z.slice(0,Y).map((X)=>X.relative_path);if(Z.length>Y)J.push(`... (+${Z.length-Y} more)`);return J.join(`
808
+ `);return J}}import Z$ from"node:fs";var b7=/^[A-Za-z]:\//;function SW($=""){if(!$)return $;return $.replace(/\\/g,"/").replace(b7,(W)=>W.toUpperCase())}var M7=/^[/\\]{2}/,v7=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/,x7=/^[A-Za-z]:$/,u5=/^\/([A-Za-z]:)?$/;var p5=function($){if($.length===0)return".";$=SW($);let W=$.match(M7),Z=j$($),Y=$[$.length-1]==="/";if($=IW($,!Z),$.length===0){if(Z)return"/";return Y?"./":"."}if(Y)$+="/";if(x7.test($))$+="/";if(W){if(!Z)return`//./${$}`;return`//${$}`}return Z&&!j$($)?`/${$}`:$},p0=function(...$){let W="";for(let Z of $){if(!Z)continue;if(W.length>0){let Y=W[W.length-1]==="/",J=Z[0]==="/";if(Y&&J)W+=Z.slice(1);else W+=Y||J?Z:`/${Z}`}else W+=Z}return p5(W)};function C7(){if(typeof process<"u"&&typeof process.cwd==="function")return process.cwd().replace(/\\/g,"/");return"/"}var u0=function(...$){$=$.map((Y)=>SW(Y));let W="",Z=!1;for(let Y=$.length-1;Y>=-1&&!Z;Y--){let J=Y>=0?$[Y]:C7();if(!J||J.length===0)continue;W=`${J}/${W}`,Z=j$(J)}if(W=IW(W,!Z),Z&&!j$(W))return`/${W}`;return W.length>0?W:"."};function IW($,W){let Z="",Y=0,J=-1,X=0,V=null;for(let H=0;H<=$.length;++H){if(H<$.length)V=$[H];else if(V==="/")break;else V="/";if(V==="/"){if(J===H-1||X===1);else if(X===2){if(Z.length<2||Y!==2||Z[Z.length-1]!=="."||Z[Z.length-2]!=="."){if(Z.length>2){let K=Z.lastIndexOf("/");if(K===-1)Z="",Y=0;else Z=Z.slice(0,K),Y=Z.length-1-Z.lastIndexOf("/");J=H,X=0;continue}else if(Z.length>0){Z="",Y=0,J=H,X=0;continue}}if(W)Z+=Z.length>0?"/..":"..",Y=2}else{if(Z.length>0)Z+=`/${$.slice(J+1,H)}`;else Z=$.slice(J+1,H);Y=H-J-1}J=H,X=0}else if(V==="."&&X!==-1)++X;else X=-1}return Z}var j$=function($){return v7.test($)};var hW=function($,W){let Z=u0($).replace(u5,"$1").split("/"),Y=u0(W).replace(u5,"$1").split("/");if(Y[0][1]===":"&&Z[0][1]===":"&&Z[0]!==Y[0])return Y.join("/");let J=[...Z];for(let X of J){if(Y[0]!==X)break;Z.shift(),Y.shift()}return[...Z.map(()=>".."),...Y].join("/")};var uW=function($,W){let Z=SW($).split("/"),Y="";for(let J=Z.length-1;J>=0;J--){let X=Z[J];if(X){Y=X;break}}return W&&Y.endsWith(W)?Y.slice(0,-W.length):Y};var p$=f("Agent");class A${static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=p0(V0(),"agents","sessions"),this.ensureDirectory()}static getInstance(){if(!A$.instance)A$.instance=new A$;return A$.instance}ensureDirectory(){if(!Z$.existsSync(this.sessionsDir))Z$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let W=$.replace(/[^a-zA-Z0-9_-]/g,"_");return p0(this.sessionsDir,`${W}.json`)}saveSession($){try{let W=this.getSessionPath($.id),Z=JSON.stringify($,null,2);Z$.writeFileSync(W,Z,"utf-8"),this.cache.set($.id,$),p$.debug(`Session saved: ${$.id}`)}catch(W){p$.warn(`Failed to save session ${$.id}:`,W)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let W=this.getSessionPath($);if(!Z$.existsSync(W))return;let Z=Z$.readFileSync(W,"utf-8"),Y=JSON.parse(Z);return this.cache.set($,Y),Y}catch(W){p$.warn(`Failed to load session ${$}:`,W);return}}updateSession($,W){let Z=this.loadSession($);if(!Z)return;let Y={...Z,...W,lastActiveAt:Date.now()};return this.saveSession(Y),Y}appendMessages($,W){let Z=this.loadSession($);if(!Z)return;return this.updateSession($,{messages:[...Z.messages,...W]})}markCompleted($,W,Z){return this.updateSession($,{status:W.success?"completed":"failed",result:W,stats:Z,completedAt:Date.now()})}deleteSession($){try{let W=this.getSessionPath($);if(Z$.existsSync(W))Z$.unlinkSync(W);return this.cache.delete($),!0}catch(W){return p$.warn(`Failed to delete session ${$}:`,W),!1}}listSessions(){try{let $=Z$.readdirSync(this.sessionsDir),W=[];for(let Z of $){if(!Z.endsWith(".json"))continue;let Y=Z.replace(".json",""),J=this.loadSession(Y);if(J)W.push(J)}return W.sort((Z,Y)=>Y.lastActiveAt-Z.lastActiveAt)}catch($){return p$.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let W=Date.now(),Z=this.listSessions(),Y=0;for(let J of Z){if(J.status==="running")continue;if(W-J.lastActiveAt>$){if(this.deleteSession(J.id))Y++}}if(Y>0)p$.info(`Cleaned up ${Y} expired agent sessions`);return Y}clearCache(){this.cache.clear()}}import{execFile as y7}from"node:child_process";import{createHash as f7,randomBytes as P7}from"node:crypto";import{mkdir as S7,readdir as I7,realpath as d0,stat as h7}from"node:fs/promises";import{Mutex as u7}from"async-mutex";var d5=64,p7=/^[a-zA-Z0-9._-]+$/,d7=/^agent\+[a-zA-Z0-9_-]{1,40}$/,g7=2592000000;function g5($){if(!$||$.length>d5)throw Error(`Worktree name must contain 1-${d5} characters`);for(let W of $.split("/"))if(W==="."||W===".."||!p7.test(W))throw Error(`Invalid worktree name "${$}": use letters, digits, dots, underscores, dashes, and optional "/" separators`)}function m5($,W=12){return f7("sha256").update($).digest("hex").slice(0,W)}function m7($){return $.replaceAll("/","+")}async function l($,W){return new Promise((Z)=>{y7("git",W,{cwd:$,encoding:"utf-8",maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""}},(Y,J,X)=>{Z({code:Y==null?0:typeof Y.code==="number"?Y.code:1,stdout:J||"",stderr:X||""})})})}function A0($,W){if($.code!==0)throw Error(`${W} failed: ${$.stderr.trim()||$.stdout.trim()||"unknown git error"}`);return $.stdout.trim()}class c5{storageRoot;sessions=new Map;sessionLocks=new Map;constructor($={}){this.storageRoot=$.storageRoot??V0()}getActiveSession($){return this.sessions.get($)}getManagedRoot($){let W=u0($),Z=`${uW(W)}-${m5(W)}`;return p0(this.storageRoot,"worktrees",Z)}async enter($){return this.getSessionLock($.sessionId).runExclusive(async()=>{if(this.sessions.has($.sessionId))throw Error("This session is already inside a managed worktree");let W=u0($.workspaceRoot),Z=await l(W,["rev-parse","--show-toplevel"]),[Y,J]=await Promise.all([d0(W),d0(A0(Z,"Resolve repository root"))]),X=hW(J,Y);if(X===".."||X.startsWith("../")||j$(X))throw Error("Workspace is outside the resolved git repository");let V=$.name??`session-${Date.now().toString(36)}-${P7(3).toString("hex")}`;g5(V);let[H,K,B]=await Promise.all([l(J,["rev-parse","HEAD"]),l(J,["branch","--show-current"]),l(J,["status","--porcelain"])]),U=A0(H,"Resolve worktree base commit"),Q=A0(K,"Resolve current branch");A0(B,"Inspect source worktree");let q=m7(V),w=`blade-worktree-${q}-${m5($.sessionId,8)}`,E=this.getManagedRoot(J),G=p0(E,q);await S7(E,{recursive:!0});let F=await l(J,["worktree","add","-b",w,G,U]);A0(F,"Create worktree");let z={sessionId:$.sessionId,name:V,branch:w,baseCommit:U,originalBranch:Q,repositoryRoot:J,originalWorkspaceRoot:Y,worktreeRoot:G,workspaceRoot:X?p0(G,X):G,sourceHadChanges:B.stdout.trim().length>0};return this.sessions.set($.sessionId,z),z})}async restoreSession($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let W=this.sessions.get($.sessionId);if(W)return W;g5($.name);let[Z,Y,J]=await Promise.all([d0($.worktreeRoot),d0($.workspaceRoot),d0($.repositoryRoot)]),[X,V,H,K]=await Promise.all([l(Z,["rev-parse","--show-toplevel"]),l(Z,["branch","--show-current"]),l(Z,["cat-file","-e",`${$.baseCommit}^{commit}`]),l(J,["worktree","list","--porcelain"])]),B=await d0(A0(X,"Resolve restored worktree")),U=A0(V,"Resolve restored branch");if(A0(H,"Resolve restored base commit"),A0(K,"List restored worktrees"),B!==Z||U!==$.branch)throw Error("Persisted worktree metadata does not match Git state");if(!K.stdout.split(`
809
+ `).filter((w)=>w.startsWith("worktree ")).map((w)=>w.slice(9)).includes(Z))throw Error("Persisted worktree is no longer registered");let q={...$,repositoryRoot:J,worktreeRoot:Z,workspaceRoot:Y};return this.sessions.set($.sessionId,q),q})}async getChangeSummary($){let W=this.sessions.get($);if(!W)return;return this.inspectChanges(W)}async cleanupStaleAgentWorktrees($){let W={scanned:0,removed:0,preserved:0,skipped:0,errors:[]},Z=$.maxAgeMs??g7;if(!Number.isFinite(Z)||Z<0)throw Error("maxAgeMs must be a finite non-negative number");let Y=await l(u0($.workspaceRoot),["rev-parse","--show-toplevel"]);if(Y.code!==0){let B=Y.stderr.trim()||Y.stdout.trim();if(!/not a git repository|not a git work tree/i.test(B))W.errors.push(`Resolve cleanup repository failed: ${B}`);return W}let J;try{J=await d0(Y.stdout.trim())}catch(B){return W.errors.push(`Resolve cleanup repository path failed: ${B instanceof Error?B.message:String(B)}`),W}let X=this.getManagedRoot(J),V;try{V=await I7(X,{withFileTypes:!0})}catch(B){if(B.code!=="ENOENT")W.errors.push(`Read managed worktrees failed: ${B instanceof Error?B.message:String(B)}`);return W}let H=new Set([...this.sessions.values()].map((B)=>u0(B.worktreeRoot))),K=($.now??Date.now())-Z;for(let B of V){if(!B.isDirectory()||!d7.test(B.name)){W.skipped++;continue}let U=p0(X,B.name);if(W.scanned++,H.has(u0(U))){W.skipped++;continue}let Q;try{Q=(await h7(U)).mtimeMs}catch(j){W.errors.push(`Inspect stale worktree "${B.name}" failed: ${j instanceof Error?j.message:String(j)}`);continue}if(Q>=K){W.skipped++;continue}let[q,w,E,G]=await Promise.all([l(U,["rev-parse","--show-toplevel"]),l(U,["branch","--show-current"]),l(U,["--no-optional-locks","status","--porcelain"]),l(U,["rev-list","--max-count=1","HEAD","--not","--remotes"])]);if(q.code!==0||w.code!==0||E.code!==0||G.code!==0){W.errors.push(`Git inspection failed for stale worktree "${B.name}"`);continue}let F=w.stdout.trim(),z,O;try{[z,O]=await Promise.all([d0(U),d0(q.stdout.trim())])}catch(j){W.errors.push(`Canonical path inspection failed for "${B.name}": ${j instanceof Error?j.message:String(j)}`);continue}if(z!==O||!F.startsWith("blade-worktree-agent+")){W.errors.push(`Managed worktree identity mismatch for "${B.name}"`);continue}if(E.stdout.trim().length>0||G.stdout.trim().length>0){W.preserved++;continue}let _=await l(J,["worktree","remove","--force",U]);if(_.code!==0){W.errors.push(`Remove stale worktree "${B.name}" failed: ${_.stderr.trim()||_.stdout.trim()}`);continue}W.removed++;let R=await l(J,["branch","-D",F]);if(R.code!==0)W.errors.push(`Delete stale branch "${F}" failed: ${R.stderr.trim()||R.stdout.trim()}`)}if(W.removed>0){let B=await l(J,["worktree","prune"]);if(B.code!==0)W.errors.push(`Prune stale worktree registrations failed: ${B.stderr.trim()||B.stdout.trim()}`)}return W}async exit($){return this.getSessionLock($.sessionId).runExclusive(async()=>{let W=this.sessions.get($.sessionId);if(!W)return{action:$.action,workspaceRoot:$.workspaceRoot??"",removed:!1,noop:!0};if($.action==="keep")return this.sessions.delete($.sessionId),{action:"keep",workspaceRoot:W.originalWorkspaceRoot,worktreeRoot:W.worktreeRoot,branch:W.branch,removed:!1};let Z=await this.inspectChanges(W);if(!Z&&!$.discardChanges)throw Error("Could not verify worktree state. Refusing removal without discard_changes=true");let{changedFiles:Y,commits:J}=Z??{changedFiles:0,commits:0};if(!$.discardChanges&&(Y>0||J>0)){let K=[Y>0?`${Y} uncommitted ${Y===1?"file":"files"}`:"",J>0?`${J} unmerged ${J===1?"commit":"commits"}`:""].filter(Boolean);throw Error(`Worktree has ${K.join(" and ")}. Use action="keep" or confirm discard_changes=true`)}let X=["worktree","remove"];if($.discardChanges)X.push("--force");X.push(W.worktreeRoot);let V=await l(W.repositoryRoot,X);A0(V,"Remove worktree");let H=await l(W.repositoryRoot,["branch","-D",W.branch]);return this.sessions.delete($.sessionId),A0(H,"Delete worktree branch"),{action:"remove",workspaceRoot:W.originalWorkspaceRoot,worktreeRoot:W.worktreeRoot,branch:W.branch,removed:!0,discardedFiles:$.discardChanges?Y:void 0,discardedCommits:$.discardChanges?J:void 0}})}releaseSession($){this.sessions.delete($)}getSessionLock($){let W=this.sessionLocks.get($);if(!W)W=new u7,this.sessionLocks.set($,W);return W}async inspectChanges($){let[W,Z]=await Promise.all([l($.worktreeRoot,["status","--porcelain"]),l($.worktreeRoot,["rev-list","--count",`${$.baseCommit}..HEAD`])]);if(W.code!==0||Z.code!==0)return null;return{changedFiles:W.stdout.split(`
810
+ `).filter((Y)=>Y.trim().length>0).length,commits:Number.parseInt(Z.stdout.trim(),10)||0}}}var N$=new c5;function c7($){return`agent/${$.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)||"anonymous"}`}class l5{manager;constructor($=N$){this.manager=$}async prepare($){let W=$.isolation??"none";if(W!=="worktree")return{isolation:"none",workspaceRoot:$.sourceWorkspaceRoot};let Z=$.restoredWorktree?await this.manager.restoreSession($.restoredWorktree):await this.manager.enter({sessionId:$.agentId,workspaceRoot:$.sourceWorkspaceRoot,name:c7($.agentId)});return{isolation:W,workspaceRoot:Z.workspaceRoot,worktree:Z}}async finalize($){let{worktree:W}=$.lease;if(!W)return{preserved:!1,removed:!1};let Z=await this.manager.getChangeSummary($.agentId);if($.success&&this.isClean(Z))return await this.manager.exit({sessionId:$.agentId,action:"remove"}),{preserved:!1,removed:!0,changedFiles:0,commits:0};return await this.manager.exit({sessionId:$.agentId,action:"keep"}),{preserved:!0,removed:!1,worktreePath:W.worktreeRoot,worktreeBranch:W.branch,worktree:W,changedFiles:Z?.changedFiles,commits:Z?.commits}}isClean($){return $!==null&&$!==void 0&&$.changedFiles===0&&$.commits===0}}var d$=new l5;var g0=f("Agent");class e{static instance=null;runningAgents=new Map;sessionStore=A$.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!e.instance)e.instance=new e;return e.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),W=Date.now(),Z=1800000;for(let Y of $)if(Y.status==="running"){let J=this.runningAgents.has(Y.id),X=W-Y.lastActiveAt;if(!J||X>1800000)g0.warn(`Cleaning up orphaned agent session: ${Y.id}`),this.sessionStore.updateSession(Y.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:W})}}startBackgroundAgent($){let{config:W,description:Z,prompt:Y,parentSessionId:J,permissionMode:X,agentId:V,existingMessages:H,taskListId:K,workspaceRoot:B=D(),isolation:U=W.isolation??"none",restoredWorktree:Q}=$,q=V||l7(),w=new AbortController,E={id:q,subagentType:W.name,description:Z,prompt:Y,messages:H||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:J,taskListId:K,workspaceRoot:B,isolation:U,worktree:Q};this.sessionStore.saveSession(E);let G=Date.now(),F=this.executeAgent(q,W,Y,J,X,w.signal,H,K,B,U,Q);return this.runningAgents.set(q,{id:q,promise:F,abortController:w,startTime:G}),F.finally(()=>{this.runningAgents.delete(q)}),g0.info(`Background agent started: ${q} (${W.name})`),q}async executeAgent($,W,Z,Y,J,X,V,H,K=D(),B="none",U){let Q=Date.now(),q,w,E=!1,G=async(F)=>{if(!w||E)return;let z=await d$.finalize({agentId:$,lease:w,success:F});return E=!0,this.sessionStore.updateSession($,{worktree:z.worktree}),z};try{if(X.aborted)throw Error("Agent execution was cancelled");w=await d$.prepare({agentId:$,sourceWorkspaceRoot:K,isolation:B,restoredWorktree:U}),this.sessionStore.updateSession($,{worktree:w.worktree});let F=W.systemPrompt?.trim(),z=W.model&&W.model!=="inherit"?W.model:void 0,O=W.permissionMode??J;q=await e1.create({sessionId:$,workspaceRoot:w.workspaceRoot,modelId:z});let _=await B0.createWithRuntime(q,{sessionId:$,toolWhitelist:W.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...W.disallowedTools??[]],modelId:z,maxTurns:W.maxTurns,permissionMode:O,...F?{appendSystemPrompt:F}:{}}),R={messages:V||[],userId:"subagent",sessionId:$,taskListId:H,workspaceRoot:w.workspaceRoot,worktreeActive:Boolean(w.worktree),permissionMode:O,subagentInfo:{parentSessionId:Y||"",subagentType:W.name,isSidechain:!1}},j=new Set,A=await N0(_.chatStream(Z,R,{signal:X}),(x)=>{if(x.kind==="tool_result"&&"function"in x.toolCall)t1(j,x.toolCall.function.name,x.result)});this.sessionStore.updateSession($,{messages:R.messages});let L=Date.now()-Q,b=A.success?{success:!0,message:A.finalMessage||"",agentId:$,verificationCommands:[...j],stats:{tokens:A.metadata?.tokensUsed||0,toolCalls:A.metadata?.toolCallsCount||0,duration:L}}:{success:!1,message:"",agentId:$,error:A.error?.message||"Unknown error",stats:{duration:L}},y=await G(b.success);if(y?.preserved)b.worktreePath=y.worktreePath,b.worktreeBranch=y.worktreeBranch,b.worktree=y.worktree;return this.sessionStore.markCompleted($,{success:b.success,message:b.message,error:b.error,verificationCommands:b.verificationCommands},b.stats),g0.info(`Background agent completed: ${$} (success=${b.success})`),b}catch(F){let z=Date.now()-Q,O=F instanceof Error?F.message:String(F),_;try{_=await G(!1)}catch(R){g0.warn(`Failed to preserve worktree for background agent ${$}`,R)}return this.sessionStore.markCompleted($,{success:!1,message:"",error:O},{duration:z}),g0.warn(`Background agent failed: ${$}`,F),{success:!1,message:"",agentId:$,error:O,stats:{duration:z},worktreePath:_?.worktreePath,worktreeBranch:_?.worktreeBranch,worktree:_?.worktree}}finally{await q?.dispose()}}getAgent($,W){let Z=this.sessionStore.loadSession($);if(W!==void 0&&Z?.parentSessionId!==W)return;return Z}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,W=30000,Z){if(Z!==void 0&&!this.getAgent($,Z))return;let Y=this.runningAgents.get($);if(!Y)return this.getAgent($,Z);if(W>0){let J=new Promise((V)=>setTimeout(()=>V("timeout"),W));if(await Promise.race([Y.promise,J])==="timeout")return this.getAgent($,Z)}else await Y.promise;return this.getAgent($,Z)}resumeAgent($,W,Z,Y,J){let X=this.sessionStore.loadSession($);if(!X){g0.warn(`Cannot resume agent ${$}: session not found`);return}if(Y!==void 0&&X.parentSessionId!==Y){g0.warn(`Cannot resume agent ${$}: parent session mismatch`);return}if(this.isRunning($)){g0.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:Z,description:X.description,prompt:W,parentSessionId:Y||X.parentSessionId,permissionMode:J,agentId:$,existingMessages:X.messages,taskListId:X.taskListId,workspaceRoot:X.workspaceRoot,isolation:X.isolation,restoredWorktree:X.worktree})}killAgent($){let W=this.runningAgents.get($);if(!W){let Z=this.sessionStore.loadSession($);if(Z&&Z.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return W.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),g0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listForSession($){return this.sessionStore.listSessions().filter((W)=>W.parentSessionId===$)}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}cleanupExpiredSessionsForParent($,W=604800000){let Z=Date.now(),Y=0;for(let J of this.listForSession($)){if(J.status==="running")continue;if(Z-J.lastActiveAt<=W)continue;if(this.sessionStore.deleteSession(J.id))Y++}return Y}}import{nanoid as i7}from"nanoid";class pW{config;constructor($){this.config=$}async execute($){let W=Date.now(),Z=$.subagentSessionId??i7();try{let Y=this.getAppendSystemPrompt(),J=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,X=this.config.permissionMode??$.permissionMode,V=await B0.create({toolWhitelist:this.config.tools,toolBlacklist:["EnterWorktree","ExitWorktree",...this.config.disallowedTools??[]],modelId:J,maxTurns:this.config.maxTurns,permissionMode:X,...Y?{appendSystemPrompt:Y}:{}}),H="",K=0,B=0,U=new Set,Q={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1},q=async(G)=>{if(G.kind==="tool_result"&&"function"in G.toolCall)t1(U,G.toolCall.function.name,G.result);await $.onEvent?.(G)},w=await N0(V.chatStream($.prompt,{messages:[],userId:"subagent",sessionId:Z,workspaceRoot:$.workspaceRoot||D(),completionRequirements:Y,worktreeActive:$.worktreeActive,permissionMode:X,subagentInfo:Q}),q);if(w.success)H=w.finalMessage||"",K=w.metadata?.toolCallsCount||0,B=w.metadata?.tokensUsed||0;else throw Error(w.error?.message||"Subagent execution failed");let E=Date.now()-W;return{success:!0,message:H,agentId:Z,verificationCommands:[...U],stats:{tokens:B,toolCalls:K,duration:E}}}catch(Y){let J=Date.now()-W;return{success:!1,message:"",agentId:Z,error:Y instanceof Error?Y.message:String(Y),stats:{duration:J}}}}getAppendSystemPrompt(){return this.config.systemPrompt?.trim()||void 0}}import{EventEmitter as r7}from"events";class g$ extends r7{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!g$.instance)g$.instance=new g$;return g$.instance}publish($,W,Z){this.emit("event",{sessionId:$,type:W,properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var T$=g$.getInstance();import{basename as Y$}from"node:path";function dW($,W){switch($){case"Write":{let Z=W.file_path;return`Writing ${Z?Y$(Z):"file"}`}case"Edit":{let Z=W.file_path;return`Editing ${Z?Y$(Z):"file"}`}case"Read":{let Z=W.file_path;return`Reading ${Z?Y$(Z):"file"}`}case"Bash":{let{command:Z,description:Y}=W;if(Y)return`${Y}`;return`Running: ${Z?Z.substring(0,40):"command"}${Z&&Z.length>40?"...":""}`}case"Glob":return`Searching files: ${W.pattern}`;case"Grep":{let{pattern:Z,path:Y}=W,J=Z&&Z.length>30?Z.substring(0,30)+"...":Z;if(Y){let X=Y$(Y);return`Searching "${J}" in ${X}`}return`Searching "${J}"`}case"WebFetch":{let Z=W.url;if(Z)try{return`Fetching ${new URL(Z).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let Z=W.query;return`Searching: "${Z&&Z.length>40?Z.substring(0,40)+"...":Z}"`}case"TaskCreate":return`Creating task: ${W.subject||"task"}`;case"TaskGet":return`Reading task ${W.taskId||""}`.trim();case"TaskUpdate":{let{status:Z,taskId:Y}=W;return Z?`Updating task ${Y||""}: ${Z}`.trim():`Updating task ${Y||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let Z=W.file_path;return`Undoing changes to ${Z?Y$(Z):"file"}`}case"Skill":return`Invoking skill: ${W.skill}`;case"Task":{let{description:Z,subagent_type:Y}=W;if(Z)return`${Y||"Agent"}: ${Z}`;return`Running ${Y||"agent"}`}case"LSP":{let{operation:Z,filePath:Y}=W,J=Y?Y$(Y):"file";return`LSP ${Z} in ${J}`}case"NotebookEdit":{let Z=W.notebook_path;return`Editing notebook: ${Z?Y$(Z):"notebook"}`}default:return`${$}`}}function n7($,W){if(!W?.success&&!W?.metadata)return!1;switch($){case"Write":case"Edit":case"Read":case"Glob":case"Grep":case"Bash":return!0;case"WebFetch":case"WebSearch":return!0;case"TaskCreate":case"TaskGet":case"TaskUpdate":case"TaskList":return!1;default:return!!W.metadata?.detail}}function a7($,W){if(!W?.success)return null;switch($){case"Glob":{if(!i5(W.metadata))return null;let{matches:Z}=W.metadata;if(!Z?.length)return null;let Y=5,J=Z.slice(0,Y).map((X)=>X.relative_path);if(Z.length>Y)J.push(`... (+${Z.length-Y} more)`);return J.join(`
811
811
  `)}case"Grep":{let Z=W.llmContent;if(!Array.isArray(Z)||!Z.length)return null;let Y=5,J=Z.slice(0,Y).map((X)=>{let V=Y$(X.file_path);if(X.line_number)return`${V}:${X.line_number}`;return V});if(Z.length>Y)J.push(`... (+${Z.length-Y} more)`);return J.join(`
812
812
  `)}case"Read":{let Z=W.metadata?.content_preview||W.llmContent;if(typeof Z!=="string"||!Z)return null;let Y=Z.split(`
813
813
  `),J=Y.length,X=3;if(J<=X+1)return Z;return`${Y.slice(0,X).join(`
@@ -829,14 +829,14 @@ Warning: Some files could not be loaded:
829
829
  ... (+${Y.length-5} more)`;return Z||null}if(Array.isArray(Z)&&Z.length>0){let J=Z.slice(0,5).map((X)=>X.title||X.url||"");if(Z.length>5)J.push(`... (+${Z.length-5} more)`);return J.join(`
830
830
  `)}return null}case"Task":{let Z=W.metadata?.subagentSummary||(typeof W.llmContent==="string"?W.llmContent:null);if(!Z)return null;return Z.length>200?`${Z.slice(0,200)}...`:Z}case"TaskOutput":{let Z=typeof W.llmContent==="string"?W.llmContent:null;if(!Z)return null;return Z.length>200?`${Z.slice(0,200)}...`:Z}case"Skill":{let Z=W.metadata?.skillName;return Z?`Skill: ${Z}`:null}default:{let Z=W.metadata?.detail;return typeof Z==="string"?Z:null}}}function n5($,W){let Z=W.success?"ok":W.error?"fail":"warn",Y=W.metadata?.summary||(W.success?"执行成功":"执行失败"),J=n7($,W)?a7($,W)||void 0:void 0;return{status:Z,summary:Y,detail:J}}function a5($){let W={ok:"[OK]",fail:"[FAIL]",warn:"[WARN]"}[$.status];return $.detail?`${W} ${$.summary}
831
831
  ${$.detail}`:`${W} ${$.summary}`}function o7($){let W=$.message||"Unknown error";if(W.includes("Too Many Requests")||W.includes("429")){let Z=$.cause;if(Z?.responseBody)try{let Y=JSON.parse(Z.responseBody);if(Y.message)return Y.message}catch{}return"API 请求过于频繁,请稍后重试"}if(W.includes("ECONNREFUSED")||W.includes("ETIMEDOUT"))return"网络连接失败,请检查网络设置";if(W.includes("401")||W.includes("Unauthorized"))return"API 认证失败,请检查 API Key 配置";return W.split(`
832
- `)[0]}function s7($){return f.getAllNames().includes($)}function t7(){let $=f.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function e7(){return`
832
+ `)[0]}function s7($){return P.getAllNames().includes($)}function t7(){let $=P.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function e7(){return`
833
833
  ## Task
834
834
 
835
835
  Launch a new agent to handle complex, multi-step tasks autonomously.
836
836
 
837
837
  The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
838
838
 
839
- ${f.getDescriptionsForPrompt()}
839
+ ${P.getDescriptionsForPrompt()}
840
840
 
841
841
  When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
842
842
 
@@ -861,9 +861,9 @@ Usage notes:
861
861
  - 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
862
862
  - 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.
863
863
  - 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.
864
- `.trim()}var gW=j({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:J$.object({subagent_type:J$.string().refine(s7,($)=>({message:`Invalid subagent type: "${$}". Available: ${t7()}`})).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:J$.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:J$.string().min(10).describe("Detailed task instructions"),run_in_background:J$.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),isolation:J$.enum(["none","worktree"]).optional().describe('Filesystem isolation for this child. Use "worktree" to prevent edits from affecting the parent workspace.'),resume:J$.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript."),subagent_session_id:J$.string().optional().describe("Internal subagent session id for tracking")}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return e7()},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($,W){let{subagent_type:Z,description:Y,prompt:J,run_in_background:X=!1,isolation:V,resume:H,subagent_session_id:B}=$,{updateOutput:K}=W,Q=W.sessionId,U=typeof B==="string"&&B.length>0?B:typeof H==="string"&&H.length>0?H:o5(),q,w=!1,E=V??"none",G=async(F)=>{if(!q||w)return;let R=await d$.finalize({agentId:U,lease:q,success:F});return w=!0,R};try{let F=f.getAllNames(),R=f.getSubagent(Z);if(!R)return{success:!1,llmContent:`Unknown subagent type: ${Z}. Available types: ${F.join(", ")||"none"}`,error:{type:"execution_error",message:`Unknown subagent type: ${Z}`},metadata:{summary:`未知的 subagent 类型: ${Z}`}};if(E=V??R.isolation??"none",H)return W3(H,J,R,Y,W);if(X)return $3(R,Y,J,W,U,E);K?.(`启动 ${Z} subagent: ${Y}`),q=await d$.prepare({agentId:U,sourceWorkspaceRoot:W.workspaceRoot||D(),isolation:E});let O=new pW(R),_=o5(8);Q1.getState().app.actions.startSubagentProgress(_,Z,Y);let z={prompt:J,parentSessionId:W.sessionId,permissionMode:W.permissionMode,subagentSessionId:U,workspaceRoot:q.workspaceRoot,worktreeActive:Boolean(q.worktree),onEvent:(y)=>{switch(y.kind){case"tool_start":{let x=y.toolCall,g="function"in x?x.function.name:"Unknown";if(Q1.getState().app.actions.updateSubagentTool(g),Q){if(T$.publish(Q,"subagent.update",{subagentSessionId:U,toolName:g}),"function"in x)T$.publish(Q,"subagent.tool.start",{subagentSessionId:U,toolCallId:x.id,toolName:g,arguments:x.function.arguments,toolKind:y.toolKind})}break}case"tool_result":{if(!Q)break;let x=y.toolCall;if(!("function"in x))break;T$.publish(Q,"subagent.tool.result",{subagentSessionId:U,toolCallId:x.id,toolName:x.function.name,success:!y.result.error,summary:y.result.metadata?.summary,output:a5(n5(x.function.name,y.result)),metadata:y.result.metadata});break}case"content_delta":{if(Q)T$.publish(Q,"subagent.delta",{subagentSessionId:U,delta:y.delta});break}case"thinking_delta":{if(Q)T$.publish(Q,"subagent.thinking.delta",{subagentSessionId:U,delta:y.delta});break}case"stream_end":{if(Q)T$.publish(Q,"subagent.stream.end",{subagentSessionId:U});break}default:break}}};K?.("执行任务中...");let N=Date.now(),A=await O.execute(z),k=Date.now()-N;try{let x=await w0.getInstance().executeSubagentStopHooks(Z,{projectDir:q.workspaceRoot,sessionId:W.sessionId||"unknown",permissionMode:W.permissionMode||"default",taskDescription:Y,success:A.success,resultSummary:A.message.slice(0,500),error:A.error});if(!x.shouldStop&&x.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${x.continueReason}`);let g={...z,prompt:x.continueReason},c0=Date.now();A=await O.execute(g),k+=Date.now()-c0}if(x.warning)console.warn(`[Task] SubagentStop hook warning: ${x.warning}`)}catch(y){console.warn("[Task] SubagentStop hook execution failed:",y)}let M=await G(A.success);if(M?.preserved)A.worktreePath=M.worktreePath,A.worktreeBranch=M.worktreeBranch,A.worktree=M.worktree;if(Q1.getState().app.actions.completeSubagentProgress(A.success),A.success){let y=A.worktreePath?`
864
+ `.trim()}var gW=N({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:J$.object({subagent_type:J$.string().refine(s7,($)=>({message:`Invalid subagent type: "${$}". Available: ${t7()}`})).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:J$.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:J$.string().min(10).describe("Detailed task instructions"),run_in_background:J$.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),isolation:J$.enum(["none","worktree"]).optional().describe('Filesystem isolation for this child. Use "worktree" to prevent edits from affecting the parent workspace.'),resume:J$.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript."),subagent_session_id:J$.string().optional().describe("Internal subagent session id for tracking")}),description:{short:"Launch a new agent to handle complex, multi-step tasks autonomously",get long(){return e7()},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($,W){let{subagent_type:Z,description:Y,prompt:J,run_in_background:X=!1,isolation:V,resume:H,subagent_session_id:K}=$,{updateOutput:B}=W,U=W.sessionId,Q=typeof K==="string"&&K.length>0?K:typeof H==="string"&&H.length>0?H:o5(),q,w=!1,E=V??"none",G=async(F)=>{if(!q||w)return;let z=await d$.finalize({agentId:Q,lease:q,success:F});return w=!0,z};try{let F=P.getAllNames(),z=P.getSubagent(Z);if(!z)return{success:!1,llmContent:`Unknown subagent type: ${Z}. Available types: ${F.join(", ")||"none"}`,error:{type:"execution_error",message:`Unknown subagent type: ${Z}`},metadata:{summary:`未知的 subagent 类型: ${Z}`}};if(E=V??z.isolation??"none",H)return W3(H,J,z,Y,W);if(X)return $3(z,Y,J,W,Q,E);B?.(`启动 ${Z} subagent: ${Y}`),q=await d$.prepare({agentId:Q,sourceWorkspaceRoot:W.workspaceRoot||D(),isolation:E});let O=new pW(z),_=o5(8);U1.getState().app.actions.startSubagentProgress(_,Z,Y);let R={prompt:J,parentSessionId:W.sessionId,permissionMode:W.permissionMode,subagentSessionId:Q,workspaceRoot:q.workspaceRoot,worktreeActive:Boolean(q.worktree),onEvent:(y)=>{switch(y.kind){case"tool_start":{let x=y.toolCall,g="function"in x?x.function.name:"Unknown";if(U1.getState().app.actions.updateSubagentTool(g),U){if(T$.publish(U,"subagent.update",{subagentSessionId:Q,toolName:g}),"function"in x)T$.publish(U,"subagent.tool.start",{subagentSessionId:Q,toolCallId:x.id,toolName:g,arguments:x.function.arguments,toolKind:y.toolKind})}break}case"tool_result":{if(!U)break;let x=y.toolCall;if(!("function"in x))break;T$.publish(U,"subagent.tool.result",{subagentSessionId:Q,toolCallId:x.id,toolName:x.function.name,success:!y.result.error,summary:y.result.metadata?.summary,output:a5(n5(x.function.name,y.result)),metadata:y.result.metadata});break}case"content_delta":{if(U)T$.publish(U,"subagent.delta",{subagentSessionId:Q,delta:y.delta});break}case"thinking_delta":{if(U)T$.publish(U,"subagent.thinking.delta",{subagentSessionId:Q,delta:y.delta});break}case"stream_end":{if(U)T$.publish(U,"subagent.stream.end",{subagentSessionId:Q});break}default:break}}};B?.("执行任务中...");let j=Date.now(),A=await O.execute(R),L=Date.now()-j;try{let x=await w0.getInstance().executeSubagentStopHooks(Z,{projectDir:q.workspaceRoot,sessionId:W.sessionId||"unknown",permissionMode:W.permissionMode||"default",taskDescription:Y,success:A.success,resultSummary:A.message.slice(0,500),error:A.error});if(!x.shouldStop&&x.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${x.continueReason}`);let g={...R,prompt:x.continueReason},c0=Date.now();A=await O.execute(g),L+=Date.now()-c0}if(x.warning)console.warn(`[Task] SubagentStop hook warning: ${x.warning}`)}catch(y){console.warn("[Task] SubagentStop hook execution failed:",y)}let b=await G(A.success);if(b?.preserved)A.worktreePath=b.worktreePath,A.worktreeBranch=b.worktreeBranch,A.worktree=b.worktree;if(U1.getState().app.actions.completeSubagentProgress(A.success),A.success){let y=A.worktreePath?`
865
865
 
866
- Worktree preserved at ${A.worktreePath}${A.worktreeBranch?` on branch ${A.worktreeBranch}`:""}.`:"";return{success:!0,llmContent:`${A.message}${y}`,metadata:{summary:`${Z} 任务完成`,subagent_type:Z,description:Y,duration:k,stats:A.stats,subagentSessionId:U,subagentType:Z,subagentStatus:"completed",subagentSummary:A.message.slice(0,500),verificationCommands:A.verificationCommands,isolation:E,worktreePath:A.worktreePath,worktreeBranch:A.worktreeBranch}}}else{let y=A.worktreePath?` Worktree preserved at ${A.worktreePath}.`:"";return{success:!1,llmContent:`Subagent execution failed: ${A.error}.${y}`,error:{type:"execution_error",message:A.error||"Unknown error"},metadata:{summary:`${Z} 任务失败`,subagentSessionId:U,subagentType:Z,subagentStatus:"failed",isolation:E,worktreePath:A.worktreePath,worktreeBranch:A.worktreeBranch}}}}catch(F){Q1.getState().app.actions.completeSubagentProgress(!1);let R=F,O=o7(R),_;try{_=await G(!1)}catch(N){console.warn("[Task] Failed to preserve subagent worktree:",N)}let z=_?.worktreePath?` Worktree preserved at ${_.worktreePath}.`:"";return{success:!1,llmContent:`Subagent execution error: ${R.message}.${z}`,error:{type:"execution_error",message:R.message,details:F},metadata:{summary:`Subagent 执行异常: ${O}`,isolation:E,worktreePath:_?.worktreePath,worktreeBranch:_?.worktreeBranch}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});function $3($,W,Z,Y,J,X){if(!Y.sessionId)return{success:!1,llmContent:"Background agents require an active parent session",error:{type:"validation_error",message:"后台 Agent 缺少 parent session 上下文"},metadata:{summary:"后台 Agent 启动失败: 缺少 parent session"}};let H=e.getInstance().startBackgroundAgent({config:$,description:W,prompt:Z,parentSessionId:Y.sessionId,permissionMode:Y.permissionMode,agentId:J,workspaceRoot:Y.workspaceRoot||D(),isolation:X});return{success:!0,llmContent:{agent_id:H,status:"running",message:`Agent started in background. Use TaskOutput(task_id: "${H}") to retrieve results.`},metadata:{summary:`后台 Agent 已启动: ${H}`,agent_id:H,subagent_type:$.name,description:W,background:!0,isolation:X,subagentSessionId:H,subagentType:$.name,subagentStatus:"running"}}}function W3($,W,Z,Y,J){let X=e.getInstance();if(!X.getAgent($,J.sessionId??""))return{success:!1,llmContent:`Cannot resume agent ${$}: session not found`,error:{type:"execution_error",message:`Agent session not found: ${$}`},metadata:{summary:`恢复 Agent 失败: 会话不存在 ${$}`}};if(X.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,error:{type:"execution_error",message:`Agent is still running: ${$}`},metadata:{summary:`恢复 Agent 失败: 仍在运行 ${$}`}};let H=X.resumeAgent($,W,Z,J.sessionId,J.permissionMode);if(!H)return{success:!1,llmContent:`Failed to resume agent ${$}`,error:{type:"execution_error",message:`Failed to resume agent: ${$}`},metadata:{summary:`恢复 Agent 失败: ${$}`}};return{success:!0,llmContent:{agent_id:H,status:"running",resumed_from:$,message:`Agent resumed in background. Use TaskOutput(task_id: "${H}") to retrieve results.`},metadata:{summary:`恢复 Agent: ${H}`,agent_id:H,resumed_from:$,subagent_type:Z.name,description:Y,background:!0,subagentSessionId:H,subagentType:Z.name,subagentStatus:"running"}}}import{z as $2}from"zod";var mW=j({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:$2.object({task_id:$2.string().min(1).describe("The task ID to get output from"),block:$2.boolean().default(!0).describe("Whether to wait for completion"),timeout:$2.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
866
+ Worktree preserved at ${A.worktreePath}${A.worktreeBranch?` on branch ${A.worktreeBranch}`:""}.`:"";return{success:!0,llmContent:`${A.message}${y}`,metadata:{summary:`${Z} 任务完成`,subagent_type:Z,description:Y,duration:L,stats:A.stats,subagentSessionId:Q,subagentType:Z,subagentStatus:"completed",subagentSummary:A.message.slice(0,500),verificationCommands:A.verificationCommands,isolation:E,worktreePath:A.worktreePath,worktreeBranch:A.worktreeBranch}}}else{let y=A.worktreePath?` Worktree preserved at ${A.worktreePath}.`:"";return{success:!1,llmContent:`Subagent execution failed: ${A.error}.${y}`,error:{type:"execution_error",message:A.error||"Unknown error"},metadata:{summary:`${Z} 任务失败`,subagentSessionId:Q,subagentType:Z,subagentStatus:"failed",isolation:E,worktreePath:A.worktreePath,worktreeBranch:A.worktreeBranch}}}}catch(F){U1.getState().app.actions.completeSubagentProgress(!1);let z=F,O=o7(z),_;try{_=await G(!1)}catch(j){console.warn("[Task] Failed to preserve subagent worktree:",j)}let R=_?.worktreePath?` Worktree preserved at ${_.worktreePath}.`:"";return{success:!1,llmContent:`Subagent execution error: ${z.message}.${R}`,error:{type:"execution_error",message:z.message,details:F},metadata:{summary:`Subagent 执行异常: ${O}`,isolation:E,worktreePath:_?.worktreePath,worktreeBranch:_?.worktreeBranch}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});function $3($,W,Z,Y,J,X){if(!Y.sessionId)return{success:!1,llmContent:"Background agents require an active parent session",error:{type:"validation_error",message:"后台 Agent 缺少 parent session 上下文"},metadata:{summary:"后台 Agent 启动失败: 缺少 parent session"}};let H=e.getInstance().startBackgroundAgent({config:$,description:W,prompt:Z,parentSessionId:Y.sessionId,permissionMode:Y.permissionMode,agentId:J,workspaceRoot:Y.workspaceRoot||D(),isolation:X});return{success:!0,llmContent:{agent_id:H,status:"running",message:`Agent started in background. Use TaskOutput(task_id: "${H}") to retrieve results.`},metadata:{summary:`后台 Agent 已启动: ${H}`,agent_id:H,subagent_type:$.name,description:W,background:!0,isolation:X,subagentSessionId:H,subagentType:$.name,subagentStatus:"running"}}}function W3($,W,Z,Y,J){let X=e.getInstance();if(!X.getAgent($,J.sessionId??""))return{success:!1,llmContent:`Cannot resume agent ${$}: session not found`,error:{type:"execution_error",message:`Agent session not found: ${$}`},metadata:{summary:`恢复 Agent 失败: 会话不存在 ${$}`}};if(X.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,error:{type:"execution_error",message:`Agent is still running: ${$}`},metadata:{summary:`恢复 Agent 失败: 仍在运行 ${$}`}};let H=X.resumeAgent($,W,Z,J.sessionId,J.permissionMode);if(!H)return{success:!1,llmContent:`Failed to resume agent ${$}`,error:{type:"execution_error",message:`Failed to resume agent: ${$}`},metadata:{summary:`恢复 Agent 失败: ${$}`}};return{success:!0,llmContent:{agent_id:H,status:"running",resumed_from:$,message:`Agent resumed in background. Use TaskOutput(task_id: "${H}") to retrieve results.`},metadata:{summary:`恢复 Agent: ${H}`,agent_id:H,resumed_from:$,subagent_type:Z.name,description:Y,background:!0,subagentSessionId:H,subagentType:Z.name,subagentStatus:"running"}}}import{z as $2}from"zod";var mW=N({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:$2.object({task_id:$2.string().min(1).describe("The task ID to get output from"),block:$2.boolean().default(!0).describe("Whether to wait for completion"),timeout:$2.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
867
867
  - Retrieves output from a running or completed task (background shell, agent, or remote session)
868
868
  - Takes a task_id parameter identifying the task
869
869
  - Returns the task output along with status information
@@ -915,7 +915,7 @@ Only mark a task completed when it is fully accomplished. If tests are failing,
915
915
 
916
916
  Status progresses: pending -> in_progress -> completed
917
917
 
918
- Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function lW($){return[K3($),Q3($),U3($),q3($)]}function K3($){let{sessionId:W,configDir:Z}=$;return j({name:"TaskCreate",displayName:"Task Create",kind:"readonly",isConcurrencySafe:!1,schema:p.object({subject:p.string().min(1).describe("A brief title for the task"),description:p.string().min(1).describe("What needs to be done"),activeForm:p.string().optional().describe("Present continuous form shown while in_progress"),owner:p.string().optional().describe("Optional owner for the task"),priority:p.enum(["high","medium","low"]).default("medium"),metadata:p.record(p.unknown()).optional()}),description:{short:"Create a new task in the task list",long:H3},async execute(Y,J){try{let X=J2(J,W,Z),V=await X.createTask(Y),H=await X.listTasks(),B=X.getStats();return Y2({llmContent:{task:k$(V),tasks:H.map(k$),stats:B},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:H,stats:B})}catch(X){return X2(X,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.subject,abstractPermissionRule:()=>"*"})}function Q3($){let{sessionId:W,configDir:Z}=$;return j({name:"TaskGet",displayName:"Task Get",kind:"readonly",isConcurrencySafe:!0,schema:p.object({taskId:p.string().min(1).describe("The ID of the task to retrieve")}),description:{short:"Retrieve a task by ID",long:"Use this tool to inspect the latest state of a task before updating it."},async execute(Y,J){try{let V=await J2(J,W,Z).getTask(Y.taskId);return{success:!0,llmContent:{task:V?k$(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${Y.taskId} 不存在`}}}catch(X){return X2(X,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function U3($){let{sessionId:W,configDir:Z}=$;return j({name:"TaskUpdate",displayName:"Task Update",kind:"readonly",isConcurrencySafe:!1,schema:p.object({taskId:p.string().min(1).describe("The ID of the task to update"),subject:p.string().min(1).optional().describe("New subject for the task"),description:p.string().min(1).optional().describe("New description for the task"),activeForm:p.string().min(1).optional(),status:cW.or(p.literal("deleted")).optional(),owner:p.string().optional(),addBlocks:p.array(p.string()).optional(),addBlockedBy:p.array(p.string()).optional(),metadata:p.record(p.unknown()).optional()}),description:{short:"Update a task in the task list",long:B3},async execute(Y,J){try{let X=J2(J,W,Z),V=Y.status;if(V==="deleted"){let q=await X.deleteTask(Y.taskId),w=await X.listTasks(),E=X.getStats();return Y2({llmContent:{success:q,taskId:Y.taskId,updatedFields:q?["deleted"]:[],error:q?void 0:"Task not found",tasks:w.map(k$),stats:E},summary:q?`删除任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:w,stats:E})}let{task:H,updatedFields:B,statusChange:K}=await X.updateTask(Y.taskId,{subject:Y.subject,description:Y.description,activeForm:Y.activeForm,status:V,owner:Y.owner,addBlocks:Y.addBlocks,addBlockedBy:Y.addBlockedBy,metadata:Y.metadata}),Q=await X.listTasks(),U=X.getStats();return Y2({llmContent:{success:H!==null,taskId:Y.taskId,task:H?k$(H):null,updatedFields:B,error:H?void 0:"Task not found",statusChange:K,tasks:Q.map(k$),stats:U},summary:H?`更新任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:Q,stats:U})}catch(X){return X2(X,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function q3($){let{sessionId:W,configDir:Z}=$;return j({name:"TaskList",displayName:"Task List",kind:"readonly",isConcurrencySafe:!0,schema:p.object({}),description:{short:"List all tasks",long:"Use this tool to check the current task list and avoid creating duplicate tasks."},async execute(Y,J){try{let X=J2(J,W,Z),V=await X.listTasks(),H=X.getStats();return Y2({llmContent:{tasks:V.map(k$),stats:H},summary:V.length===0?"暂无任务":`任务列表 (${H.completed}/${H.total} 完成)`,tasks:V,stats:H})}catch(X){return X2(X,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function J2($,W,Z){return L$.getInstance($.taskListId||$.sessionId||W,Z)}function Y2($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function X2($,W){let Z=$;return{success:!1,llmContent:`Task operation failed: ${Z.message}`,error:{type:"execution_error",message:Z.message,details:$},metadata:{summary:W}}}function k$($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as e5 from"os";import*as $8 from"path";import{z as J0}from"zod";import*as X$ from"fs/promises";import*as U1 from"path";class E0{static instances=new Map;teamsDir;constructor($){this.teamsDir=U1.join($,"teams")}static getInstance($){if(!E0.instances.has($))E0.instances.set($,new E0($));return E0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return U1.join(this.teamsDir,E0.sanitizeName($),"config.json")}async createTeam($){let W=await this.getUniqueTeamName($.name),Z=Date.now(),Y=this.getTeamFilePath(W),J={name:W,description:$.description,createdAt:Z,updatedAt:Z,leadAgentId:`team-lead@${W}`,leadSessionId:$.leadSessionId,teamFilePath:Y,members:[{id:`team-lead@${W}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:Z},...$.members]};return await this.saveTeam(J),J}async loadTeam($){try{let W=await X$.readFile(this.getTeamFilePath($),"utf-8");return w3(JSON.parse(W))}catch(W){if(W.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,W);return}}async saveTeam($){let W=this.getTeamFilePath($.name);await X$.mkdir(U1.dirname(W),{recursive:!0,mode:493}),await X$.writeFile(W,JSON.stringify({...$,teamFilePath:W,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await X$.readdir(this.teamsDir,{withFileTypes:!0}),W=[];for(let Z of $){if(!Z.isDirectory())continue;let Y=await this.loadTeam(Z.name);if(Y)W.push(Y)}return W.sort((Z,Y)=>Y.updatedAt-Z.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let W=await this.loadTeam($);if(!W)return;let Z=Date.now(),Y={...W,deletedAt:Z,updatedAt:Z,members:W.members.map((J)=>J.status==="running"?{...J,status:"cancelled",completedAt:J.completedAt||Z}:J)};return await this.saveTeam(Y),Y}async getUniqueTeamName($){let W=E0.sanitizeName($);if(!W)throw Error("team_name must contain at least one letter or number");let Z=W,Y=2;while(await this.loadTeam(Z))Z=`${W}-${Y}`,Y+=1;return Z}}function w3($){if(!$||typeof $!=="object")return;let W=$;if(!W.name||!Array.isArray(W.members))return;return{name:W.name,description:W.description,createdAt:typeof W.createdAt==="number"?W.createdAt:Date.now(),updatedAt:typeof W.updatedAt==="number"?W.updatedAt:Date.now(),deletedAt:typeof W.deletedAt==="number"?W.deletedAt:void 0,leadAgentId:W.leadAgentId||`team-lead@${W.name}`,leadSessionId:W.leadSessionId,teamFilePath:W.teamFilePath||"",members:W.members.map((Z)=>({id:Z.id,name:Z.name,subagentType:Z.subagentType,description:Z.description,prompt:Z.prompt,agentId:Z.agentId,status:Z.status,joinedAt:Z.joinedAt,completedAt:Z.completedAt}))}}var G3=J0.object({name:J0.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:J0.string().min(1).describe("Registered subagent type to launch for this teammate"),description:J0.string().min(3).max(100).optional(),prompt:J0.string().min(10).describe("Detailed assignment for this teammate")});function rW($){let W=$?.sessionId||`session_${Date.now()}`,Z=$?.configDir||$8.join(e5.homedir(),".blade");return[E3({sessionId:W,configDir:Z}),F3({configDir:Z}),z3({configDir:Z})]}function E3($){return j({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:J0.object({team_name:J0.string().min(1).describe("Name for the new agent team"),description:J0.string().optional().describe("Team description or purpose"),agent_type:J0.string().optional().describe("Optional role/type label for the team lead"),members:J0.array(G3).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:j3(),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(W,Z){try{R3();let Y=_3(W.members.map((q)=>q.name));if(Y)return V2(`Duplicate teammate name: ${Y}`,"创建团队失败");let J=W.members.map((q)=>q.subagent_type).filter((q)=>!f.getSubagent(q));if(J.length>0)return V2(`Invalid subagent type(s): ${[...new Set(J)].join(", ")}. Available: ${f.getAllNames().join(", ")||"none"}`,"创建团队失败");let X=e.getInstance(),V=E0.getInstance($.configDir),H=await V.createTeam({name:W.team_name,description:W.description,leadAgentType:W.agent_type,leadSessionId:Z.sessionId||$.sessionId,members:[]}),B=Date.now(),K=[];for(let q of W.members){let w=f.getSubagent(q.subagent_type);if(!w)continue;let E=`${E0.sanitizeName(q.name)}@${H.name}`,G=O3({teamName:H.name,teamDescription:W.description,memberName:q.name,memberPrompt:q.prompt,teamFileHint:H.teamFilePath}),F=X.startBackgroundAgent({config:w,description:q.description||q.name,prompt:G,parentSessionId:Z.sessionId||$.sessionId,permissionMode:Z.permissionMode,agentId:E,taskListId:H.name,workspaceRoot:Z.workspaceRoot||D(),isolation:w.isolation});K.push({id:E,name:q.name,subagentType:q.subagent_type,description:q.description||q.name,prompt:q.prompt,agentId:F,status:"running",joinedAt:B})}let Q={...H,members:[...H.members,...K],updatedAt:Date.now()};await V.saveTeam(Q);let U=await iW(V,Q);return{success:!0,llmContent:{team:c$(U),message:K.length>0?`Team created with ${K.length} teammate(s). Use TeamStatus(team_name: "${U.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${U.name}".`},metadata:{summary:`创建 Agent Team: ${U.name} (${K.length} teammates)`,team_name:U.name,team_file_path:U.teamFilePath,lead_agent_id:U.leadAgentId,member_agent_ids:K.map((q)=>q.agentId).filter(Boolean)}}}catch(Y){return nW(Y,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(W)=>W.team_name,abstractPermissionRule:()=>"*"})}function F3($){return j({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:J0.object({team_name:J0.string().optional().describe("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(W){try{let Z=E0.getInstance($.configDir);if(!W.team_name){let X=await Promise.all((await Z.listTeams()).map((V)=>iW(Z,V)));return{success:!0,llmContent:{teams:X.map(c$)},metadata:{summary:X.length===0?"暂无 Agent Teams":`Agent Teams: ${X.length}`,teams:X.map(c$)}}}let Y=await Z.loadTeam(W.team_name);if(!Y)return V2(`Team not found: ${W.team_name}`,"读取团队失败");let J=await iW(Z,Y);return{success:!0,llmContent:{team:c$(J)},metadata:{summary:`Agent Team ${J.name}: ${W8(J)}`,team:c$(J)}}}catch(Z){return nW(Z,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(W)=>W.team_name||"*",abstractPermissionRule:()=>"*"})}function z3($){return j({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:J0.object({team_name:J0.string().min(1).describe("Team name to delete"),kill_running:J0.boolean().default(!0).describe("Whether to cancel running teammate agents")}),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(W){try{let Z=E0.getInstance($.configDir),Y=await Z.loadTeam(W.team_name);if(!Y)return V2(`Team not found: ${W.team_name}`,"删除团队失败");let J=e.getInstance(),X=[];if(W.kill_running){for(let H of Y.members)if(H.agentId&&J.killAgent(H.agentId))X.push(H.agentId)}let V=await Z.markDeleted(W.team_name);return{success:!0,llmContent:{team:V?c$(V):null,killed_agent_ids:X},metadata:{summary:`删除 Agent Team: ${Y.name}`,team_name:Y.name,killed_agent_ids:X}}}catch(Z){return nW(Z,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(W)=>W.team_name,abstractPermissionRule:()=>"*"})}function R3(){if(f.getAllNames().length===0)f.loadFromStandardLocations()}function O3($){return`
918
+ Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function lW($){return[K3($),U3($),Q3($),q3($)]}function K3($){let{sessionId:W,configDir:Z}=$;return N({name:"TaskCreate",displayName:"Task Create",kind:"readonly",isConcurrencySafe:!1,schema:p.object({subject:p.string().min(1).describe("A brief title for the task"),description:p.string().min(1).describe("What needs to be done"),activeForm:p.string().optional().describe("Present continuous form shown while in_progress"),owner:p.string().optional().describe("Optional owner for the task"),priority:p.enum(["high","medium","low"]).default("medium"),metadata:p.record(p.unknown()).optional()}),description:{short:"Create a new task in the task list",long:H3},async execute(Y,J){try{let X=J2(J,W,Z),V=await X.createTask(Y),H=await X.listTasks(),K=X.getStats();return Y2({llmContent:{task:k$(V),tasks:H.map(k$),stats:K},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:H,stats:K})}catch(X){return X2(X,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.subject,abstractPermissionRule:()=>"*"})}function U3($){let{sessionId:W,configDir:Z}=$;return N({name:"TaskGet",displayName:"Task Get",kind:"readonly",isConcurrencySafe:!0,schema:p.object({taskId:p.string().min(1).describe("The ID of the task to retrieve")}),description:{short:"Retrieve a task by ID",long:"Use this tool to inspect the latest state of a task before updating it."},async execute(Y,J){try{let V=await J2(J,W,Z).getTask(Y.taskId);return{success:!0,llmContent:{task:V?k$(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${Y.taskId} 不存在`}}}catch(X){return X2(X,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function Q3($){let{sessionId:W,configDir:Z}=$;return N({name:"TaskUpdate",displayName:"Task Update",kind:"readonly",isConcurrencySafe:!1,schema:p.object({taskId:p.string().min(1).describe("The ID of the task to update"),subject:p.string().min(1).optional().describe("New subject for the task"),description:p.string().min(1).optional().describe("New description for the task"),activeForm:p.string().min(1).optional(),status:cW.or(p.literal("deleted")).optional(),owner:p.string().optional(),addBlocks:p.array(p.string()).optional(),addBlockedBy:p.array(p.string()).optional(),metadata:p.record(p.unknown()).optional()}),description:{short:"Update a task in the task list",long:B3},async execute(Y,J){try{let X=J2(J,W,Z),V=Y.status;if(V==="deleted"){let q=await X.deleteTask(Y.taskId),w=await X.listTasks(),E=X.getStats();return Y2({llmContent:{success:q,taskId:Y.taskId,updatedFields:q?["deleted"]:[],error:q?void 0:"Task not found",tasks:w.map(k$),stats:E},summary:q?`删除任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:w,stats:E})}let{task:H,updatedFields:K,statusChange:B}=await X.updateTask(Y.taskId,{subject:Y.subject,description:Y.description,activeForm:Y.activeForm,status:V,owner:Y.owner,addBlocks:Y.addBlocks,addBlockedBy:Y.addBlockedBy,metadata:Y.metadata}),U=await X.listTasks(),Q=X.getStats();return Y2({llmContent:{success:H!==null,taskId:Y.taskId,task:H?k$(H):null,updatedFields:K,error:H?void 0:"Task not found",statusChange:B,tasks:U.map(k$),stats:Q},summary:H?`更新任务 #${Y.taskId}`:`任务 #${Y.taskId} 不存在`,tasks:U,stats:Q})}catch(X){return X2(X,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(Y)=>Y.taskId,abstractPermissionRule:()=>"*"})}function q3($){let{sessionId:W,configDir:Z}=$;return N({name:"TaskList",displayName:"Task List",kind:"readonly",isConcurrencySafe:!0,schema:p.object({}),description:{short:"List all tasks",long:"Use this tool to check the current task list and avoid creating duplicate tasks."},async execute(Y,J){try{let X=J2(J,W,Z),V=await X.listTasks(),H=X.getStats();return Y2({llmContent:{tasks:V.map(k$),stats:H},summary:V.length===0?"暂无任务":`任务列表 (${H.completed}/${H.total} 完成)`,tasks:V,stats:H})}catch(X){return X2(X,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function J2($,W,Z){return L$.getInstance($.taskListId||$.sessionId||W,Z)}function Y2($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function X2($,W){let Z=$;return{success:!1,llmContent:`Task operation failed: ${Z.message}`,error:{type:"execution_error",message:Z.message,details:$},metadata:{summary:W}}}function k$($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as e5 from"os";import*as $8 from"path";import{z as J0}from"zod";import*as X$ from"fs/promises";import*as Q1 from"path";class E0{static instances=new Map;teamsDir;constructor($){this.teamsDir=Q1.join($,"teams")}static getInstance($){if(!E0.instances.has($))E0.instances.set($,new E0($));return E0.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return Q1.join(this.teamsDir,E0.sanitizeName($),"config.json")}async createTeam($){let W=await this.getUniqueTeamName($.name),Z=Date.now(),Y=this.getTeamFilePath(W),J={name:W,description:$.description,createdAt:Z,updatedAt:Z,leadAgentId:`team-lead@${W}`,leadSessionId:$.leadSessionId,teamFilePath:Y,members:[{id:`team-lead@${W}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:Z},...$.members]};return await this.saveTeam(J),J}async loadTeam($){try{let W=await X$.readFile(this.getTeamFilePath($),"utf-8");return w3(JSON.parse(W))}catch(W){if(W.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,W);return}}async saveTeam($){let W=this.getTeamFilePath($.name);await X$.mkdir(Q1.dirname(W),{recursive:!0,mode:493}),await X$.writeFile(W,JSON.stringify({...$,teamFilePath:W,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await X$.readdir(this.teamsDir,{withFileTypes:!0}),W=[];for(let Z of $){if(!Z.isDirectory())continue;let Y=await this.loadTeam(Z.name);if(Y)W.push(Y)}return W.sort((Z,Y)=>Y.updatedAt-Z.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let W=await this.loadTeam($);if(!W)return;let Z=Date.now(),Y={...W,deletedAt:Z,updatedAt:Z,members:W.members.map((J)=>J.status==="running"?{...J,status:"cancelled",completedAt:J.completedAt||Z}:J)};return await this.saveTeam(Y),Y}async getUniqueTeamName($){let W=E0.sanitizeName($);if(!W)throw Error("team_name must contain at least one letter or number");let Z=W,Y=2;while(await this.loadTeam(Z))Z=`${W}-${Y}`,Y+=1;return Z}}function w3($){if(!$||typeof $!=="object")return;let W=$;if(!W.name||!Array.isArray(W.members))return;return{name:W.name,description:W.description,createdAt:typeof W.createdAt==="number"?W.createdAt:Date.now(),updatedAt:typeof W.updatedAt==="number"?W.updatedAt:Date.now(),deletedAt:typeof W.deletedAt==="number"?W.deletedAt:void 0,leadAgentId:W.leadAgentId||`team-lead@${W.name}`,leadSessionId:W.leadSessionId,teamFilePath:W.teamFilePath||"",members:W.members.map((Z)=>({id:Z.id,name:Z.name,subagentType:Z.subagentType,description:Z.description,prompt:Z.prompt,agentId:Z.agentId,status:Z.status,joinedAt:Z.joinedAt,completedAt:Z.completedAt}))}}var G3=J0.object({name:J0.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:J0.string().min(1).describe("Registered subagent type to launch for this teammate"),description:J0.string().min(3).max(100).optional(),prompt:J0.string().min(10).describe("Detailed assignment for this teammate")});function rW($){let W=$?.sessionId||`session_${Date.now()}`,Z=$?.configDir||$8.join(e5.homedir(),".blade");return[E3({sessionId:W,configDir:Z}),F3({configDir:Z}),z3({configDir:Z})]}function E3($){return N({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:J0.object({team_name:J0.string().min(1).describe("Name for the new agent team"),description:J0.string().optional().describe("Team description or purpose"),agent_type:J0.string().optional().describe("Optional role/type label for the team lead"),members:J0.array(G3).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:j3(),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(W,Z){try{R3();let Y=D3(W.members.map((q)=>q.name));if(Y)return V2(`Duplicate teammate name: ${Y}`,"创建团队失败");let J=W.members.map((q)=>q.subagent_type).filter((q)=>!P.getSubagent(q));if(J.length>0)return V2(`Invalid subagent type(s): ${[...new Set(J)].join(", ")}. Available: ${P.getAllNames().join(", ")||"none"}`,"创建团队失败");let X=e.getInstance(),V=E0.getInstance($.configDir),H=await V.createTeam({name:W.team_name,description:W.description,leadAgentType:W.agent_type,leadSessionId:Z.sessionId||$.sessionId,members:[]}),K=Date.now(),B=[];for(let q of W.members){let w=P.getSubagent(q.subagent_type);if(!w)continue;let E=`${E0.sanitizeName(q.name)}@${H.name}`,G=O3({teamName:H.name,teamDescription:W.description,memberName:q.name,memberPrompt:q.prompt,teamFileHint:H.teamFilePath}),F=X.startBackgroundAgent({config:w,description:q.description||q.name,prompt:G,parentSessionId:Z.sessionId||$.sessionId,permissionMode:Z.permissionMode,agentId:E,taskListId:H.name,workspaceRoot:Z.workspaceRoot||D(),isolation:w.isolation});B.push({id:E,name:q.name,subagentType:q.subagent_type,description:q.description||q.name,prompt:q.prompt,agentId:F,status:"running",joinedAt:K})}let U={...H,members:[...H.members,...B],updatedAt:Date.now()};await V.saveTeam(U);let Q=await iW(V,U);return{success:!0,llmContent:{team:c$(Q),message:B.length>0?`Team created with ${B.length} teammate(s). Use TeamStatus(team_name: "${Q.name}") to inspect progress.`:`Team created. Use Task and TaskCreate tools to coordinate work for "${Q.name}".`},metadata:{summary:`创建 Agent Team: ${Q.name} (${B.length} teammates)`,team_name:Q.name,team_file_path:Q.teamFilePath,lead_agent_id:Q.leadAgentId,member_agent_ids:B.map((q)=>q.agentId).filter(Boolean)}}}catch(Y){return nW(Y,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(W)=>W.team_name,abstractPermissionRule:()=>"*"})}function F3($){return N({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:J0.object({team_name:J0.string().optional().describe("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(W){try{let Z=E0.getInstance($.configDir);if(!W.team_name){let X=await Promise.all((await Z.listTeams()).map((V)=>iW(Z,V)));return{success:!0,llmContent:{teams:X.map(c$)},metadata:{summary:X.length===0?"暂无 Agent Teams":`Agent Teams: ${X.length}`,teams:X.map(c$)}}}let Y=await Z.loadTeam(W.team_name);if(!Y)return V2(`Team not found: ${W.team_name}`,"读取团队失败");let J=await iW(Z,Y);return{success:!0,llmContent:{team:c$(J)},metadata:{summary:`Agent Team ${J.name}: ${W8(J)}`,team:c$(J)}}}catch(Z){return nW(Z,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(W)=>W.team_name||"*",abstractPermissionRule:()=>"*"})}function z3($){return N({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:J0.object({team_name:J0.string().min(1).describe("Team name to delete"),kill_running:J0.boolean().default(!0).describe("Whether to cancel running teammate agents")}),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(W){try{let Z=E0.getInstance($.configDir),Y=await Z.loadTeam(W.team_name);if(!Y)return V2(`Team not found: ${W.team_name}`,"删除团队失败");let J=e.getInstance(),X=[];if(W.kill_running){for(let H of Y.members)if(H.agentId&&J.killAgent(H.agentId))X.push(H.agentId)}let V=await Z.markDeleted(W.team_name);return{success:!0,llmContent:{team:V?c$(V):null,killed_agent_ids:X},metadata:{summary:`删除 Agent Team: ${Y.name}`,team_name:Y.name,killed_agent_ids:X}}}catch(Z){return nW(Z,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(W)=>W.team_name,abstractPermissionRule:()=>"*"})}function R3(){if(P.getAllNames().length===0)P.loadFromStandardLocations()}function O3($){return`
919
919
  You are ${$.memberName}, a teammate in Blade agent team "${$.teamName}".
920
920
 
921
921
  Team purpose: ${$.teamDescription||"Coordinate parallel agent work"}.
@@ -927,7 +927,7 @@ Work independently on your assignment and return a concise final result for the
927
927
 
928
928
  Assignment:
929
929
  ${$.memberPrompt}
930
- `.trim()}async function iW($,W){let Z=e.getInstance(),Y=!1,J=W.members.map((V)=>{if(!V.agentId)return V;let H=Z.getAgent(V.agentId);if(!H)return{...V,status:"unknown"};let B=D3(H);if(B!==V.status||H.completedAt!==V.completedAt)return Y=!0,{...V,status:B,completedAt:H.completedAt};return V}),X={...W,members:J};if(Y)await $.saveTeam(X);return X}function D3($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function c$($){let W=e.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":W8($),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((Z)=>{let Y=Z.agentId?W.getAgent(Z.agentId):void 0;return{id:Z.id,name:Z.name,subagent_type:Z.subagentType,description:Z.description,agent_id:Z.agentId,status:Z.status,task_output_id:Z.agentId,result:Y?.result,stats:Y?.stats}})}}function W8($){let W=$.members.reduce((Z,Y)=>{return Z[Y.status]=(Z[Y.status]||0)+1,Z},{});return Object.entries(W).map(([Z,Y])=>`${Y} ${Z}`).join(", ")}function _3($){let W=new Set;for(let Z of $){let Y=E0.sanitizeName(Z);if(W.has(Y))return Z;W.add(Y)}return}function V2($,W){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:W}}}function nW($,W){let Z=$;return{success:!1,llmContent:`Team operation failed: ${Z.message}`,error:{type:"execution_error",message:Z.message,details:$},metadata:{summary:W}}}function j3(){return`
930
+ `.trim()}async function iW($,W){let Z=e.getInstance(),Y=!1,J=W.members.map((V)=>{if(!V.agentId)return V;let H=Z.getAgent(V.agentId);if(!H)return{...V,status:"unknown"};let K=_3(H);if(K!==V.status||H.completedAt!==V.completedAt)return Y=!0,{...V,status:K,completedAt:H.completedAt};return V}),X={...W,members:J};if(Y)await $.saveTeam(X);return X}function _3($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function c$($){let W=e.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":W8($),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((Z)=>{let Y=Z.agentId?W.getAgent(Z.agentId):void 0;return{id:Z.id,name:Z.name,subagent_type:Z.subagentType,description:Z.description,agent_id:Z.agentId,status:Z.status,task_output_id:Z.agentId,result:Y?.result,stats:Y?.stats}})}}function W8($){let W=$.members.reduce((Z,Y)=>{return Z[Y.status]=(Z[Y.status]||0)+1,Z},{});return Object.entries(W).map(([Z,Y])=>`${Y} ${Z}`).join(", ")}function D3($){let W=new Set;for(let Z of $){let Y=E0.sanitizeName(Z);if(W.has(Y))return Z;W.add(Y)}return}function V2($,W){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:W}}}function nW($,W){let Z=$;return{success:!1,llmContent:`Team operation failed: ${Z.message}`,error:{type:"execution_error",message:Z.message,details:$},metadata:{summary:W}}}function j3(){return`
931
931
  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.
932
932
 
933
933
  When to use:
@@ -942,7 +942,7 @@ Workflow:
942
942
  4. Inspect progress with TeamStatus.
943
943
  5. Retrieve detailed teammate output with TaskOutput using the member task_output_id.
944
944
  6. Stop the team with TeamDelete when the work is complete or cancelled.
945
- `.trim()}import{z as K0}from"zod";import{isPlainObject as Y8}from"lodash-es";function J8($){if(!Y8($))return;let W=$;return typeof W.name==="string"?W.name:void 0}function A3($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(Y8($)){let W=$;if(typeof W.message==="string")return W.message}return String($)}var aW=j({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",isConcurrencySafe:!0,schema:K0.object({url:K0.string().url().describe("URL to request"),method:K0.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:K0.boolean().default(!1).describe("Use Jina Reader to extract clean content in Markdown format. Removes HTML clutter, scripts, and styling, returning only the main content."),jina_options:K0.object({with_generated_alt:K0.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:K0.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:K0.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:K0.record(K0.string()).optional().describe("Request headers (optional)"),body:K0.string().optional().describe("Request body (optional)"),timeout:I.timeout(1000,120000,30000),follow_redirects:K0.boolean().default(!0).describe("Follow redirects"),max_redirects:K0.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:K0.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
945
+ `.trim()}import{z as K0}from"zod";import{isPlainObject as Y8}from"lodash-es";function J8($){if(!Y8($))return;let W=$;return typeof W.name==="string"?W.name:void 0}function A3($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(Y8($)){let W=$;if(typeof W.message==="string")return W.message}return String($)}var aW=N({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",isConcurrencySafe:!0,schema:K0.object({url:K0.string().url().describe("URL to request"),method:K0.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:K0.boolean().default(!1).describe("Use Jina Reader to extract clean content in Markdown format. Removes HTML clutter, scripts, and styling, returning only the main content."),jina_options:K0.object({with_generated_alt:K0.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:K0.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:K0.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:K0.record(K0.string()).optional().describe("Request headers (optional)"),body:K0.string().optional().describe("Request body (optional)"),timeout:I.timeout(1000,120000,30000),follow_redirects:K0.boolean().default(!0).describe("Follow redirects"),max_redirects:K0.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:K0.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
946
946
  - Fetches content from a specified URL and processes it using an AI model
947
947
  - Takes a URL and a prompt as input
948
948
  - Fetches the URL content, converts HTML to markdown
@@ -959,7 +959,7 @@ Usage notes:
959
959
  - Results may be summarized if the content is very large
960
960
  - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
961
961
  - 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.
962
- `},async execute($,W){let{url:Z,method:Y="GET",extract_content:J=!1,jina_options:X,headers:V={},body:H,timeout:B=30000,follow_redirects:K=!0,max_redirects:Q=5,return_headers:U=!1}=$,{updateOutput:q}=W,w=W.signal??new AbortController().signal;try{if(J)try{let _=Date.now(),z=await k3({url:Z,jinaOptions:X,timeout:B,signal:w,updateOutput:q}),N=Date.now()-_;if(z.response_time=N,!U)delete z.headers;let A={url:Z,method:"GET",status:z.status,response_time:N,content_length:Buffer.byteLength(z.body||"","utf8"),redirected:z.redirected||!1,redirect_count:z.redirect_count??0,final_url:z.url,content_type:z.content_type,redirect_chain:z.redirect_chain},k=Z8(Z);return{success:!0,llmContent:z,metadata:{...A,summary:`GET ${k} - ${z.status}`}}}catch{q?.("[WARN] Jina Reader 失败,使用标准方式获取")}q?.(`发送 ${Y} 请求到: ${Z}`);let E=Date.now(),G=await N3({url:Z,method:Y,headers:V,body:H,timeout:B,follow_redirects:K,max_redirects:Q,signal:w}),F=Date.now()-E;if(G.response_time=F,!U)delete G.headers;let R={url:Z,method:Y,status:G.status,response_time:F,content_length:Buffer.byteLength(G.body||"","utf8"),redirected:G.redirected||!1,redirect_count:G.redirect_count??0,final_url:G.url,content_type:G.content_type,redirect_chain:G.redirect_chain},O=Z8(Z);if(G.status>=400)return{success:!1,llmContent:`HTTP error ${G.status}: ${G.status_text}`,error:{type:"execution_error",message:`HTTP error ${G.status}: ${G.status_text}`,details:{...R,response_body:G.body}},metadata:{...R,summary:`请求失败: HTTP ${G.status} ${G.status_text}`}};return{success:!0,llmContent:G,metadata:{...R,summary:`${Y} ${O} - ${G.status}`}}}catch(E){if(J8(E)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let G=A3(E);return{success:!1,llmContent:`Network request failed: ${G}`,error:{type:"execution_error",message:G,details:E},metadata:{summary:`请求失败: ${G}`}}}},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 N3($){let{url:W,method:Z,headers:Y,body:J,timeout:X,follow_redirects:V,max_redirects:H,signal:B}=$,K={"User-Agent":"Blade-AI/1.0",...Y},Q=W,U=Z,q=J,w=0,E=[];while(!0){let G={...K};if(q&&U!=="GET"&&U!=="HEAD"&&!L3(G,"content-type"))G["Content-Type"]="application/json";let F=await X8(Q,{method:U,headers:G,body:q&&U!=="GET"&&U!=="HEAD"?q:void 0,redirect:"manual"},X,B),R=F.headers.get("location"),O=F.status>=300&&F.status<400,_=V&&O&&R&&w<H;if(O&&V&&!R)throw Error(`收到状态码 ${F.status} 但响应缺少 Location 头`);if(O&&V&&w>=H)throw Error(`超过最大重定向次数 (${H})`);if(_&&R){w++;let A=T3(R,Q);if(E.push(`${F.status} -> ${A}`),F.status===303||(F.status===301||F.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",q=void 0;Q=A;continue}let z=await F.text(),N=V8(F.headers);return{status:F.status,status_text:F.statusText,headers:N,body:z,url:F.url||Q,redirected:w>0,redirect_count:w,redirect_chain:E,content_type:N["content-type"],response_time:0}}}function Z8($){try{return new URL($).hostname}catch{return $}}async function X8($,W,Z,Y){let J=new AbortController,X=setTimeout(()=>J.abort(),Z),V=()=>J.abort();Y?.addEventListener("abort",V);try{return await fetch($,{...W,signal:J.signal})}catch(H){if(J8(H)==="AbortError"){if(H instanceof Error)throw H.message="请求被中止或超时",H;let B=Error("请求被中止或超时");throw B.name="AbortError",B}throw H}finally{clearTimeout(X),Y?.removeEventListener("abort",V)}}function T3($,W){try{return new URL($,W).toString()}catch{return $}}function V8($){let W={};return $.forEach((Z,Y)=>{W[Y.toLowerCase()]=Z}),W}function L3($,W){let Z=W.toLowerCase();return Object.keys($).some((Y)=>Y.toLowerCase()===Z)}async function k3($){let{url:W,jinaOptions:Z,timeout:Y,signal:J,updateOutput:X}=$,V=`https://r.jina.ai/${encodeURIComponent(W)}`;X?.(`使用 Jina Reader 提取内容: ${W}`);let H={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(Z?.with_generated_alt)H["X-With-Generated-Alt"]="true";if(Z?.with_links_summary)H["X-With-Links-Summary"]="true";if(Z?.wait_for_selector)H["X-Wait-For-Selector"]=Z.wait_for_selector;try{let B=await X8(V,{method:"GET",headers:H},Y,J);if(!B.ok)throw Error(`Jina Reader error: ${B.status} ${B.statusText}`);let K=await B.text(),Q=b3(K);return X?.(`[OK] Jina Reader 成功提取内容 (${Q.content.length} 字符)`),{status:B.status,status_text:B.statusText,headers:V8(B.headers),body:M3(Q),url:Q.sourceUrl||W,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(B){throw X?.("[WARN] Jina Reader 失败,回退到直接获取"),B}}function b3($){let W=$.split(`
962
+ `},async execute($,W){let{url:Z,method:Y="GET",extract_content:J=!1,jina_options:X,headers:V={},body:H,timeout:K=30000,follow_redirects:B=!0,max_redirects:U=5,return_headers:Q=!1}=$,{updateOutput:q}=W,w=W.signal??new AbortController().signal;try{if(J)try{let _=Date.now(),R=await k3({url:Z,jinaOptions:X,timeout:K,signal:w,updateOutput:q}),j=Date.now()-_;if(R.response_time=j,!Q)delete R.headers;let A={url:Z,method:"GET",status:R.status,response_time:j,content_length:Buffer.byteLength(R.body||"","utf8"),redirected:R.redirected||!1,redirect_count:R.redirect_count??0,final_url:R.url,content_type:R.content_type,redirect_chain:R.redirect_chain},L=Z8(Z);return{success:!0,llmContent:R,metadata:{...A,summary:`GET ${L} - ${R.status}`}}}catch{q?.("[WARN] Jina Reader 失败,使用标准方式获取")}q?.(`发送 ${Y} 请求到: ${Z}`);let E=Date.now(),G=await N3({url:Z,method:Y,headers:V,body:H,timeout:K,follow_redirects:B,max_redirects:U,signal:w}),F=Date.now()-E;if(G.response_time=F,!Q)delete G.headers;let z={url:Z,method:Y,status:G.status,response_time:F,content_length:Buffer.byteLength(G.body||"","utf8"),redirected:G.redirected||!1,redirect_count:G.redirect_count??0,final_url:G.url,content_type:G.content_type,redirect_chain:G.redirect_chain},O=Z8(Z);if(G.status>=400)return{success:!1,llmContent:`HTTP error ${G.status}: ${G.status_text}`,error:{type:"execution_error",message:`HTTP error ${G.status}: ${G.status_text}`,details:{...z,response_body:G.body}},metadata:{...z,summary:`请求失败: HTTP ${G.status} ${G.status_text}`}};return{success:!0,llmContent:G,metadata:{...z,summary:`${Y} ${O} - ${G.status}`}}}catch(E){if(J8(E)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let G=A3(E);return{success:!1,llmContent:`Network request failed: ${G}`,error:{type:"execution_error",message:G,details:E},metadata:{summary:`请求失败: ${G}`}}}},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 N3($){let{url:W,method:Z,headers:Y,body:J,timeout:X,follow_redirects:V,max_redirects:H,signal:K}=$,B={"User-Agent":"Blade-AI/1.0",...Y},U=W,Q=Z,q=J,w=0,E=[];while(!0){let G={...B};if(q&&Q!=="GET"&&Q!=="HEAD"&&!L3(G,"content-type"))G["Content-Type"]="application/json";let F=await X8(U,{method:Q,headers:G,body:q&&Q!=="GET"&&Q!=="HEAD"?q:void 0,redirect:"manual"},X,K),z=F.headers.get("location"),O=F.status>=300&&F.status<400,_=V&&O&&z&&w<H;if(O&&V&&!z)throw Error(`收到状态码 ${F.status} 但响应缺少 Location 头`);if(O&&V&&w>=H)throw Error(`超过最大重定向次数 (${H})`);if(_&&z){w++;let A=T3(z,U);if(E.push(`${F.status} -> ${A}`),F.status===303||(F.status===301||F.status===302)&&Q!=="GET"&&Q!=="HEAD")Q="GET",q=void 0;U=A;continue}let R=await F.text(),j=V8(F.headers);return{status:F.status,status_text:F.statusText,headers:j,body:R,url:F.url||U,redirected:w>0,redirect_count:w,redirect_chain:E,content_type:j["content-type"],response_time:0}}}function Z8($){try{return new URL($).hostname}catch{return $}}async function X8($,W,Z,Y){let J=new AbortController,X=setTimeout(()=>J.abort(),Z),V=()=>J.abort();Y?.addEventListener("abort",V);try{return await fetch($,{...W,signal:J.signal})}catch(H){if(J8(H)==="AbortError"){if(H instanceof Error)throw H.message="请求被中止或超时",H;let K=Error("请求被中止或超时");throw K.name="AbortError",K}throw H}finally{clearTimeout(X),Y?.removeEventListener("abort",V)}}function T3($,W){try{return new URL($,W).toString()}catch{return $}}function V8($){let W={};return $.forEach((Z,Y)=>{W[Y.toLowerCase()]=Z}),W}function L3($,W){let Z=W.toLowerCase();return Object.keys($).some((Y)=>Y.toLowerCase()===Z)}async function k3($){let{url:W,jinaOptions:Z,timeout:Y,signal:J,updateOutput:X}=$,V=`https://r.jina.ai/${encodeURIComponent(W)}`;X?.(`使用 Jina Reader 提取内容: ${W}`);let H={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(Z?.with_generated_alt)H["X-With-Generated-Alt"]="true";if(Z?.with_links_summary)H["X-With-Links-Summary"]="true";if(Z?.wait_for_selector)H["X-Wait-For-Selector"]=Z.wait_for_selector;try{let K=await X8(V,{method:"GET",headers:H},Y,J);if(!K.ok)throw Error(`Jina Reader error: ${K.status} ${K.statusText}`);let B=await K.text(),U=b3(B);return X?.(`[OK] Jina Reader 成功提取内容 (${U.content.length} 字符)`),{status:K.status,status_text:K.statusText,headers:V8(K.headers),body:M3(U),url:U.sourceUrl||W,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(K){throw X?.("[WARN] Jina Reader 失败,回退到直接获取"),K}}function b3($){let W=$.split(`
963
963
  `),Z="",Y="",J=0;for(let V=0;V<W.length;V++){let H=W[V];if(H.startsWith("Title: "))Z=H.substring(7).trim();else if(H.startsWith("URL Source: "))Y=H.substring(12).trim();else if(H.startsWith("Markdown Content:")){J=V+1;break}}let X=W.slice(J).join(`
964
964
  `).trim();return{title:Z||"Untitled",sourceUrl:Y||"",content:X||$}}function M3($){let W="";if($.title)W+=`# ${$.title}
965
965
 
@@ -967,11 +967,11 @@ Usage notes:
967
967
 
968
968
  `;return W+=`---
969
969
 
970
- `,W+=$.content,W}import{ProxyAgent as p3,fetch as d3}from"undici";import{z as l$}from"zod";import{LRUCache as H8}from"lru-cache";import v3 from"node:crypto";class B8{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new H8({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,W){let Z=W.toLowerCase().trim(),Y=v3.createHash("md5").update(Z).digest("hex").substring(0,8);return`${$}:${Y}`}get($,W){if(!this.config.enabled)return null;let Z=this.generateKey($,W),Y=this.cache.get(Z);if(!Y)return this.misses++,null;if(Date.now()>Y.expiresAt)return this.cache.delete(Z),this.misses++,null;return this.hits++,Y.results}set($,W,Z){if(!this.config.enabled||Z.length===0)return;let Y=this.generateKey($,W),J=Date.now(),X={query:W,provider:$,results:Z,timestamp:J,expiresAt:J+this.config.ttl};this.cache.set(Y,X)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,W=$>0?this.hits/$*100:0;return{size:this.cache.size,maxSize:this.config.maxSize,enabled:this.config.enabled,ttl:this.config.ttl,hits:this.hits,misses:this.misses,hitRate:Number.parseFloat(W.toFixed(2))}}cleanup(){let $=Date.now(),W=0;for(let[Z,Y]of this.cache.entries())if($>Y.expiresAt)this.cache.delete(Z),W++;return W}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}updateConfig($){if($.maxSize!==void 0&&$.maxSize!==this.config.maxSize){this.config.maxSize=$.maxSize;let W=Array.from(this.cache.entries());this.cache=new H8({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[Z,Y]of W.slice(-this.config.maxSize))this.cache.set(Z,Y)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var x3=new B8;function K8(){return x3}function C3($){return $.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function Q8($){let W=C3($).trim();if(!W.includes(" - "))return{title:W,snippet:W};let[Z,...Y]=W.split(" - "),J=Z.trim(),X=Y.join(" - ").trim()||W;return{title:J,snippet:X}}function q1($){try{let W=new URL($),Z=W.pathname==="/"?"":W.pathname;return`${W.hostname}${Z}`}catch{return $}}function w1($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function y3($){if(!$.FirstURL||!$.Text)return null;let{title:W,snippet:Z}=Q8($.Text);return{title:W,snippet:Z,url:$.FirstURL,display_url:q1($.FirstURL),source:w1($.FirstURL)}}function U8($){let W=[];for(let Z of $){if(Z.Topics&&Z.Topics.length>0){W.push(...U8(Z.Topics));continue}if(Z.FirstURL&&Z.Text){let{title:Y,snippet:J}=Q8(Z.Text);W.push({title:Y,snippet:J,url:Z.FirstURL,display_url:q1(Z.FirstURL),source:w1(Z.FirstURL)})}}return W}function P3($){let W=$,Z=(W.Results??[]).map((J)=>y3(J)).filter((J)=>J!==null),Y=U8(W.RelatedTopics??[]);return[...Z,...Y]}var f3={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let W=new URL("https://duckduckgo.com/");return W.searchParams.set("q",$),W.searchParams.set("format","json"),W.searchParams.set("no_html","1"),W.searchParams.set("skip_disambig","1"),W.searchParams.set("t","blade-code"),W.searchParams.set("kl","us-en"),W.toString()},parseResponse:P3,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function S3($){let W=$,Z=[];for(let Y of W.results??[]){if(!Y.url||!Y.title)continue;Z.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:q1(Y.url),source:w1(Y.url)})}return Z}var q8=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function I3($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(Z)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",Z),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:S3,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var V$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function h3($){let W=[],Z=$.split(`
970
+ `,W+=$.content,W}import{ProxyAgent as p3,fetch as d3}from"undici";import{z as l$}from"zod";import{LRUCache as H8}from"lru-cache";import v3 from"node:crypto";class B8{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new H8({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,W){let Z=W.toLowerCase().trim(),Y=v3.createHash("md5").update(Z).digest("hex").substring(0,8);return`${$}:${Y}`}get($,W){if(!this.config.enabled)return null;let Z=this.generateKey($,W),Y=this.cache.get(Z);if(!Y)return this.misses++,null;if(Date.now()>Y.expiresAt)return this.cache.delete(Z),this.misses++,null;return this.hits++,Y.results}set($,W,Z){if(!this.config.enabled||Z.length===0)return;let Y=this.generateKey($,W),J=Date.now(),X={query:W,provider:$,results:Z,timestamp:J,expiresAt:J+this.config.ttl};this.cache.set(Y,X)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,W=$>0?this.hits/$*100:0;return{size:this.cache.size,maxSize:this.config.maxSize,enabled:this.config.enabled,ttl:this.config.ttl,hits:this.hits,misses:this.misses,hitRate:Number.parseFloat(W.toFixed(2))}}cleanup(){let $=Date.now(),W=0;for(let[Z,Y]of this.cache.entries())if($>Y.expiresAt)this.cache.delete(Z),W++;return W}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}isEnabled(){return this.config.enabled}updateConfig($){if($.maxSize!==void 0&&$.maxSize!==this.config.maxSize){this.config.maxSize=$.maxSize;let W=Array.from(this.cache.entries());this.cache=new H8({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[Z,Y]of W.slice(-this.config.maxSize))this.cache.set(Z,Y)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var x3=new B8;function K8(){return x3}function C3($){return $.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function U8($){let W=C3($).trim();if(!W.includes(" - "))return{title:W,snippet:W};let[Z,...Y]=W.split(" - "),J=Z.trim(),X=Y.join(" - ").trim()||W;return{title:J,snippet:X}}function q1($){try{let W=new URL($),Z=W.pathname==="/"?"":W.pathname;return`${W.hostname}${Z}`}catch{return $}}function w1($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function y3($){if(!$.FirstURL||!$.Text)return null;let{title:W,snippet:Z}=U8($.Text);return{title:W,snippet:Z,url:$.FirstURL,display_url:q1($.FirstURL),source:w1($.FirstURL)}}function Q8($){let W=[];for(let Z of $){if(Z.Topics&&Z.Topics.length>0){W.push(...Q8(Z.Topics));continue}if(Z.FirstURL&&Z.Text){let{title:Y,snippet:J}=U8(Z.Text);W.push({title:Y,snippet:J,url:Z.FirstURL,display_url:q1(Z.FirstURL),source:w1(Z.FirstURL)})}}return W}function f3($){let W=$,Z=(W.Results??[]).map((J)=>y3(J)).filter((J)=>J!==null),Y=Q8(W.RelatedTopics??[]);return[...Z,...Y]}var P3={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let W=new URL("https://duckduckgo.com/");return W.searchParams.set("q",$),W.searchParams.set("format","json"),W.searchParams.set("no_html","1"),W.searchParams.set("skip_disambig","1"),W.searchParams.set("t","blade-code"),W.searchParams.set("kl","us-en"),W.toString()},parseResponse:f3,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function S3($){let W=$,Z=[];for(let Y of W.results??[]){if(!Y.url||!Y.title)continue;Z.push({title:Y.title,snippet:Y.content||Y.title,url:Y.url,display_url:q1(Y.url),source:w1(Y.url)})}return Z}var q8=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function I3($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(Z)=>{let Y=new URL(`${$}/search`);return Y.searchParams.set("q",Z),Y.searchParams.set("format","json"),Y.searchParams.set("categories","general"),Y.toString()},parseResponse:S3,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var V$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function h3($){let W=[],Z=$.split(`
971
971
  `),Y={};for(let J=0;J<Z.length;J++){let X=Z[J].trim();if(X.startsWith("Title: ")){if(Y.title&&Y.url)W.push({title:Y.title,url:Y.url,snippet:Y.snippet||Y.title,display_url:q1(Y.url),source:w1(Y.url)});Y={title:X.substring(7).trim(),snippet:""}}else if(X.startsWith("URL: "))Y.url=X.substring(5).trim();else if(X.startsWith("Text: ")){let H=X.substring(6).trim().replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();Y.snippet=H.substring(0,300)}}if(Y.title&&Y.url)W.push({title:Y.title,url:Y.url,snippet:Y.snippet||Y.title,display_url:q1(Y.url),source:w1(Y.url)});return W}function u3(){return{name:"Exa",endpoint:`${V$.BASE_URL}${V$.ENDPOINT}`,searchFn:async($)=>{let W={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:V$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},Z=new AbortController,Y=setTimeout(()=>Z.abort(),V$.TIMEOUT);try{let J=await fetch(`${V$.BASE_URL}${V$.ENDPOINT}`,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(W),signal:Z.signal});if(clearTimeout(Y),!J.ok)throw Error(`MCP error (${J.status})`);let V=(await J.text()).split(`
972
- `);for(let H of V)if(H.startsWith("data: ")){let B=JSON.parse(H.substring(6));if(B.result&&B.result.content&&B.result.content.length>0)return h3(B.result.content[0].text)}throw Error("No search results found")}catch(J){if(clearTimeout(Y),J.name==="AbortError")throw Error("MCP request timed out");throw J}},buildUrl:()=>`${V$.BASE_URL}${V$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function w8(){let $=[];return $.push(u3()),$.push(f3),$.push(...q8.map(I3)),$}function G8(){return 2+q8.length}var g3=15000,m3=8,G1={maxRetries:3,baseDelay:1000,maxDelay:8000};function c3(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new p3($)}catch(W){console.warn(`Invalid proxy URL: ${$}`)}return}async function l3($,W,Z,Y,J){let X=new AbortController,V=setTimeout(()=>X.abort(),Z),H=()=>X.abort();Y?.addEventListener("abort",H);try{return await d3($,{...W,signal:X.signal,dispatcher:J})}catch(B){if(B.name==="AbortError")throw Error("搜索请求超时或被中止");throw B}finally{clearTimeout(V),Y?.removeEventListener("abort",H)}}async function i3($,W,Z,Y,J,X){let V=null;for(let H=0;H<G1.maxRetries;H++)try{return await l3($,W,Z,Y,J)}catch(B){if(V=B,Y?.aborted)throw B;if(H<G1.maxRetries-1){let K=Math.min(G1.baseDelay*Math.pow(2,H),G1.maxDelay);X?.(`请求失败,${K/1000}s 后重试 (${H+1}/${G1.maxRetries})...`),await new Promise((Q)=>setTimeout(Q,K))}}throw V}async function r3($,W,Z,Y,J,X){let V=K8(),H=V.get($.name,W);if(H)return X?.(`使用缓存结果 (${$.name})`),{results:H,providerName:`${$.name} (cached)`};if($.searchFn)try{X?.(`搜索中 (${$.name})...`);let F=await $.searchFn(W);return V.set($.name,W,F),{results:F,providerName:$.name}}catch(F){throw Error(`SDK search failed: ${F.message}`)}X?.(`搜索中 (${$.name})...`);let B=$.buildUrl(W),K=$.method||"GET",U={headers:$.getHeaders(),method:K};if(K==="POST"&&$.buildBody)U.body=JSON.stringify($.buildBody(W));let q=await i3(B,U,Z,Y,J,X);if(!q.ok)throw Error(`HTTP ${q.status}`);let w=await q.text(),E;try{E=JSON.parse(w)}catch{throw Error("Failed to parse search result JSON")}let G=$.parseResponse(E);return V.set($.name,W,G),{results:G,providerName:$.name}}async function n3($,W,Z,Y){let J=w8(),X=c3(),V=[];for(let H=0;H<J.length;H++){let B=J[H];if(Z?.aborted)throw Error("搜索被用户中止");try{return Y?.(`使用 ${B.name} 搜索...`),await r3(B,$,W,Z,X,Y)}catch(K){let Q=K,U=`${B.name}: ${Q.message}`;if(V.push(U),Y?.(`[WARN] ${U}`),H===J.length-1)throw Error(`所有搜索提供商都失败了:
972
+ `);for(let H of V)if(H.startsWith("data: ")){let K=JSON.parse(H.substring(6));if(K.result&&K.result.content&&K.result.content.length>0)return h3(K.result.content[0].text)}throw Error("No search results found")}catch(J){if(clearTimeout(Y),J.name==="AbortError")throw Error("MCP request timed out");throw J}},buildUrl:()=>`${V$.BASE_URL}${V$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function w8(){let $=[];return $.push(u3()),$.push(P3),$.push(...q8.map(I3)),$}function G8(){return 2+q8.length}var g3=15000,m3=8,G1={maxRetries:3,baseDelay:1000,maxDelay:8000};function c3(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new p3($)}catch(W){console.warn(`Invalid proxy URL: ${$}`)}return}async function l3($,W,Z,Y,J){let X=new AbortController,V=setTimeout(()=>X.abort(),Z),H=()=>X.abort();Y?.addEventListener("abort",H);try{return await d3($,{...W,signal:X.signal,dispatcher:J})}catch(K){if(K.name==="AbortError")throw Error("搜索请求超时或被中止");throw K}finally{clearTimeout(V),Y?.removeEventListener("abort",H)}}async function i3($,W,Z,Y,J,X){let V=null;for(let H=0;H<G1.maxRetries;H++)try{return await l3($,W,Z,Y,J)}catch(K){if(V=K,Y?.aborted)throw K;if(H<G1.maxRetries-1){let B=Math.min(G1.baseDelay*Math.pow(2,H),G1.maxDelay);X?.(`请求失败,${B/1000}s 后重试 (${H+1}/${G1.maxRetries})...`),await new Promise((U)=>setTimeout(U,B))}}throw V}async function r3($,W,Z,Y,J,X){let V=K8(),H=V.get($.name,W);if(H)return X?.(`使用缓存结果 (${$.name})`),{results:H,providerName:`${$.name} (cached)`};if($.searchFn)try{X?.(`搜索中 (${$.name})...`);let F=await $.searchFn(W);return V.set($.name,W,F),{results:F,providerName:$.name}}catch(F){throw Error(`SDK search failed: ${F.message}`)}X?.(`搜索中 (${$.name})...`);let K=$.buildUrl(W),B=$.method||"GET",Q={headers:$.getHeaders(),method:B};if(B==="POST"&&$.buildBody)Q.body=JSON.stringify($.buildBody(W));let q=await i3(K,Q,Z,Y,J,X);if(!q.ok)throw Error(`HTTP ${q.status}`);let w=await q.text(),E;try{E=JSON.parse(w)}catch{throw Error("Failed to parse search result JSON")}let G=$.parseResponse(E);return V.set($.name,W,G),{results:G,providerName:$.name}}async function n3($,W,Z,Y){let J=w8(),X=c3(),V=[];for(let H=0;H<J.length;H++){let K=J[H];if(Z?.aborted)throw Error("搜索被用户中止");try{return Y?.(`使用 ${K.name} 搜索...`),await r3(K,$,W,Z,X,Y)}catch(B){let U=B,Q=`${K.name}: ${U.message}`;if(V.push(Q),Y?.(`[WARN] ${Q}`),H===J.length-1)throw Error(`所有搜索提供商都失败了:
973
973
  ${V.join(`
974
- `)}`)}}throw Error("No search providers available")}function a3($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function o3($){return $.trim().toLowerCase()}function E8($){if(!$||$.length===0)return[];return $.map(o3).filter(Boolean)}function F8($,W){return $===W||$.endsWith(`.${W}`)}function s3($,W,Z){return $.filter((Y)=>{let J=a3(Y.url);if(!J)return!1;if(Z.length>0&&Z.some((X)=>F8(J,X)))return!1;if(W.length>0&&!W.some((X)=>F8(J,X)))return!1;return!0})}function t3($){let W=$.trim().toLowerCase();return W.length>80?W.slice(0,80):W}var oW=j({name:"WebSearch",displayName:"Web Search",kind:"readonly",isConcurrencySafe:!0,schema:l$.object({query:l$.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:l$.array(l$.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:l$.array(l$.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
974
+ `)}`)}}throw Error("No search providers available")}function a3($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function o3($){return $.trim().toLowerCase()}function E8($){if(!$||$.length===0)return[];return $.map(o3).filter(Boolean)}function F8($,W){return $===W||$.endsWith(`.${W}`)}function s3($,W,Z){return $.filter((Y)=>{let J=a3(Y.url);if(!J)return!1;if(Z.length>0&&Z.some((X)=>F8(J,X)))return!1;if(W.length>0&&!W.some((X)=>F8(J,X)))return!1;return!0})}function t3($){let W=$.trim().toLowerCase();return W.length>80?W.slice(0,80):W}var oW=N({name:"WebSearch",displayName:"Web Search",kind:"readonly",isConcurrencySafe:!0,schema:l$.object({query:l$.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:l$.array(l$.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:l$.array(l$.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
975
975
  - Search the web and use the results to inform responses
976
976
  - Provides up-to-date information for current events and recent data
977
977
  - Returns search result information formatted as search result blocks, including links as markdown hyperlinks
@@ -999,41 +999,41 @@ Usage notes:
999
999
  IMPORTANT - Use the correct year in search queries:
1000
1000
  - You MUST use the current year when searching for recent information, documentation, or current events.
1001
1001
  - Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
1002
- `},async execute($,W){let{query:Z}=$,Y=E8($.allowed_domains),J=E8($.blocked_domains),{updateOutput:X}=W,V=W.signal??new AbortController().signal;X?.(`Searching: "${Z}" (${G8()} providers available)`);try{let{results:H,providerName:B}=await n3(Z,g3,V,X),K=s3(H,Y,J),Q=K.slice(0,m3),U={query:Z,results:Q,provider:B,total_results:K.length,fetched_at:new Date().toISOString()},q={query:Z,provider:B,fetched_at:U.fetched_at,total_results:K.length,returned_results:Q.length,allowed_domains:Y,blocked_domains:J};if(Q.length===0)return{success:!0,llmContent:U,metadata:{...q,summary:`搜索 "${Z}" 找到 0 条结果`}};return{success:!0,llmContent:U,metadata:{...q,summary:`搜索 "${Z}" 找到 ${Q.length} 条结果`}}}catch(H){let B=H;return{success:!1,llmContent:`WebSearch call failed: ${B.message}`,error:{type:"execution_error",message:B.message,details:{query:Z,allowedDomains:Y,blockedDomains:J}},metadata:{summary:`搜索失败: ${B.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${t3($.query)}`,abstractPermissionRule:()=>"search:*"});import{z as E1}from"zod";function z8($){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:$}}}function sW($){let W=$.manager??N$,Z=j({name:"EnterWorktree",displayName:"Enter Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:E1.object({name:E1.string().optional().describe('Optional worktree name. Use letters, digits, dots, underscores, dashes, and optional "/" separators.')}),description:{short:"Create an isolated git worktree and switch this session into it",long:"Use only when the user explicitly asks to work in a git worktree. The worktree starts from committed HEAD; uncommitted source changes remain in the original workspace.",usageNotes:["Do not combine EnterWorktree with file or Bash tools in the same response","Wait for the worktree path, then use that path for all subsequent operations","Use ExitWorktree when the user asks to leave, keep, or remove the worktree"],important:["Never enter a worktree unless the user explicitly requested worktree isolation","A session can have only one active managed worktree"]},async execute(J,X){try{let V=X.sessionId??$.sessionId,H=await W.enter({sessionId:V,workspaceRoot:X.workspaceRoot??D(),name:J.name}),B=H.sourceHadChanges?" The original workspace has uncommitted changes; they were not copied.":"";return{success:!0,llmContent:`Created worktree ${H.worktreeRoot} on branch ${H.branch}. This session now uses ${H.workspaceRoot}.${B}`,metadata:{summary:`Entered worktree ${H.name}`,workspaceTransition:"enter",workspaceRoot:H.workspaceRoot,worktreeRoot:H.worktreeRoot,worktreeBranch:H.branch,originalWorkspaceRoot:H.originalWorkspaceRoot,sourceHadChanges:H.sourceHadChanges}}}catch(V){return z8(V instanceof Error?V.message:String(V))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(J)=>J.name??"auto",abstractPermissionRule:()=>"*"}),Y=j({name:"ExitWorktree",displayName:"Exit Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:E1.object({action:E1.enum(["keep","remove"]).describe('"keep" preserves the worktree and branch; "remove" deletes both when safe.'),discard_changes:E1.boolean().default(!1).describe("Required true to remove a worktree with uncommitted files or unmerged commits.")}),description:{short:"Exit the managed worktree for this session",long:"Only affects a worktree created by EnterWorktree in the same session. Manual or unrelated worktrees are never touched.",usageNotes:['Use action="keep" to preserve work for later','Use action="remove" only when the worktree is clean',"If removal is refused, ask the user before retrying with discard_changes=true"],important:["Never set discard_changes=true without explicit user confirmation","Removal fails closed when Git state cannot be verified"]},async execute(J,X){try{let V=X.sessionId??$.sessionId,H=await W.exit({sessionId:V,action:J.action,discardChanges:J.discard_changes,workspaceRoot:X.workspaceRoot??D()});if(H.noop)return{success:!0,llmContent:"No active managed worktree exists for this session. No files were changed.",metadata:{summary:"No active worktree",noop:!0}};return{success:!0,llmContent:H.action==="keep"?`Exited worktree and preserved it at ${H.worktreeRoot} on branch ${H.branch}. Session workspace restored to ${H.workspaceRoot}.`:`Exited and removed worktree ${H.worktreeRoot}. Session workspace restored to ${H.workspaceRoot}.`,metadata:{summary:H.action==="keep"?`Kept worktree ${H.branch}`:`Removed worktree ${H.branch}`,workspaceTransition:"exit",workspaceRoot:H.workspaceRoot,worktreeRoot:H.worktreeRoot,worktreeBranch:H.branch,removed:H.removed,discardedFiles:H.discardedFiles,discardedCommits:H.discardedCommits}}}catch(V){return z8(V instanceof Error?V.message:String(V))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(J)=>`${J.action}${J.discard_changes?":discard":""}`,abstractPermissionRule:(J)=>J.action});return[Z,Y]}async function e3(){try{return await G0.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function s1($){let W=$?.sessionId||`session_${Date.now()}`,Z=$?.configDir||O8.join(R8.homedir(),".blade"),Y=[h2,I2,p2,c2,a2,e2,WW,ZW,aW,oW,gW,mW,...lW({sessionId:W,configDir:Z}),...rW({sessionId:W,configDir:Z}),...sW({sessionId:W}),l2,r2,YW,XW,UW,wW,g2,m2,d2],J=await e3();return[...Y,...J]}import{Mutex as XY}from"async-mutex";import{nanoid as j8}from"nanoid";import{Mutex as $Y}from"async-mutex";import*as T0 from"node:fs/promises";import*as _8 from"node:path";import WY from"write-file-atomic";var H2=1,D8=8388608;function tW($,W){return $ instanceof Error&&"code"in $&&$.code===W}function ZY($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((W)=>{if(!W||typeof W!=="object"||!("type"in W))return!1;if(W.type==="text")return"text"in W&&typeof W.text==="string";return W.type==="image_url"&&"image_url"in W&&typeof W.image_url==="object"&&W.image_url!==null&&"url"in W.image_url&&typeof W.image_url.url==="string"})}function YY($,W,Z){let Y;try{Y=JSON.parse($)}catch(X){throw Error(`Invalid steering inbox JSON: ${W}`,{cause:X})}if(!Y||typeof Y!=="object"||!("version"in Y)||Y.version!==H2||!("sessionId"in Y)||Y.sessionId!==Z||!("messages"in Y)||!Array.isArray(Y.messages))throw Error(`Invalid steering inbox record: ${W}`);let J=Y.messages.map((X)=>{if(!X||typeof X!=="object"||!("id"in X)||typeof X.id!=="string"||!("content"in X)||!ZY(X.content)||!("queuedAt"in X)||typeof X.queuedAt!=="number")throw Error(`Invalid steering inbox message: ${W}`);return{id:X.id,content:X.content,queuedAt:X.queuedAt}});return{version:H2,sessionId:Z,messages:J}}function JY($){return new Set($.flatMap((W)=>W.type==="inbox_acknowledged"?W.data.messageIds:[]))}class B2{workspaceRoot;sessionId;filePath;mutex=new $Y;messages=[];constructor($,W,Z){this.workspaceRoot=$;this.sessionId=W;this.filePath=Z}static async open($,W){let Z=new B2($,W,I$($,W));return await Z.loadAndReconcile(),Z}async enqueue($,W){return this.mutex.runExclusive(async()=>{if(W&&!W(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}];return await this.persist(Z),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let W=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((Y)=>!W.has(Y.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((W)=>W.type==="text"?{...W}:{...W,image_url:{...W.image_url}})}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:H2,sessionId:this.sessionId,messages:[]};try{if((await T0.stat(this.filePath)).size>D8)throw Error(`Steering inbox exceeds ${D8} bytes: ${this.filePath}`);await T0.chmod(this.filePath,384),$=YY(await T0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(J){if(!tW(J,"ENOENT"))throw J}let W=o(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=JY(_$(await T0.readFile(W,"utf8"),W))}catch(J){if(!tW(J,"ENOENT"))throw J}let Y=$.messages.filter((J)=>!Z.has(J.id)).map((J)=>({...J,recovered:!0}));if(this.messages=Y,Y.length!==$.messages.length)await this.persist(Y)})}async persist($){if(await T0.mkdir(_8.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await T0.unlink(this.filePath).catch((Z)=>{if(!tW(Z,"ENOENT"))throw Z});return}let W={version:H2,sessionId:this.sessionId,messages:$.map(({recovered:Z,...Y})=>Y)};await WY(this.filePath,`${JSON.stringify(W)}
1003
- `,{encoding:"utf8",mode:384,fsync:!0})}}var VY=20,HY=5000000;function A8($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;return W+Z.image_url.url.length},0)}class K2{inbox;transitionMutex=new XY;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,W){return new K2(await B2.open($,W))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,W={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!W.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let Z=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";if(!await this.inbox.enqueue({id:j8(12),content:$,queuedAt:Date.now()},(J)=>J.length<VY&&J.reduce((X,V)=>X+A8(V.content),A8($))<=HY))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:Z}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let W=this.inbox.list().filter((Z)=>!this.claimed.has(Z.id));for(let Z of W)this.claimed.set(Z.id,Z);return W})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let W=this.inbox.list().filter((Z)=>!this.claimed.has(Z.id));for(let Z of W)this.claimed.set(Z.id,Z);return{messages:W,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let W of $)this.claimed.delete(W)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,W={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!W.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`)}createTurn(){let $={id:j8(12)};return this.activeTurn={id:$.id,sealed:!1},$}}import{createHash as BY,randomUUID as KY}from"node:crypto";import*as C0 from"node:fs/promises";import*as U2 from"node:path";var L8=1;function QY($,W){let Z=BY("sha256").update(W).digest("hex");return U2.join($$($),".locks",`${Z}.lock`)}function Q2($,W){return $ instanceof Error&&"code"in $&&$.code===W}async function eW($){try{let W=JSON.parse(await C0.readFile($,"utf8"));if(W.version!==L8||typeof W.sessionId!=="string"||typeof W.ownerId!=="string"||!Number.isInteger(W.pid)||(W.pid??0)<=0||typeof W.acquiredAt!=="string")return;return W}catch{return}}async function N8($){let W=await eW($);if(W)return W;return await new Promise((Z)=>setTimeout(Z,10)),eW($)}function UY($){try{return process.kill($,0),!0}catch(W){return Q2(W,"EPERM")}}async function T8($,W){let Z;try{return Z=await C0.open($,"wx",384),await Z.writeFile(`${JSON.stringify(W)}
1004
- `,"utf8"),!0}catch(Y){if(Q2(Y,"EEXIST"))return!1;if(Z)await C0.unlink($).catch(()=>{return});throw Y}finally{await Z?.close().catch(()=>{return})}}class $Z extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class F1{filePath;record;released=!1;constructor($,W){this.filePath=$;this.record=W}static async acquire($,W=D()){let Z=QY(W,$),Y={version:L8,sessionId:$,ownerId:KY(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await C0.mkdir(U2.dirname(Z),{recursive:!0,mode:448}),await T8(Z,Y))return new F1(Z,Y);let J=await N8(Z);if(J&&UY(J.pid))throw new $Z(J.pid);if(await C0.unlink(Z).catch((X)=>{if(!Q2(X,"ENOENT"))throw X}),await T8(Z,Y))return new F1(Z,Y);throw new $Z((await N8(Z))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await eW(this.filePath))?.ownerId!==this.record.ownerId)return;await C0.unlink(this.filePath).catch((W)=>{if(!Q2(W,"ENOENT"))throw W})}}var L0=P("Agent"),k8=new Map;async function wY($){let W=k8.get($);if(!W)W=(async()=>{try{let Z=await N$.cleanupStaleAgentWorktrees({workspaceRoot:$});if(Z.removed>0)L0.info(`[WorktreeGC] removed ${Z.removed} stale agent worktree(s)`);if(Z.errors.length>0)L0.warn(`[WorktreeGC] completed with ${Z.errors.length} error(s): ${Z.errors.join("; ")}`)}catch(Z){L0.warn(`[WorktreeGC] cleanup failed: ${Z instanceof Error?Z.message:String(Z)}`)}})(),k8.set($,W);await W}class e1{config;options;approvalStore=new X1;baseRegistry=new O$;attachmentCollector;activeTurnMailbox;chatService;executionEngine;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;constructor($,W){this.config=$;this.options=W;this.attachmentCollector=new e$({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){if(await n1(),await wY($.workspaceRoot??D()),W$().length===0)throw Error(`没有可用的模型配置
1002
+ `},async execute($,W){let{query:Z}=$,Y=E8($.allowed_domains),J=E8($.blocked_domains),{updateOutput:X}=W,V=W.signal??new AbortController().signal;X?.(`Searching: "${Z}" (${G8()} providers available)`);try{let{results:H,providerName:K}=await n3(Z,g3,V,X),B=s3(H,Y,J),U=B.slice(0,m3),Q={query:Z,results:U,provider:K,total_results:B.length,fetched_at:new Date().toISOString()},q={query:Z,provider:K,fetched_at:Q.fetched_at,total_results:B.length,returned_results:U.length,allowed_domains:Y,blocked_domains:J};if(U.length===0)return{success:!0,llmContent:Q,metadata:{...q,summary:`搜索 "${Z}" 找到 0 条结果`}};return{success:!0,llmContent:Q,metadata:{...q,summary:`搜索 "${Z}" 找到 ${U.length} 条结果`}}}catch(H){let K=H;return{success:!1,llmContent:`WebSearch call failed: ${K.message}`,error:{type:"execution_error",message:K.message,details:{query:Z,allowedDomains:Y,blockedDomains:J}},metadata:{summary:`搜索失败: ${K.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${t3($.query)}`,abstractPermissionRule:()=>"search:*"});import{z as E1}from"zod";function z8($){return{success:!1,llmContent:$,error:{type:"execution_error",message:$},metadata:{summary:$}}}function sW($){let W=$.manager??N$,Z=N({name:"EnterWorktree",displayName:"Enter Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:E1.object({name:E1.string().optional().describe('Optional worktree name. Use letters, digits, dots, underscores, dashes, and optional "/" separators.')}),description:{short:"Create an isolated git worktree and switch this session into it",long:"Use only when the user explicitly asks to work in a git worktree. The worktree starts from committed HEAD; uncommitted source changes remain in the original workspace.",usageNotes:["Do not combine EnterWorktree with file or Bash tools in the same response","Wait for the worktree path, then use that path for all subsequent operations","Use ExitWorktree when the user asks to leave, keep, or remove the worktree"],important:["Never enter a worktree unless the user explicitly requested worktree isolation","A session can have only one active managed worktree"]},async execute(J,X){try{let V=X.sessionId??$.sessionId,H=await W.enter({sessionId:V,workspaceRoot:X.workspaceRoot??D(),name:J.name}),K=H.sourceHadChanges?" The original workspace has uncommitted changes; they were not copied.":"";return{success:!0,llmContent:`Created worktree ${H.worktreeRoot} on branch ${H.branch}. This session now uses ${H.workspaceRoot}.${K}`,metadata:{summary:`Entered worktree ${H.name}`,workspaceTransition:"enter",workspaceRoot:H.workspaceRoot,worktreeRoot:H.worktreeRoot,worktreeBranch:H.branch,originalWorkspaceRoot:H.originalWorkspaceRoot,sourceHadChanges:H.sourceHadChanges}}}catch(V){return z8(V instanceof Error?V.message:String(V))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(J)=>J.name??"auto",abstractPermissionRule:()=>"*"}),Y=N({name:"ExitWorktree",displayName:"Exit Worktree",kind:"execute",isConcurrencySafe:!1,strict:!0,schema:E1.object({action:E1.enum(["keep","remove"]).describe('"keep" preserves the worktree and branch; "remove" deletes both when safe.'),discard_changes:E1.boolean().default(!1).describe("Required true to remove a worktree with uncommitted files or unmerged commits.")}),description:{short:"Exit the managed worktree for this session",long:"Only affects a worktree created by EnterWorktree in the same session. Manual or unrelated worktrees are never touched.",usageNotes:['Use action="keep" to preserve work for later','Use action="remove" only when the worktree is clean',"If removal is refused, ask the user before retrying with discard_changes=true"],important:["Never set discard_changes=true without explicit user confirmation","Removal fails closed when Git state cannot be verified"]},async execute(J,X){try{let V=X.sessionId??$.sessionId,H=await W.exit({sessionId:V,action:J.action,discardChanges:J.discard_changes,workspaceRoot:X.workspaceRoot??D()});if(H.noop)return{success:!0,llmContent:"No active managed worktree exists for this session. No files were changed.",metadata:{summary:"No active worktree",noop:!0}};return{success:!0,llmContent:H.action==="keep"?`Exited worktree and preserved it at ${H.worktreeRoot} on branch ${H.branch}. Session workspace restored to ${H.workspaceRoot}.`:`Exited and removed worktree ${H.worktreeRoot}. Session workspace restored to ${H.workspaceRoot}.`,metadata:{summary:H.action==="keep"?`Kept worktree ${H.branch}`:`Removed worktree ${H.branch}`,workspaceTransition:"exit",workspaceRoot:H.workspaceRoot,worktreeRoot:H.worktreeRoot,worktreeBranch:H.branch,removed:H.removed,discardedFiles:H.discardedFiles,discardedCommits:H.discardedCommits}}}catch(V){return z8(V instanceof Error?V.message:String(V))}},version:"1.0.0",category:"工作区工具",tags:["git","worktree","isolation"],extractSignatureContent:(J)=>`${J.action}${J.discard_changes?":discard":""}`,abstractPermissionRule:(J)=>J.action});return[Z,Y]}async function e3(){try{return await G0.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function s1($){let W=$?.sessionId||`session_${Date.now()}`,Z=$?.configDir||O8.join(R8.homedir(),".blade"),Y=[h2,I2,p2,c2,a2,e2,WW,ZW,aW,oW,gW,mW,...lW({sessionId:W,configDir:Z}),...rW({sessionId:W,configDir:Z}),...sW({sessionId:W}),l2,r2,YW,XW,QW,wW,g2,m2,d2],J=await e3();return[...Y,...J]}import{Mutex as XY}from"async-mutex";import{nanoid as j8}from"nanoid";import{Mutex as $Y}from"async-mutex";import*as T0 from"node:fs/promises";import*as D8 from"node:path";import WY from"write-file-atomic";var H2=1,_8=8388608;function tW($,W){return $ instanceof Error&&"code"in $&&$.code===W}function ZY($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((W)=>{if(!W||typeof W!=="object"||!("type"in W))return!1;if(W.type==="text")return"text"in W&&typeof W.text==="string";return W.type==="image_url"&&"image_url"in W&&typeof W.image_url==="object"&&W.image_url!==null&&"url"in W.image_url&&typeof W.image_url.url==="string"})}function YY($,W,Z){let Y;try{Y=JSON.parse($)}catch(X){throw Error(`Invalid steering inbox JSON: ${W}`,{cause:X})}if(!Y||typeof Y!=="object"||!("version"in Y)||Y.version!==H2||!("sessionId"in Y)||Y.sessionId!==Z||!("messages"in Y)||!Array.isArray(Y.messages))throw Error(`Invalid steering inbox record: ${W}`);let J=Y.messages.map((X)=>{if(!X||typeof X!=="object"||!("id"in X)||typeof X.id!=="string"||!("content"in X)||!ZY(X.content)||!("queuedAt"in X)||typeof X.queuedAt!=="number")throw Error(`Invalid steering inbox message: ${W}`);return{id:X.id,content:X.content,queuedAt:X.queuedAt}});return{version:H2,sessionId:Z,messages:J}}function JY($){return new Set($.flatMap((W)=>W.type==="inbox_acknowledged"?W.data.messageIds:[]))}class B2{workspaceRoot;sessionId;filePath;mutex=new $Y;messages=[];constructor($,W,Z){this.workspaceRoot=$;this.sessionId=W;this.filePath=Z}static async open($,W){let Z=new B2($,W,I$($,W));return await Z.loadAndReconcile(),Z}async enqueue($,W){return this.mutex.runExclusive(async()=>{if(W&&!W(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}];return await this.persist(Z),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let W=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((Y)=>!W.has(Y.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((W)=>W.type==="text"?{...W}:{...W,image_url:{...W.image_url}})}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:H2,sessionId:this.sessionId,messages:[]};try{if((await T0.stat(this.filePath)).size>_8)throw Error(`Steering inbox exceeds ${_8} bytes: ${this.filePath}`);await T0.chmod(this.filePath,384),$=YY(await T0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(J){if(!tW(J,"ENOENT"))throw J}let W=o(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=JY(D$(await T0.readFile(W,"utf8"),W))}catch(J){if(!tW(J,"ENOENT"))throw J}let Y=$.messages.filter((J)=>!Z.has(J.id)).map((J)=>({...J,recovered:!0}));if(this.messages=Y,Y.length!==$.messages.length)await this.persist(Y)})}async persist($){if(await T0.mkdir(D8.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await T0.unlink(this.filePath).catch((Z)=>{if(!tW(Z,"ENOENT"))throw Z});return}let W={version:H2,sessionId:this.sessionId,messages:$.map(({recovered:Z,...Y})=>Y)};await WY(this.filePath,`${JSON.stringify(W)}
1003
+ `,{encoding:"utf8",mode:384,fsync:!0})}}var VY=20,HY=5000000;function A8($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;return W+Z.image_url.url.length},0)}class K2{inbox;transitionMutex=new XY;activeTurn;claimed=new Map;constructor($){this.inbox=$}static async create($,W){return new K2(await B2.open($,W))}beginTurn(){if(this.activeTurn)throw Error(`Session already has an active turn: ${this.activeTurn.id}`);return this.createTurn()}async enqueue($,W={}){return this.transitionMutex.runExclusive(async()=>{if(!this.activeTurn&&!W.allowBeforeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"no_active_turn"};let Z=this.activeTurn&&!this.activeTurn.sealed?"current_turn":"next_turn";return this.enqueueDurably($,Z)})}async prepareInputTurn($){return this.transitionMutex.runExclusive(async()=>{if(this.activeTurn)return{accepted:!1,queued:this.inbox.count(),reason:"turn_active"};let W=this.inbox.count()>0,Z=await this.enqueueDurably($,"next_turn");if(!Z.accepted||!Z.messageId)return{accepted:!1,queued:Z.queued,reason:"queue_full"};let Y=this.createTurn();if(!W){let J=this.inbox.list().find((X)=>X.id===Z.messageId);if(!J)throw this.activeTurn=void 0,Error(`Prepared input disappeared from inbox: ${Z.messageId}`);this.claimed.set(J.id,J)}return{accepted:!0,handle:Y,messageId:Z.messageId,queued:Z.queued,mode:W?"pending":"direct"}})}async drain($){return this.transitionMutex.runExclusive(()=>{this.assertOwner($);let W=this.inbox.list().filter((Z)=>!this.claimed.has(Z.id));for(let Z of W)this.claimed.set(Z.id,Z);return W})}async drainOrSeal($){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.inbox.count()>this.claimed.size){let W=this.inbox.list().filter((Z)=>!this.claimed.has(Z.id));for(let Z of W)this.claimed.set(Z.id,Z);return{messages:W,sealed:!1}}return this.activeTurn.sealed=!0,{messages:[],sealed:!0}})}async acknowledge($){await this.inbox.acknowledge($);for(let W of $)this.claimed.delete(W)}async claimedMessageIds($){return this.transitionMutex.runExclusive(()=>{return this.assertOwner($),[...this.claimed.keys()]})}async finishTurn($,W={}){return this.transitionMutex.runExclusive(()=>{if(this.assertOwner($),this.activeTurn=void 0,this.claimed.clear(),!W.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($,W){let Z={id:j8(12),content:$,queuedAt:Date.now()};if(!await this.inbox.enqueue(Z,(J)=>{if(J.length>=VY)return!1;return J.reduce((V,H)=>V+A8(H.content),0)+A8($)<=HY}))return{accepted:!1,turnId:this.activeTurn?.id,queued:this.inbox.count(),reason:"queue_full"};return{accepted:!0,messageId:Z.id,turnId:this.activeTurn?.id,queued:this.inbox.count(),delivery:W}}createTurn(){let $={id:j8(12)};return this.activeTurn={id:$.id,sealed:!1},$}}import{createHash as BY,randomUUID as KY}from"node:crypto";import*as C0 from"node:fs/promises";import*as Q2 from"node:path";var L8=1;function UY($,W){let Z=BY("sha256").update(W).digest("hex");return Q2.join($$($),".locks",`${Z}.lock`)}function U2($,W){return $ instanceof Error&&"code"in $&&$.code===W}async function eW($){try{let W=JSON.parse(await C0.readFile($,"utf8"));if(W.version!==L8||typeof W.sessionId!=="string"||typeof W.ownerId!=="string"||!Number.isInteger(W.pid)||(W.pid??0)<=0||typeof W.acquiredAt!=="string")return;return W}catch{return}}async function N8($){let W=await eW($);if(W)return W;return await new Promise((Z)=>setTimeout(Z,10)),eW($)}function QY($){try{return process.kill($,0),!0}catch(W){return U2(W,"EPERM")}}async function T8($,W){let Z;try{return Z=await C0.open($,"wx",384),await Z.writeFile(`${JSON.stringify(W)}
1004
+ `,"utf8"),!0}catch(Y){if(U2(Y,"EEXIST"))return!1;if(Z)await C0.unlink($).catch(()=>{return});throw Y}finally{await Z?.close().catch(()=>{return})}}class $Z extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class F1{filePath;record;released=!1;constructor($,W){this.filePath=$;this.record=W}static async acquire($,W=D()){let Z=UY(W,$),Y={version:L8,sessionId:$,ownerId:KY(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await C0.mkdir(Q2.dirname(Z),{recursive:!0,mode:448}),await T8(Z,Y))return new F1(Z,Y);let J=await N8(Z);if(J&&QY(J.pid))throw new $Z(J.pid);if(await C0.unlink(Z).catch((X)=>{if(!U2(X,"ENOENT"))throw X}),await T8(Z,Y))return new F1(Z,Y);throw new $Z((await N8(Z))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await eW(this.filePath))?.ownerId!==this.record.ownerId)return;await C0.unlink(this.filePath).catch((W)=>{if(!U2(W,"ENOENT"))throw W})}}var L0=f("Agent"),k8=new Map;async function wY($){let W=k8.get($);if(!W)W=(async()=>{try{let Z=await N$.cleanupStaleAgentWorktrees({workspaceRoot:$});if(Z.removed>0)L0.info(`[WorktreeGC] removed ${Z.removed} stale agent worktree(s)`);if(Z.errors.length>0)L0.warn(`[WorktreeGC] completed with ${Z.errors.length} error(s): ${Z.errors.join("; ")}`)}catch(Z){L0.warn(`[WorktreeGC] cleanup failed: ${Z instanceof Error?Z.message:String(Z)}`)}})(),k8.set($,W);await W}class e1{config;options;approvalStore=new X1;baseRegistry=new O$;attachmentCollector;activeTurnMailbox;chatService;executionEngine;currentModelId;currentModelMaxContextTokens;initialized=!1;sessionLease;sessionMcpRegistry;constructor($,W){this.config=$;this.options=W;this.attachmentCollector=new e$({cwd:this.workspaceRoot,maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){if(await n1(),await wY($.workspaceRoot??D()),W$().length===0)throw Error(`没有可用的模型配置
1005
1005
 
1006
1006
  `+`请先使用以下命令添加模型:
1007
1007
  `+` /model add
1008
1008
 
1009
1009
  `+`或运行初始化向导:
1010
- `+" /init");let Z=Y0();if(!Z)throw Error("配置未初始化,请确保应用已正确启动");r1.getInstance().validateConfig(Z);let Y=new e1(Z,$);return await Y.initialize(),Y}static async hasPendingInbox($,W){try{return(await qY(I$($,W))).size>0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??D()}getConfig(){return this.config}getChatService(){return this.chatService}getExecutionEngine(){return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getCurrentModelMaxContextTokens(){return this.currentModelMaxContextTokens}beginTurn(){return this.activeTurnMailbox.beginTurn()}async enqueueSteering($,W){return this.activeTurnMailbox.enqueue($,W)}async drainSteering($){return this.activeTurnMailbox.drain($)}async drainSteeringOrSeal($){return this.activeTurnMailbox.drainOrSeal($)}async acknowledgeTurn($){let W=await this.activeTurnMailbox.claimedMessageIds($);if(W.length===0)return;await this.executionEngine.getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,W),await this.activeTurnMailbox.acknowledge(W)}async finishTurn($,W){return this.activeTurnMailbox.finishTurn($,W)}async beginPendingTurn(){return this.activeTurnMailbox.beginPendingTurn()}hasActiveTurn(){return this.activeTurnMailbox.isActive()}hasTurnOwner(){return this.activeTurnMailbox.hasTurnOwner()}getPendingSteeringCount(){return this.activeTurnMailbox.pendingCount()}getPendingSteeringMessages(){return this.activeTurnMailbox.pendingMessages()}getRecoveredSteeringCount(){return this.activeTurnMailbox.recoveredCount()}async initialize(){if(this.initialized)return;this.sessionLease=await F1.acquire(this.sessionId,this.workspaceRoot);try{await this.validateSystemPromptConfig(),this.activeTurnMailbox=await K2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills(),await this.applyModelConfig(this.resolveModelConfig(this.options.modelId),"使用模型:"),await this.executionEngine.getContextManager().persistentStore.initSession(this.sessionId),this.initialized=!0,L0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.sessionMcpRegistry?.disconnectAll()}finally{this.sessionMcpRegistry=void 0,await this.sessionLease.release(),this.sessionLease=void 0}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let W=$.modelId&&$.modelId!=="inherit"?$.modelId:j0()?.id;if(W&&W!==this.currentModelId)await this.applyModelConfig(this.resolveModelConfig(W),"切换模型")}createToolExecutor($={}){let W=new O$,Z=$.toolWhitelist?new Set($.toolWhitelist):null,Y=$.toolBlacklist?new Set($.toolBlacklist):null;for(let V of this.baseRegistry.getBuiltinTools()){if(Y?.has(V.name))continue;if(!Z||Z.has(V.name))W.register(V)}for(let V of this.baseRegistry.getMcpTools()){if(Y?.has(V.name))continue;if(!Z||Z.has(V.name))W.registerMcpTool(V)}let J={...this.config.permissions,...$.permissions},X=$.permissionMode??this.config.permissionMode??"default";return new V1(W,{permissionConfig:J,permissionMode:X,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){try{await $0.getInstance().killSession(this.sessionId),this.approvalStore.clear(),N$.releaseSession(this.sessionId),await this.chatService?.dispose?.()}finally{try{await this.sessionMcpRegistry?.disconnectAll()}finally{this.sessionMcpRegistry=void 0;try{await this.sessionLease?.release()}finally{this.sessionLease=void 0,this.currentModelId=void 0,this.initialized=!1}}}}resolveModelConfig($){let W=$&&$!=="inherit"?$:void 0,Z=W?K1(W):j0();if(!Z)throw Error(`模型配置未找到: ${W??"current"}`);return Z}async applyModelConfig($,W){L0.debug(`${W} ${$.name} (${$.model})`);let Z=c1($),Y=a1(),J=Z&&Y,X=$.maxContextTokens??this.config.maxContextTokens,V=await o1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:X,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:$.timeout??this.config.timeout,supportsThinking:J,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries}),H=this.initialized?this.chatService:void 0,B=this.executionEngine?.getContextManager();this.chatService=V,this.executionEngine=new B1(V,B,this.workspaceRoot),this.currentModelMaxContextTokens=X,this.currentModelId=$.id;let K=H;try{await K?.dispose?.()}catch(Q){L0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,Q)}}async validateSystemPromptConfig(){try{await q$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language})}catch($){L0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let W=(await s1({sessionId:this.sessionId,configDir:M8.join(b8.homedir(),".blade")})).filter((Z)=>!Z.name.startsWith("mcp__"));this.baseRegistry.registerAll(W),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers!==void 0;if(!$&&this.options.mcpConfig&&this.options.mcpConfig.length>0)await M1(this.options.mcpConfig);let W=$?this.options.mcpServers??{}:k0();if(Object.keys(W).length===0)return;let Z=$?G0.createIsolated():G0.getInstance();if($)this.sessionMcpRegistry=Z;for(let[J,X]of Object.entries(W))try{await Z.registerServer(J,X)}catch(V){L0.warn(`Warning: MCP server "${J}" connection failed:`,V)}let Y=await Z.getAvailableTools();for(let J of Y)this.baseRegistry.registerMcpTool(J)}catch($){L0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){try{if(f.getAllNames().length===0)f.loadFromStandardLocations();if(this.options.agents?.length)f.applyOverrides(this.options.agents)}catch($){L0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await u$({cwd:this.workspaceRoot})}catch($){L0.warn("Failed to discover skills:",$)}}}import*as F0 from"node:fs/promises";import{homedir as OY}from"node:os";import*as i from"node:path";import S8 from"gray-matter";function q2($,W){return`${$}:${W}`}function v8($,W){return`${$}__${W}`}import*as w2 from"node:fs/promises";import*as P8 from"node:path";import{z as T}from"zod";var GY=T.string().min(2,"Plugin name must be at least 2 characters").max(64,"Plugin name must be at most 64 characters").regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$/,{message:"Plugin name must be lowercase letters, numbers, and hyphens only, starting and ending with alphanumeric"}),EY=T.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),FY=T.object({name:T.string().min(1,"Author name is required"),email:T.string().email().optional(),url:T.string().url().optional()}),C8=T.object({name:GY,description:T.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:EY,author:FY.optional(),license:T.string().optional(),repository:T.string().url().optional(),homepage:T.string().url().optional(),keywords:T.array(T.string()).optional(),dependencies:T.record(T.string()).optional(),bladeVersion:T.string().optional()}),x8=T.object({type:T.enum(["stdio","sse","http"]),command:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional(),url:T.string().url().optional(),headers:T.record(T.string()).optional(),timeout:T.number().positive().optional(),oauth:T.object({enabled:T.boolean().optional(),clientId:T.string().optional(),clientSecret:T.string().optional(),authorizationUrl:T.string().url().optional(),tokenUrl:T.string().url().optional(),scopes:T.array(T.string()).optional(),redirectUri:T.string().url().optional()}).optional(),healthCheck:T.object({enabled:T.boolean().optional(),interval:T.number().positive().optional(),timeout:T.number().positive().optional(),failureThreshold:T.number().positive().optional()}).optional()}),zY=T.union([T.object({mcpServers:T.record(x8)}),T.record(x8)]);function y8($){return zY.safeParse($)}var RY=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function i$($){for(let{dir:W,source:Z}of RY){let Y=P8.join($,W,"plugin.json");try{await w2.access(Y)}catch{continue}try{let J=await w2.readFile(Y,"utf-8"),X=JSON.parse(J),V=C8.safeParse(X);if(!V.success){let H=V.error.issues.map((B)=>`${B.path.join(".")}: ${B.message}`).join("; ");throw Error(`Invalid plugin.json: ${H}`)}return S.debug(`Parsed plugin manifest from ${Y}`),{manifest:V.data,source:Z,manifestPath:Y}}catch(J){if(J instanceof SyntaxError)throw Error(`Invalid JSON in ${Y}: ${J.message}`);throw J}}return null}async function f8($){try{return await i$($)!==null}catch{return!1}}class G2{async loadPlugin($,W,Z={}){let Y=await i$($);if(!Y)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:J,source:X}=Y,V=J.name;S.debug(`Loading plugin "${V}" from ${$}`);let H=Z.skipCommands?[]:await this.loadCommands($,V),B=Z.skipAgents?[]:await this.loadAgents($,V),K=Z.skipSkills?[]:await this.loadSkills($,V),Q=Z.skipHooks?void 0:await this.loadHooks($),U=Z.skipMcp?void 0:await this.loadMcpConfig($,V);return S.debug(`Plugin "${V}" loaded: ${H.length} commands, ${B.length} agents, ${K.length} skills`),{manifest:J,basePath:$,source:W,manifestSource:X,commands:H,agents:B,skills:K,hooks:Q,mcpServers:U,status:"active",loadedAt:new Date}}async loadCommands($,W){let Z=i.join($,"commands"),Y=[];if(!await this.dirExists(Z))return Y;let J=await this.scanMarkdownFiles(Z);for(let X of J)try{let V=await this.parseCommandFile(X,Z,W);if(V)Y.push(V)}catch(V){S.warn(`Failed to load command from ${X}: ${V instanceof Error?V.message:String(V)}`)}return Y}async parseCommandFile($,W,Z){let Y=await F0.readFile($,"utf-8"),{data:J,content:X}=S8(Y),H=i.relative(W,$).split(i.sep),B=H.pop();if(!B)return null;let K=B.replace(/\.md$/i,""),Q=K;if(H.length>0)Q=[...H,K].join("/");let U=q2(Z,Q),q=this.normalizeCommandConfig(J);return{originalName:Q,namespacedName:U,pluginName:Z,config:q,content:X.trim(),path:$}}normalizeCommandConfig($){return{description:this.asString($.description),allowedTools:this.parseStringArray($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}async loadAgents($,W){let Z=i.join($,"agents"),Y=[];if(!await this.dirExists(Z))return Y;let J=await this.scanMarkdownFiles(Z);for(let X of J)try{let V=await this.parseAgentFile(X,Z,W);if(V)Y.push(V)}catch(V){S.warn(`Failed to load agent from ${X}: ${V instanceof Error?V.message:String(V)}`)}return Y}async parseAgentFile($,W,Z){let Y=await F0.readFile($,"utf-8"),{data:J,content:X}=S8(Y),V=i.relative(W,$),H=i.basename(V,".md"),B=J.name||H,K=q2(Z,B),Q={name:K,description:this.asString(J.description)||"",tools:this.parseStringArray(J.tools),color:this.asString(J.color),model:this.asString(J.model),permissionMode:this.asString(J.permissionMode),skills:this.parseStringArray(J.skills),systemPrompt:X.trim(),source:`plugin:${Z}`};return{originalName:B,namespacedName:K,pluginName:Z,config:Q,path:$}}async loadSkills($,W){let Z=i.join($,"skills"),Y=[];if(!await this.dirExists(Z))return Y;let J=await F0.readdir(Z,{withFileTypes:!0});for(let X of J){if(!X.isDirectory())continue;let V=i.join(Z,X.name),H=i.join(V,"SKILL.md");try{let B=await I8(H,"project");if(B.success&&B.content){let K=B.content.metadata.name,Q=q2(W,K);Y.push({originalName:K,namespacedName:Q,pluginName:W,metadata:{...B.content.metadata,name:Q},path:V})}}catch(B){S.warn(`Failed to load skill from ${H}: ${B instanceof Error?B.message:String(B)}`)}}return Y}async loadHooks($){let W=i.join($,"hooks","hooks.json");try{let Z=await F0.readFile(W,"utf-8"),Y=JSON.parse(Z);return Y.hooks||Y}catch{return}}async loadMcpConfig($,W){let Z=i.join($,".mcp.json");try{let Y=await F0.readFile(Z,"utf-8"),J=JSON.parse(Y),X=y8(J);if(!X.success){S.warn(`Invalid .mcp.json in ${$}: ${X.error}`);return}let V="mcpServers"in J?J.mcpServers:J,H={};for(let[B,K]of Object.entries(V)){let Q=v8(W,B);H[Q]=K}return H}catch{return}}async scanMarkdownFiles($){let W=[],Z=async(Y)=>{let J=await F0.readdir(Y,{withFileTypes:!0});for(let X of J){let V=i.join(Y,X.name);if(X.isDirectory())await Z(V);else if(X.name.endsWith(".md"))W.push(V)}};return await Z($),W}async dirExists($){try{return(await F0.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((W)=>String(W).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((W)=>W.trim()).filter(Boolean);return}static getPluginDirs($){let W=OY();return[{path:i.join(W,".claude","plugins"),source:"user",type:"claude"},{path:i.join(W,".blade","plugins"),source:"user",type:"blade"},{path:i.join($,".claude","plugins"),source:"project",type:"claude"},{path:i.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,W){let Z=[],Y=[];try{await F0.access($)}catch{return{plugins:Z,errors:Y}}let J=await F0.readdir($,{withFileTypes:!0});for(let X of J){if(!X.isDirectory())continue;let V=i.join($,X.name);try{let H=await this.loadPlugin(V,W);Z.push(H)}catch(H){Y.push({path:V,error:H instanceof Error?H.message:String(H)})}}return{plugins:Z,errors:Y}}}class b${static instance=null;plugins=new Map;loader=new G2;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}static resetInstance(){b$.instance=null}async initialize($,W=[]){this.workspaceRoot=$,this.cliPluginDirs=W;let Z=[],Y=[];for(let X of W)try{let V=await this.loader.loadPlugin(X,"cli");this.plugins.set(V.manifest.name,V),Z.push(V),S.info(`Loaded CLI plugin: ${V.manifest.name} from ${X}`)}catch(V){Y.push({path:X,error:V instanceof Error?V.message:String(V)}),S.warn(`Failed to load CLI plugin from ${X}: ${V}`)}let J=G2.getPluginDirs($);for(let{path:X,source:V}of J){let H=await this.loader.discoverPluginsInDir(X,V);for(let B of H.plugins){let K=this.plugins.get(B.manifest.name);if(!K||K.source!=="cli")this.plugins.set(B.manifest.name,B),Z.push(B)}Y.push(...H.errors)}return this.initialized=!0,S.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Y.length>0?`, ${Y.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Y}}isInitialized(){return this.initialized}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter(($)=>$.status==="active")}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getBySource(){let $={cli:[],project:[],user:[]};for(let W of this.plugins.values())$[W.source].push(W);return $}getAllCommands(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.commands);return $}getAllSkills(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.skills);return $}getAllAgents(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.agents);return $}findCommand($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}findSkill($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.skills)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.skills)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}findAgent($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.agents)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.agents)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}hasCommandConflict($){let W=0;for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$){if(W++,W>1)return!0}}return!1}getCommandProviders($){let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$){W.push(Z.manifest.name);break}}return W}disable($){let W=this.plugins.get($);if(W&&W.status==="active")return W.status="inactive",S.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let W=this.plugins.get($);if(W&&W.status==="inactive")return W.status="active",S.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return S.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let $=0,W=0,Z=0,Y=0,J=0;for(let X of this.plugins.values())if(X.status==="active")$++,Z+=X.commands.length,Y+=X.skills.length,J+=X.agents.length;else W++;return{total:this.plugins.size,active:$,inactive:W,commands:Z,skills:Y,agents:J}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let W=[],Z=this.getBySource();if(Z.cli.length>0){W.push("## CLI 指定的插件");for(let Y of Z.cli){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}W.push("")}if(Z.project.length>0){W.push("## 项目级插件");for(let Y of Z.project){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}W.push("")}if(Z.user.length>0){W.push("## 用户级插件");for(let Y of Z.user){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}}return W.join(`
1011
- `)}}function m0(){return b$.getInstance()}class WZ{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=r.getInstance(),this.hookManager=w0.getInstance(),this.mcpRegistry=G0.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),Q0().clearPluginSkills(),f.clearPluginAgents(),S.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let W=m0().getActive(),Z=[],Y=[],J=0,X=0,V=0,H=0;for(let B of W){let K=await this.integratePlugin(B);Z.push(K),J+=K.commandsRegistered,X+=K.skillsRegistered,V+=K.agentsRegistered,H+=K.mcpServersRegistered,Y.push(...K.errors)}if(J+X+V>0)S.info(`Plugin integration complete: ${J} commands, ${X} skills, ${V} agents, ${H} MCP servers`);return{plugins:Z,totalCommands:J,totalSkills:X,totalAgents:V,totalMcpServers:H,errors:Y}}async integratePlugin($){let W={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{W.commandsRegistered=this.integrateCommands($)}catch(Z){W.errors.push(`Failed to integrate commands: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.skillsRegistered=this.integrateSkills($)}catch(Z){W.errors.push(`Failed to integrate skills: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.agentsRegistered=this.integrateAgents($)}catch(Z){W.errors.push(`Failed to integrate agents: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.hooksRegistered=this.integrateHooks($)}catch(Z){W.errors.push(`Failed to integrate hooks: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.mcpServersRegistered=await this.integrateMcp($)}catch(Z){W.errors.push(`Failed to integrate MCP servers: ${Z instanceof Error?Z.message:String(Z)}`)}return S.debug(`Integrated plugin "${$.manifest.name}": ${W.commandsRegistered} commands, ${W.skillsRegistered} skills, ${W.agentsRegistered} agents`),W}integrateCommands($){let W=0;for(let Z of $.commands)this.commandRegistry.registerPluginCommand(Z),W++;return W}integrateSkills($){let W=Q0(),Z=0;for(let Y of $.skills)W.registerPluginSkill(Y),Z++;return Z}integrateAgents($){let W=0;for(let Z of $.agents)f.register({...Z.config,name:Z.namespacedName}),W++;return W}integrateHooks($){if(!$.hooks)return!1;let W=this.hookManager.getConfig();return this.hookManager.loadConfig({...W,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let W=0;for(let[Z,Y]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(Z,Y),W++}catch(J){S.warn(`Failed to register MCP server "${Z}" from plugin "${$.manifest.name}": ${J instanceof Error?J.message:String(J)}`)}return W}}async function E2(){return new WZ().integrateAll()}function F2(){new WZ().clearAllPluginResources()}import{execSync as h8}from"node:child_process";import*as X0 from"node:fs/promises";import{homedir as DY}from"node:os";import*as r$ from"node:path";class u8{userPluginsDir;constructor($){this.userPluginsDir=$||r$.join(DY(),".blade","plugins")}async install($){try{let W=this.parseGitUrl($);if(!W)return{success:!1,error:`Invalid source URL: ${$}`};let Z=this.extractPluginName(W);if(!Z)return{success:!1,error:`Could not extract plugin name from URL: ${W}`};await X0.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let Y=r$.join(this.userPluginsDir,Z);try{return await X0.access(Y),{success:!1,pluginName:Z,pluginPath:Y,error:`Plugin "${Z}" already exists at ${Y}. Use /plugins uninstall first.`}}catch{}S.info(`Cloning ${W} to ${Y}...`);try{h8(`git clone --depth 1 "${W}" "${Y}"`,{stdio:"pipe",timeout:60000})}catch(X){return{success:!1,pluginName:Z,error:`Failed to clone repository: ${X instanceof Error?X.message:String(X)}`}}if(!await f8(Y))return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let J;try{J=await i$(Y)}catch(X){return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:`Invalid plugin manifest: ${X instanceof Error?X.message:String(X)}`}}if(!J)return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:"Invalid plugin manifest: No manifest found"};return S.info(`Successfully installed plugin: ${J.manifest.name}`),{success:!0,pluginName:J.manifest.name,pluginPath:Y,manifest:J.manifest}}catch(W){return{success:!1,error:`Installation failed: ${W instanceof Error?W.message:String(W)}`}}}async uninstall($){try{let W=r$.join(this.userPluginsDir,$);try{await X0.access(W)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${W}`}}return await X0.rm(W,{recursive:!0,force:!0}),S.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:W}}catch(W){return{success:!1,pluginName:$,error:`Uninstallation failed: ${W instanceof Error?W.message:String(W)}`}}}async listInstalled(){try{return await X0.access(this.userPluginsDir),(await X0.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((W)=>W.isDirectory()).map((W)=>W.name)}catch{return[]}}async update($){try{let W=r$.join(this.userPluginsDir,$);try{await X0.access(W)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${W}`}}let Z=r$.join(W,".git");try{await X0.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}S.info(`Updating plugin: ${$}...`);try{h8(`git -C "${W}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(J){return{success:!1,pluginName:$,error:`Failed to update: ${J instanceof Error?J.message:String(J)}`}}let Y;try{Y=await i$(W)}catch(J){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${J instanceof Error?J.message:String(J)}`}}if(!Y)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return S.info(`Successfully updated plugin: ${Y.manifest.name}`),{success:!0,pluginName:Y.manifest.name,pluginPath:W,manifest:Y.manifest}}catch(W){return{success:!1,pluginName:$,error:`Update failed: ${W instanceof Error?W.message:String(W)}`}}}parseGitUrl($){if($.startsWith("https://")||$.startsWith("git@"))return $;if(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/.test($))return`https://github.com/${$}.git`;return null}extractPluginName($){let W=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(W)return W[1];let Z=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[2];return null}}var ZZ=null;function z1($){if(!ZZ)ZZ=new u8($);return ZZ}import dJ from"fuse.js";import Z6 from"node:fs/promises";import Y6 from"node:path";import _Y from"node:os";import p8 from"node:path";function C($){if($.acp)return{sendMessage:(W)=>$.acp.sendMessage(`• ${W}
1010
+ `+" /init");let Z=Y0();if(!Z)throw Error("配置未初始化,请确保应用已正确启动");r1.getInstance().validateConfig(Z);let Y=new e1(Z,$);return await Y.initialize(),Y}static async hasPendingInbox($,W){try{return(await qY(I$($,W))).size>0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}get sessionId(){return this.options.sessionId}get workspaceRoot(){return this.options.workspaceRoot??D()}getConfig(){return this.config}getChatService(){return this.chatService}getExecutionEngine(){return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getCurrentModelMaxContextTokens(){return this.currentModelMaxContextTokens}beginTurn(){return this.activeTurnMailbox.beginTurn()}async prepareInputTurn($){return this.activeTurnMailbox.prepareInputTurn($)}async enqueueSteering($,W){return this.activeTurnMailbox.enqueue($,W)}async drainSteering($){return this.activeTurnMailbox.drain($)}async drainSteeringOrSeal($){return this.activeTurnMailbox.drainOrSeal($)}async acknowledgeTurn($){let W=await this.activeTurnMailbox.claimedMessageIds($);if(W.length===0)return;await this.executionEngine.getContextManager().persistentStore.acknowledgeInboxMessages(this.sessionId,W),await this.activeTurnMailbox.acknowledge(W)}async finishTurn($,W){return this.activeTurnMailbox.finishTurn($,W)}async beginPendingTurn(){return this.activeTurnMailbox.beginPendingTurn()}hasActiveTurn(){return this.activeTurnMailbox.isActive()}hasTurnOwner(){return this.activeTurnMailbox.hasTurnOwner()}getPendingSteeringCount(){return this.activeTurnMailbox.pendingCount()}getPendingSteeringMessages(){return this.activeTurnMailbox.pendingMessages()}getRecoveredSteeringCount(){return this.activeTurnMailbox.recoveredCount()}async initialize(){if(this.initialized)return;this.sessionLease=await F1.acquire(this.sessionId,this.workspaceRoot);try{await this.validateSystemPromptConfig(),this.activeTurnMailbox=await K2.create(this.workspaceRoot,this.sessionId),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills(),await this.applyModelConfig(this.resolveModelConfig(this.options.modelId),"使用模型:"),await this.executionEngine.getContextManager().persistentStore.initSession(this.sessionId),this.initialized=!0,L0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}catch($){try{await this.sessionMcpRegistry?.disconnectAll()}finally{this.sessionMcpRegistry=void 0,await this.sessionLease.release(),this.sessionLease=void 0}throw $}}async refresh($){if(!this.initialized){await this.initialize();return}let W=$.modelId&&$.modelId!=="inherit"?$.modelId:j0()?.id;if(W&&W!==this.currentModelId)await this.applyModelConfig(this.resolveModelConfig(W),"切换模型")}createToolExecutor($={}){let W=new O$,Z=$.toolWhitelist?new Set($.toolWhitelist):null,Y=$.toolBlacklist?new Set($.toolBlacklist):null;for(let V of this.baseRegistry.getBuiltinTools()){if(Y?.has(V.name))continue;if(!Z||Z.has(V.name))W.register(V)}for(let V of this.baseRegistry.getMcpTools()){if(Y?.has(V.name))continue;if(!Z||Z.has(V.name))W.registerMcpTool(V)}let J={...this.config.permissions,...$.permissions},X=$.permissionMode??this.config.permissionMode??"default";return new V1(W,{permissionConfig:J,permissionMode:X,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist})}createExecutionPipeline($={}){return this.createToolExecutor($)}async dispose(){try{await $0.getInstance().killSession(this.sessionId),this.approvalStore.clear(),N$.releaseSession(this.sessionId),await this.chatService?.dispose?.()}finally{try{await this.sessionMcpRegistry?.disconnectAll()}finally{this.sessionMcpRegistry=void 0;try{await this.sessionLease?.release()}finally{this.sessionLease=void 0,this.currentModelId=void 0,this.initialized=!1}}}}resolveModelConfig($){let W=$&&$!=="inherit"?$:void 0,Z=W?K1(W):j0();if(!Z)throw Error(`模型配置未找到: ${W??"current"}`);return Z}async applyModelConfig($,W){L0.debug(`${W} ${$.name} (${$.model})`);let Z=c1($),Y=a1(),J=Z&&Y,X=$.maxContextTokens??this.config.maxContextTokens,V=await o1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:X,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:$.timeout??this.config.timeout,supportsThinking:J,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries}),H=this.initialized?this.chatService:void 0,K=this.executionEngine?.getContextManager();this.chatService=V,this.executionEngine=new B1(V,K,this.workspaceRoot),this.currentModelMaxContextTokens=X,this.currentModelId=$.id;let B=H;try{await B?.dispose?.()}catch(U){L0.warn(`[SessionRuntime ${this.sessionId}] Failed to dispose previous model service`,U)}}async validateSystemPromptConfig(){try{await q$({projectPath:this.workspaceRoot,includeEnvironment:!1,language:this.config.language})}catch($){L0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let W=(await s1({sessionId:this.sessionId,configDir:M8.join(b8.homedir(),".blade")})).filter((Z)=>!Z.name.startsWith("mcp__"));this.baseRegistry.registerAll(W),await this.registerMcpTools()}async registerMcpTools(){try{let $=this.options.mcpServers!==void 0;if(!$&&this.options.mcpConfig&&this.options.mcpConfig.length>0)await M1(this.options.mcpConfig);let W=$?this.options.mcpServers??{}:k0();if(Object.keys(W).length===0)return;let Z=$?G0.createIsolated():G0.getInstance();if($)this.sessionMcpRegistry=Z;for(let[J,X]of Object.entries(W))try{await Z.registerServer(J,X)}catch(V){L0.warn(`Warning: MCP server "${J}" connection failed:`,V)}let Y=await Z.getAvailableTools();for(let J of Y)this.baseRegistry.registerMcpTool(J)}catch($){L0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){try{if(P.getAllNames().length===0)P.loadFromStandardLocations();if(this.options.agents?.length)P.applyOverrides(this.options.agents)}catch($){L0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await u$({cwd:this.workspaceRoot})}catch($){L0.warn("Failed to discover skills:",$)}}}import*as F0 from"node:fs/promises";import{homedir as OY}from"node:os";import*as i from"node:path";import S8 from"gray-matter";function q2($,W){return`${$}:${W}`}function v8($,W){return`${$}__${W}`}import*as w2 from"node:fs/promises";import*as f8 from"node:path";import{z as T}from"zod";var GY=T.string().min(2,"Plugin name must be at least 2 characters").max(64,"Plugin name must be at most 64 characters").regex(/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]{1,2}$/,{message:"Plugin name must be lowercase letters, numbers, and hyphens only, starting and ending with alphanumeric"}),EY=T.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),FY=T.object({name:T.string().min(1,"Author name is required"),email:T.string().email().optional(),url:T.string().url().optional()}),C8=T.object({name:GY,description:T.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:EY,author:FY.optional(),license:T.string().optional(),repository:T.string().url().optional(),homepage:T.string().url().optional(),keywords:T.array(T.string()).optional(),dependencies:T.record(T.string()).optional(),bladeVersion:T.string().optional()}),x8=T.object({type:T.enum(["stdio","sse","http"]),command:T.string().optional(),args:T.array(T.string()).optional(),env:T.record(T.string()).optional(),url:T.string().url().optional(),headers:T.record(T.string()).optional(),timeout:T.number().positive().optional(),oauth:T.object({enabled:T.boolean().optional(),clientId:T.string().optional(),clientSecret:T.string().optional(),authorizationUrl:T.string().url().optional(),tokenUrl:T.string().url().optional(),scopes:T.array(T.string()).optional(),redirectUri:T.string().url().optional()}).optional(),healthCheck:T.object({enabled:T.boolean().optional(),interval:T.number().positive().optional(),timeout:T.number().positive().optional(),failureThreshold:T.number().positive().optional()}).optional()}),zY=T.union([T.object({mcpServers:T.record(x8)}),T.record(x8)]);function y8($){return zY.safeParse($)}var RY=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function i$($){for(let{dir:W,source:Z}of RY){let Y=f8.join($,W,"plugin.json");try{await w2.access(Y)}catch{continue}try{let J=await w2.readFile(Y,"utf-8"),X=JSON.parse(J),V=C8.safeParse(X);if(!V.success){let H=V.error.issues.map((K)=>`${K.path.join(".")}: ${K.message}`).join("; ");throw Error(`Invalid plugin.json: ${H}`)}return S.debug(`Parsed plugin manifest from ${Y}`),{manifest:V.data,source:Z,manifestPath:Y}}catch(J){if(J instanceof SyntaxError)throw Error(`Invalid JSON in ${Y}: ${J.message}`);throw J}}return null}async function P8($){try{return await i$($)!==null}catch{return!1}}class G2{async loadPlugin($,W,Z={}){let Y=await i$($);if(!Y)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:J,source:X}=Y,V=J.name;S.debug(`Loading plugin "${V}" from ${$}`);let H=Z.skipCommands?[]:await this.loadCommands($,V),K=Z.skipAgents?[]:await this.loadAgents($,V),B=Z.skipSkills?[]:await this.loadSkills($,V),U=Z.skipHooks?void 0:await this.loadHooks($),Q=Z.skipMcp?void 0:await this.loadMcpConfig($,V);return S.debug(`Plugin "${V}" loaded: ${H.length} commands, ${K.length} agents, ${B.length} skills`),{manifest:J,basePath:$,source:W,manifestSource:X,commands:H,agents:K,skills:B,hooks:U,mcpServers:Q,status:"active",loadedAt:new Date}}async loadCommands($,W){let Z=i.join($,"commands"),Y=[];if(!await this.dirExists(Z))return Y;let J=await this.scanMarkdownFiles(Z);for(let X of J)try{let V=await this.parseCommandFile(X,Z,W);if(V)Y.push(V)}catch(V){S.warn(`Failed to load command from ${X}: ${V instanceof Error?V.message:String(V)}`)}return Y}async parseCommandFile($,W,Z){let Y=await F0.readFile($,"utf-8"),{data:J,content:X}=S8(Y),H=i.relative(W,$).split(i.sep),K=H.pop();if(!K)return null;let B=K.replace(/\.md$/i,""),U=B;if(H.length>0)U=[...H,B].join("/");let Q=q2(Z,U),q=this.normalizeCommandConfig(J);return{originalName:U,namespacedName:Q,pluginName:Z,config:q,content:X.trim(),path:$}}normalizeCommandConfig($){return{description:this.asString($.description),allowedTools:this.parseStringArray($["allowed-tools"]),argumentHint:this.asString($["argument-hint"]),model:this.asString($.model),disableModelInvocation:$["disable-model-invocation"]===!0}}async loadAgents($,W){let Z=i.join($,"agents"),Y=[];if(!await this.dirExists(Z))return Y;let J=await this.scanMarkdownFiles(Z);for(let X of J)try{let V=await this.parseAgentFile(X,Z,W);if(V)Y.push(V)}catch(V){S.warn(`Failed to load agent from ${X}: ${V instanceof Error?V.message:String(V)}`)}return Y}async parseAgentFile($,W,Z){let Y=await F0.readFile($,"utf-8"),{data:J,content:X}=S8(Y),V=i.relative(W,$),H=i.basename(V,".md"),K=J.name||H,B=q2(Z,K),U={name:B,description:this.asString(J.description)||"",tools:this.parseStringArray(J.tools),color:this.asString(J.color),model:this.asString(J.model),permissionMode:this.asString(J.permissionMode),skills:this.parseStringArray(J.skills),systemPrompt:X.trim(),source:`plugin:${Z}`};return{originalName:K,namespacedName:B,pluginName:Z,config:U,path:$}}async loadSkills($,W){let Z=i.join($,"skills"),Y=[];if(!await this.dirExists(Z))return Y;let J=await F0.readdir(Z,{withFileTypes:!0});for(let X of J){if(!X.isDirectory())continue;let V=i.join(Z,X.name),H=i.join(V,"SKILL.md");try{let K=await I8(H,"project");if(K.success&&K.content){let B=K.content.metadata.name,U=q2(W,B);Y.push({originalName:B,namespacedName:U,pluginName:W,metadata:{...K.content.metadata,name:U},path:V})}}catch(K){S.warn(`Failed to load skill from ${H}: ${K instanceof Error?K.message:String(K)}`)}}return Y}async loadHooks($){let W=i.join($,"hooks","hooks.json");try{let Z=await F0.readFile(W,"utf-8"),Y=JSON.parse(Z);return Y.hooks||Y}catch{return}}async loadMcpConfig($,W){let Z=i.join($,".mcp.json");try{let Y=await F0.readFile(Z,"utf-8"),J=JSON.parse(Y),X=y8(J);if(!X.success){S.warn(`Invalid .mcp.json in ${$}: ${X.error}`);return}let V="mcpServers"in J?J.mcpServers:J,H={};for(let[K,B]of Object.entries(V)){let U=v8(W,K);H[U]=B}return H}catch{return}}async scanMarkdownFiles($){let W=[],Z=async(Y)=>{let J=await F0.readdir(Y,{withFileTypes:!0});for(let X of J){let V=i.join(Y,X.name);if(X.isDirectory())await Z(V);else if(X.name.endsWith(".md"))W.push(V)}};return await Z($),W}async dirExists($){try{return(await F0.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((W)=>String(W).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((W)=>W.trim()).filter(Boolean);return}static getPluginDirs($){let W=OY();return[{path:i.join(W,".claude","plugins"),source:"user",type:"claude"},{path:i.join(W,".blade","plugins"),source:"user",type:"blade"},{path:i.join($,".claude","plugins"),source:"project",type:"claude"},{path:i.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,W){let Z=[],Y=[];try{await F0.access($)}catch{return{plugins:Z,errors:Y}}let J=await F0.readdir($,{withFileTypes:!0});for(let X of J){if(!X.isDirectory())continue;let V=i.join($,X.name);try{let H=await this.loadPlugin(V,W);Z.push(H)}catch(H){Y.push({path:V,error:H instanceof Error?H.message:String(H)})}}return{plugins:Z,errors:Y}}}class b${static instance=null;plugins=new Map;loader=new G2;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}static resetInstance(){b$.instance=null}async initialize($,W=[]){this.workspaceRoot=$,this.cliPluginDirs=W;let Z=[],Y=[];for(let X of W)try{let V=await this.loader.loadPlugin(X,"cli");this.plugins.set(V.manifest.name,V),Z.push(V),S.info(`Loaded CLI plugin: ${V.manifest.name} from ${X}`)}catch(V){Y.push({path:X,error:V instanceof Error?V.message:String(V)}),S.warn(`Failed to load CLI plugin from ${X}: ${V}`)}let J=G2.getPluginDirs($);for(let{path:X,source:V}of J){let H=await this.loader.discoverPluginsInDir(X,V);for(let K of H.plugins){let B=this.plugins.get(K.manifest.name);if(!B||B.source!=="cli")this.plugins.set(K.manifest.name,K),Z.push(K)}Y.push(...H.errors)}return this.initialized=!0,S.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(Y.length>0?`, ${Y.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:Y}}isInitialized(){return this.initialized}getAll(){return Array.from(this.plugins.values())}getActive(){return Array.from(this.plugins.values()).filter(($)=>$.status==="active")}get($){return this.plugins.get($)}has($){return this.plugins.has($)}getBySource(){let $={cli:[],project:[],user:[]};for(let W of this.plugins.values())$[W.source].push(W);return $}getAllCommands(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.commands);return $}getAllSkills(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.skills);return $}getAllAgents(){let $=[];for(let W of this.plugins.values())if(W.status==="active")$.push(...W.agents);return $}findCommand($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}findSkill($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.skills)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.skills)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}findAgent($){for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.agents)if(Y.namespacedName===$)return Y}let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.agents)if(Y.originalName===$)W.push(Y)}if(W.length===1)return W[0];return}hasCommandConflict($){let W=0;for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$){if(W++,W>1)return!0}}return!1}getCommandProviders($){let W=[];for(let Z of this.plugins.values()){if(Z.status!=="active")continue;for(let Y of Z.commands)if(Y.originalName===$){W.push(Z.manifest.name);break}}return W}disable($){let W=this.plugins.get($);if(W&&W.status==="active")return W.status="inactive",S.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let W=this.plugins.get($);if(W&&W.status==="inactive")return W.status="active",S.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return S.info("Refreshing plugin list..."),this.plugins.clear(),this.initialized=!1,this.initialize(this.workspaceRoot,this.cliPluginDirs)}getStats(){let $=0,W=0,Z=0,Y=0,J=0;for(let X of this.plugins.values())if(X.status==="active")$++,Z+=X.commands.length,Y+=X.skills.length,J+=X.agents.length;else W++;return{total:this.plugins.size,active:$,inactive:W,commands:Z,skills:Y,agents:J}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let W=[],Z=this.getBySource();if(Z.cli.length>0){W.push("## CLI 指定的插件");for(let Y of Z.cli){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}W.push("")}if(Z.project.length>0){W.push("## 项目级插件");for(let Y of Z.project){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}W.push("")}if(Z.user.length>0){W.push("## 用户级插件");for(let Y of Z.user){let J=Y.status==="inactive"?" (禁用)":"";W.push(`- **${Y.manifest.name}** v${Y.manifest.version}${J}`),W.push(` ${Y.manifest.description}`)}}return W.join(`
1011
+ `)}}function m0(){return b$.getInstance()}class WZ{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=r.getInstance(),this.hookManager=w0.getInstance(),this.mcpRegistry=G0.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),U0().clearPluginSkills(),P.clearPluginAgents(),S.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let W=m0().getActive(),Z=[],Y=[],J=0,X=0,V=0,H=0;for(let K of W){let B=await this.integratePlugin(K);Z.push(B),J+=B.commandsRegistered,X+=B.skillsRegistered,V+=B.agentsRegistered,H+=B.mcpServersRegistered,Y.push(...B.errors)}if(J+X+V>0)S.info(`Plugin integration complete: ${J} commands, ${X} skills, ${V} agents, ${H} MCP servers`);return{plugins:Z,totalCommands:J,totalSkills:X,totalAgents:V,totalMcpServers:H,errors:Y}}async integratePlugin($){let W={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{W.commandsRegistered=this.integrateCommands($)}catch(Z){W.errors.push(`Failed to integrate commands: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.skillsRegistered=this.integrateSkills($)}catch(Z){W.errors.push(`Failed to integrate skills: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.agentsRegistered=this.integrateAgents($)}catch(Z){W.errors.push(`Failed to integrate agents: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.hooksRegistered=this.integrateHooks($)}catch(Z){W.errors.push(`Failed to integrate hooks: ${Z instanceof Error?Z.message:String(Z)}`)}try{W.mcpServersRegistered=await this.integrateMcp($)}catch(Z){W.errors.push(`Failed to integrate MCP servers: ${Z instanceof Error?Z.message:String(Z)}`)}return S.debug(`Integrated plugin "${$.manifest.name}": ${W.commandsRegistered} commands, ${W.skillsRegistered} skills, ${W.agentsRegistered} agents`),W}integrateCommands($){let W=0;for(let Z of $.commands)this.commandRegistry.registerPluginCommand(Z),W++;return W}integrateSkills($){let W=U0(),Z=0;for(let Y of $.skills)W.registerPluginSkill(Y),Z++;return Z}integrateAgents($){let W=0;for(let Z of $.agents)P.register({...Z.config,name:Z.namespacedName}),W++;return W}integrateHooks($){if(!$.hooks)return!1;let W=this.hookManager.getConfig();return this.hookManager.loadConfig({...W,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let W=0;for(let[Z,Y]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(Z,Y),W++}catch(J){S.warn(`Failed to register MCP server "${Z}" from plugin "${$.manifest.name}": ${J instanceof Error?J.message:String(J)}`)}return W}}async function E2(){return new WZ().integrateAll()}function F2(){new WZ().clearAllPluginResources()}import{execSync as h8}from"node:child_process";import*as X0 from"node:fs/promises";import{homedir as _Y}from"node:os";import*as r$ from"node:path";class u8{userPluginsDir;constructor($){this.userPluginsDir=$||r$.join(_Y(),".blade","plugins")}async install($){try{let W=this.parseGitUrl($);if(!W)return{success:!1,error:`Invalid source URL: ${$}`};let Z=this.extractPluginName(W);if(!Z)return{success:!1,error:`Could not extract plugin name from URL: ${W}`};await X0.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let Y=r$.join(this.userPluginsDir,Z);try{return await X0.access(Y),{success:!1,pluginName:Z,pluginPath:Y,error:`Plugin "${Z}" already exists at ${Y}. Use /plugins uninstall first.`}}catch{}S.info(`Cloning ${W} to ${Y}...`);try{h8(`git clone --depth 1 "${W}" "${Y}"`,{stdio:"pipe",timeout:60000})}catch(X){return{success:!1,pluginName:Z,error:`Failed to clone repository: ${X instanceof Error?X.message:String(X)}`}}if(!await P8(Y))return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let J;try{J=await i$(Y)}catch(X){return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:`Invalid plugin manifest: ${X instanceof Error?X.message:String(X)}`}}if(!J)return await X0.rm(Y,{recursive:!0,force:!0}),{success:!1,pluginName:Z,error:"Invalid plugin manifest: No manifest found"};return S.info(`Successfully installed plugin: ${J.manifest.name}`),{success:!0,pluginName:J.manifest.name,pluginPath:Y,manifest:J.manifest}}catch(W){return{success:!1,error:`Installation failed: ${W instanceof Error?W.message:String(W)}`}}}async uninstall($){try{let W=r$.join(this.userPluginsDir,$);try{await X0.access(W)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${W}`}}return await X0.rm(W,{recursive:!0,force:!0}),S.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:W}}catch(W){return{success:!1,pluginName:$,error:`Uninstallation failed: ${W instanceof Error?W.message:String(W)}`}}}async listInstalled(){try{return await X0.access(this.userPluginsDir),(await X0.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((W)=>W.isDirectory()).map((W)=>W.name)}catch{return[]}}async update($){try{let W=r$.join(this.userPluginsDir,$);try{await X0.access(W)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${W}`}}let Z=r$.join(W,".git");try{await X0.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}S.info(`Updating plugin: ${$}...`);try{h8(`git -C "${W}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(J){return{success:!1,pluginName:$,error:`Failed to update: ${J instanceof Error?J.message:String(J)}`}}let Y;try{Y=await i$(W)}catch(J){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${J instanceof Error?J.message:String(J)}`}}if(!Y)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return S.info(`Successfully updated plugin: ${Y.manifest.name}`),{success:!0,pluginName:Y.manifest.name,pluginPath:W,manifest:Y.manifest}}catch(W){return{success:!1,pluginName:$,error:`Update failed: ${W instanceof Error?W.message:String(W)}`}}}parseGitUrl($){if($.startsWith("https://")||$.startsWith("git@"))return $;if(/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_.-]+$/.test($))return`https://github.com/${$}.git`;return null}extractPluginName($){let W=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(W)return W[1];let Z=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[2];return null}}var ZZ=null;function z1($){if(!ZZ)ZZ=new u8($);return ZZ}import dJ from"fuse.js";import Z6 from"node:fs/promises";import Y6 from"node:path";import DY from"node:os";import p8 from"node:path";function C($){if($.acp)return{sendMessage:(W)=>$.acp.sendMessage(`• ${W}
1012
1012
 
1013
- `),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(W)=>L().addAssistantMessage(W),sendToolStart:void 0,sendToolResult:void 0}}var d8={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($,W){let Z=$[0],Y=C(W);if(!Z)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(Z==="list"){let X=f.getAllNames().map((U)=>f.getSubagent(U)).filter((U)=>U!==void 0);if(X.length===0){let U=`**Agents 管理**
1013
+ `),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(W)=>k().addAssistantMessage(W),sendToolStart:void 0,sendToolResult:void 0}}var d8={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($,W){let Z=$[0],Y=C(W);if(!Z)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(Z==="list"){let X=P.getAllNames().map((Q)=>P.getSubagent(Q)).filter((Q)=>Q!==void 0);if(X.length===0){let Q=`**Agents 管理**
1014
1014
 
1015
1015
  `+`没有找到任何 agent 配置
1016
1016
 
1017
1017
  `+`**配置文件位置:**
1018
- `+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"使用 `/agents` 打开管理对话框";return Y.sendMessage(U),{success:!0,message:"No agents found"}}let V=p8.join(D(),".blade","agents"),H=p8.join(_Y.homedir(),".blade","agents"),B=X.filter((U)=>U.configPath?.startsWith(V)),K=X.filter((U)=>U.configPath?.startsWith(H)),Q=`**Agents 管理**
1018
+ `+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"使用 `/agents` 打开管理对话框";return Y.sendMessage(Q),{success:!0,message:"No agents found"}}let V=p8.join(D(),".blade","agents"),H=p8.join(DY.homedir(),".blade","agents"),K=X.filter((Q)=>Q.configPath?.startsWith(V)),B=X.filter((Q)=>Q.configPath?.startsWith(H)),U=`**Agents 管理**
1019
1019
 
1020
1020
  找到 **${X.length}** 个 agent:
1021
1021
 
1022
- `;if(B.length>0){Q+=`**项目级** (.blade/agents/):
1023
- `;for(let U of B){if(Q+=`
1024
- • **${U.name}**
1025
- `,Q+=` ${U.description}
1026
- `,U.tools&&U.tools.length>0)Q+=` 工具: ${U.tools.join(", ")}
1027
- `;if(U.color)Q+=` 颜色: ${U.color}
1028
- `}Q+=`
1029
- `}if(K.length>0){Q+=`**用户级** (~/.blade/agents/):
1030
- `;for(let U of K){if(Q+=`
1031
- • **${U.name}**
1032
- `,Q+=` ${U.description}
1033
- `,U.tools&&U.tools.length>0)Q+=` 工具: ${U.tools.join(", ")}
1034
- `;if(U.color)Q+=` 颜色: ${U.color}
1035
- `}Q+=`
1036
- `}return Q+="\n使用 `/agents` 打开管理对话框",Y.sendMessage(Q),{success:!0,message:`Listed ${X.length} agents`}}if(Z==="help"){let X=`**Agents 管理帮助**
1022
+ `;if(K.length>0){U+=`**项目级** (.blade/agents/):
1023
+ `;for(let Q of K){if(U+=`
1024
+ • **${Q.name}**
1025
+ `,U+=` ${Q.description}
1026
+ `,Q.tools&&Q.tools.length>0)U+=` 工具: ${Q.tools.join(", ")}
1027
+ `;if(Q.color)U+=` 颜色: ${Q.color}
1028
+ `}U+=`
1029
+ `}if(B.length>0){U+=`**用户级** (~/.blade/agents/):
1030
+ `;for(let Q of B){if(U+=`
1031
+ • **${Q.name}**
1032
+ `,U+=` ${Q.description}
1033
+ `,Q.tools&&Q.tools.length>0)U+=` 工具: ${Q.tools.join(", ")}
1034
+ `;if(Q.color)U+=` 颜色: ${Q.color}
1035
+ `}U+=`
1036
+ `}return U+="\n使用 `/agents` 打开管理对话框",Y.sendMessage(U),{success:!0,message:`Listed ${X.length} agents`}}if(Z==="help"){let X=`**Agents 管理帮助**
1037
1037
 
1038
1038
  `+`**可用子命令:**
1039
1039
  `+"- `/agents list` - 列出所有已配置的 agents\n"+"- `/agents help` - 显示此帮助信息\n\n"+`**手动创建 Agent:**
@@ -1055,12 +1055,12 @@ IMPORTANT - Use the correct year in search queries:
1055
1055
  `+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
1056
1056
  `+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"**提示:** 创建文件后,重启 Blade 使配置生效";return Y.sendMessage(X),{success:!0,message:"Help displayed"}}if(Z==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let J=`未知子命令: \`${Z}\`
1057
1057
 
1058
- `+"使用 `/agents help` 查看可用命令";return Y.sendMessage(J),{success:!1,error:`Unknown subcommand: ${Z}`}}};async function jY($,W){let Z=C(W);try{let Y=Y0(),J=j0();if(!Y||!J)return{success:!1,error:"配置未初始化"};let X=Z0().session,V=X.messages,H=X.sessionId;if(!V||V.length===0)return Z.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let B=V.map((w)=>({role:w.role,content:w.content})),K=z2.countTokens(B,J.model),Q=J.maxContextTokens??Y.maxContextTokens,U=(K/Q*100).toFixed(1);if(Z.sendMessage(`**当前上下文统计**
1059
- • 消息数量: ${B.length}
1060
- • Token 数量: ${K.toLocaleString()}
1061
- • Token 限制: ${Q.toLocaleString()}
1062
- • 使用率: ${U}%`),K<Q*0.5)return Z.sendMessage(`提示: 当前 token 使用率较低(${U}%),可以暂时不压缩。
1063
- 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};Z.sendMessage("**正在压缩上下文...**");let q=await g8.compact(B,{trigger:"manual",modelName:J.model,maxContextTokens:Q,apiKey:J.apiKey,baseURL:J.baseUrl});if(q.success){try{if(H)await new H1().saveCompaction(H,q.summary,{trigger:"manual",preTokens:q.preTokens,postTokens:q.postTokens,filesIncluded:q.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(E){console.warn("[/compact] 保存压缩数据失败:",E)}let w=`[OK] **压缩完成!**
1058
+ `+"使用 `/agents help` 查看可用命令";return Y.sendMessage(J),{success:!1,error:`Unknown subcommand: ${Z}`}}};async function jY($,W){let Z=C(W);try{let Y=Y0(),J=j0();if(!Y||!J)return{success:!1,error:"配置未初始化"};let X=Z0().session,V=X.messages,H=X.sessionId;if(!V||V.length===0)return Z.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let K=V.map((w)=>({role:w.role,content:w.content})),B=z2.countTokens(K,J.model),U=J.maxContextTokens??Y.maxContextTokens,Q=(B/U*100).toFixed(1);if(Z.sendMessage(`**当前上下文统计**
1059
+ • 消息数量: ${K.length}
1060
+ • Token 数量: ${B.toLocaleString()}
1061
+ • Token 限制: ${U.toLocaleString()}
1062
+ • 使用率: ${Q}%`),B<U*0.5)return Z.sendMessage(`提示: 当前 token 使用率较低(${Q}%),可以暂时不压缩。
1063
+ 系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};Z.sendMessage("**正在压缩上下文...**");let q=await g8.compact(K,{trigger:"manual",modelName:J.model,maxContextTokens:U,apiKey:J.apiKey,baseURL:J.baseUrl});if(q.success){try{if(H)await new H1().saveCompaction(H,q.summary,{trigger:"manual",preTokens:q.preTokens,postTokens:q.postTokens,filesIncluded:q.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(E){console.warn("[/compact] 保存压缩数据失败:",E)}let w=`[OK] **压缩完成!**
1064
1064
 
1065
1065
  **Token 变化**
1066
1066
  • 压缩前: ${q.preTokens.toLocaleString()} tokens
@@ -1083,14 +1083,14 @@ IMPORTANT - Use the correct year in search queries:
1083
1083
 
1084
1084
  使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$.sendMessage("正在检查 MCP 服务器状态...");let Y=Object.entries(Z).map(async([J,X])=>{try{let V=W.getServerStatus(J);if(!V)await W.registerServer(J,X),V=W.getServerStatus(J);else if(V.status==="disconnected")await W.connectServer(J);return{name:J,config:X,serverInfo:W.getServerStatus(J)}}catch(V){return{name:J,config:X,serverInfo:null,error:V}}});await Promise.all(Y),TY($,W.getAllServers())}function TY($,W){let Z=`**MCP 服务器状态**
1085
1085
 
1086
- `,Y=0,J=0,X=0;for(let[V,H]of W){let{config:B,status:K,connectedAt:Q,lastError:U,tools:q}=H,w=K==="connected"?"[OK]":"[FAIL]",E=K==="connected"?"Connected":"Disconnected";if(K==="connected")Y++,X+=q.length;else J++;if(Z+=`**${V}**
1086
+ `,Y=0,J=0,X=0;for(let[V,H]of W){let{config:K,status:B,connectedAt:U,lastError:Q,tools:q}=H,w=B==="connected"?"[OK]":"[FAIL]",E=B==="connected"?"Connected":"Disconnected";if(B==="connected")Y++,X+=q.length;else J++;if(Z+=`**${V}**
1087
1087
  `,Z+=` 状态: ${w} ${E}
1088
- `,Z+=` 类型: ${B.type}
1089
- `,B.type==="stdio")Z+=` 命令: ${B.command}${B.args?.length?" "+B.args.join(" "):""}
1090
- `;else Z+=` URL: ${B.url}
1088
+ `,Z+=` 类型: ${K.type}
1089
+ `,K.type==="stdio")Z+=` 命令: ${K.command}${K.args?.length?" "+K.args.join(" "):""}
1090
+ `;else Z+=` URL: ${K.url}
1091
1091
  `;if(Z+=` 工具: ${q.length} 个
1092
- `,Q&&K==="connected")Z+=` 连接时间: ${l8(Q)}
1093
- `;if(U&&K!=="connected")Z+=` 错误: ${U.message}
1092
+ `,U&&B==="connected")Z+=` 连接时间: ${l8(U)}
1093
+ `;if(Q&&B!=="connected")Z+=` 错误: ${Q.message}
1094
1094
  `;Z+=`
1095
1095
  `}Z+=`**总计:**
1096
1096
  `,Z+=`- 服务器: ${W.size} 个 (${Y} 连接, ${J} 断开)
@@ -1099,28 +1099,28 @@ IMPORTANT - Use the correct year in search queries:
1099
1099
  `,Z+="使用 `/mcp <server-name>` 查看详细信息\n",Z+="使用 `/mcp tools` 查看所有工具",$.sendMessage(Z)}async function LY($,W){let Z=G0.getInstance(),J=k0()[W];if(!J){$.sendMessage(`服务器 "${W}" 不存在
1100
1100
 
1101
1101
  使用 \`/mcp\` 查看所有可用服务器`);return}try{let X=Z.getServerStatus(W);if(!X)$.sendMessage(`正在连接 ${W}...`),await Z.registerServer(W,J),X=Z.getServerStatus(W);else if(X.status==="disconnected")$.sendMessage(`正在重新连接 ${W}...`),await Z.connectServer(W),X=Z.getServerStatus(W);if(X)kY($,W,X);else c8($,W,J)}catch(X){c8($,W,J),$.sendMessage(`
1102
- [WARN] 连接失败: ${X instanceof Error?X.message:"未知错误"}`)}}function kY($,W,Z){let{config:Y,status:J,connectedAt:X,lastError:V,tools:H}=Z,B=J==="connected"?"[OK]":"[FAIL]",K=J==="connected"?"Connected":"Disconnected",Q=`**${W}**
1103
-
1104
- `;if(Q+=`**连接状态:**
1105
- `,Q+=` ${B} ${K}`,X&&J==="connected")Q+=` (连接于 ${l8(X)})`;if(Q+=`
1106
-
1107
- `,Q+=`**配置信息:**
1108
- `,Q+=` 类型: ${Y.type}
1109
- `,Y.type==="stdio"){if(Q+=` 命令: ${Y.command}
1110
- `,Y.args&&Y.args.length>0)Q+=` 参数: ${Y.args.join(" ")}
1111
- `;if(Y.env&&Object.keys(Y.env).length>0)Q+=` 环境变量: ${Object.keys(Y.env).length} 个
1112
- `}else if(Q+=` URL: ${Y.url}
1113
- `,Y.headers&&Object.keys(Y.headers).length>0)Q+=` Headers: ${Object.keys(Y.headers).length} 个
1114
- `;if(Y.timeout)Q+=` 超时: ${Y.timeout}ms
1115
- `;if(Q+=`
1116
- `,J==="connected")if(Q+=`**可用工具 (${H.length}):**
1117
- `,H.length===0)Q+=` (无)
1118
- `;else for(let U of H){if(Q+=` • ${U.name}`,U.description)Q+=` - ${U.description}`;Q+=`
1119
- `}else Q+=`**工具:**
1102
+ [WARN] 连接失败: ${X instanceof Error?X.message:"未知错误"}`)}}function kY($,W,Z){let{config:Y,status:J,connectedAt:X,lastError:V,tools:H}=Z,K=J==="connected"?"[OK]":"[FAIL]",B=J==="connected"?"Connected":"Disconnected",U=`**${W}**
1103
+
1104
+ `;if(U+=`**连接状态:**
1105
+ `,U+=` ${K} ${B}`,X&&J==="connected")U+=` (连接于 ${l8(X)})`;if(U+=`
1106
+
1107
+ `,U+=`**配置信息:**
1108
+ `,U+=` 类型: ${Y.type}
1109
+ `,Y.type==="stdio"){if(U+=` 命令: ${Y.command}
1110
+ `,Y.args&&Y.args.length>0)U+=` 参数: ${Y.args.join(" ")}
1111
+ `;if(Y.env&&Object.keys(Y.env).length>0)U+=` 环境变量: ${Object.keys(Y.env).length} 个
1112
+ `}else if(U+=` URL: ${Y.url}
1113
+ `,Y.headers&&Object.keys(Y.headers).length>0)U+=` Headers: ${Object.keys(Y.headers).length} 个
1114
+ `;if(Y.timeout)U+=` 超时: ${Y.timeout}ms
1115
+ `;if(U+=`
1116
+ `,J==="connected")if(U+=`**可用工具 (${H.length}):**
1117
+ `,H.length===0)U+=` (无)
1118
+ `;else for(let Q of H){if(U+=` • ${Q.name}`,Q.description)U+=` - ${Q.description}`;U+=`
1119
+ `}else U+=`**工具:**
1120
1120
  [WARN] 服务器未连接,无法获取工具列表
1121
- `;if(V)Q+=`
1121
+ `;if(V)U+=`
1122
1122
  **错误信息:**
1123
- `,Q+=` ${V.message}`;$.sendMessage(Q)}function c8($,W,Z){let Y=`**${W}**
1123
+ `,U+=` ${V.message}`;$.sendMessage(U)}function c8($,W,Z){let Y=`**${W}**
1124
1124
 
1125
1125
  `;if(Y+=`**连接状态:**
1126
1126
  `,Y+=` 未启动 (等待 Agent 连接)
@@ -1138,25 +1138,25 @@ IMPORTANT - Use the correct year in search queries:
1138
1138
 
1139
1139
  [WARN] 暂无配置的 MCP 服务器
1140
1140
 
1141
- 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$.sendMessage("正在检查 MCP 服务器并获取工具列表...");let Y=Object.entries(Z).map(async([H,B])=>{try{let K=W.getServerStatus(H);if(!K)await W.registerServer(H,B),K=W.getServerStatus(H);else if(K.status==="disconnected")await W.connectServer(H);return{name:H,config:B,serverInfo:W.getServerStatus(H)}}catch(K){return{name:H,config:B,serverInfo:null,error:K}}});await Promise.all(Y);let J=W.getAllServers(),X=`**可用的 MCP 工具**
1141
+ 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$.sendMessage("正在检查 MCP 服务器并获取工具列表...");let Y=Object.entries(Z).map(async([H,K])=>{try{let B=W.getServerStatus(H);if(!B)await W.registerServer(H,K),B=W.getServerStatus(H);else if(B.status==="disconnected")await W.connectServer(H);return{name:H,config:K,serverInfo:W.getServerStatus(H)}}catch(B){return{name:H,config:K,serverInfo:null,error:B}}});await Promise.all(Y);let J=W.getAllServers(),X=`**可用的 MCP 工具**
1142
1142
 
1143
- `,V=0;for(let[H,B]of J){let{status:K,tools:Q}=B;if(X+=`**${H} (${Q.length} 个工具):**
1144
- `,K!=="connected"){X+=` [WARN] 服务器未连接
1143
+ `,V=0;for(let[H,K]of J){let{status:B,tools:U}=K;if(X+=`**${H} (${U.length} 个工具):**
1144
+ `,B!=="connected"){X+=` [WARN] 服务器未连接
1145
1145
 
1146
- `;continue}if(Q.length===0){X+=` (无)
1146
+ `;continue}if(U.length===0){X+=` (无)
1147
1147
 
1148
- `;continue}V+=Q.length;for(let U of Q){if(X+=` • ${U.name}`,U.description){let q=U.description.length>60?U.description.substring(0,57)+"...":U.description;X+=` - ${q}`}X+=`
1148
+ `;continue}V+=U.length;for(let Q of U){if(X+=` • ${Q.name}`,Q.description){let q=Q.description.length>60?Q.description.substring(0,57)+"...":Q.description;X+=` - ${q}`}X+=`
1149
1149
  `}X+=`
1150
1150
  `}X+=`**总计:** ${V} 个工具可用`,$.sendMessage(X)}var MY={name:"mcp",description:"Display MCP server status and available tools",fullDescription:"显示 MCP 服务器状态、连接信息和可用工具列表",usage:"/mcp [server-name | tools]",category:"MCP",examples:["/mcp - 显示所有服务器概览","/mcp chrome-devtools - 显示特定服务器详情","/mcp tools - 显示所有可用工具"],async handler($,W){let Z=C(W);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await NY(Z),{success:!0,message:"MCP 服务器概览已显示"};let Y=$[0];if(console.log("[MCP Command] Subcommand:",Y),Y==="tools")return await bY(Z),{success:!0,message:"MCP 工具列表已显示"};return await LY(Z,Y),{success:!0,message:`服务器 "${Y}" 详情已显示`}}catch(Y){return{success:!1,error:`显示 MCP 信息失败: ${Y instanceof Error?Y.message:"未知错误"}`}}}},i8=MY;import{spawn as vY}from"node:child_process";import*as r8 from"node:path";function xY($){return new Promise((W)=>{let Z=process.env.EDITOR||process.env.VISUAL||"vi",Y=vY(Z,[$],{stdio:"inherit"});Y.on("close",(J)=>{W(J===0)}),Y.on("error",()=>{W(!1)})})}var CY={name:"memory",description:"Manage project auto memory",fullDescription:"查看和管理项目的 Auto Memory(跨会话持久记忆)",usage:"/memory [list|show|edit|clear]",aliases:["mem"],async handler($,W){let Z=C(W),Y=D(),J=new l0(Y);switch($[0]||"list"){case"list":{let V=await J.listTopics();if(V.length===0)Z.sendMessage(`暂无记忆文件。Agent 在工作过程中会自动记录有价值的项目知识。
1151
1151
 
1152
- `+`记忆目录: ${J.getMemoryDir()}`);else{let H=V.map((B)=>{let K=(B.size/1024).toFixed(1),Q=B.lastModified.toLocaleDateString("zh-CN");return`${B.name==="MEMORY"?"[INDEX]":"[FILE]"} **${B.name}.md** — ${K}KB, ${Q}`}).join(`
1152
+ `+`记忆目录: ${J.getMemoryDir()}`);else{let H=V.map((K)=>{let B=(K.size/1024).toFixed(1),U=K.lastModified.toLocaleDateString("zh-CN");return`${K.name==="MEMORY"?"[INDEX]":"[FILE]"} **${K.name}.md** — ${B}KB, ${U}`}).join(`
1153
1153
  `);Z.sendMessage(`**项目记忆文件:**
1154
1154
 
1155
1155
  ${H}
1156
1156
 
1157
1157
  `+"使用 `/memory edit [topic]` 编辑,`/memory show [topic]` 查看\n"+`${J.getMemoryDir()}`)}return{success:!0,message:"记忆列表已显示"}}case"show":{let V=$[1]||"MEMORY",H=await J.readTopic(V);if(H===null)Z.sendMessage(`记忆文件 "${V}.md" 不存在`);else Z.sendMessage(`**${V}.md:**
1158
1158
 
1159
- ${H}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",H=r8.join(J.getMemoryDir(),`${V}.md`);if(await J.initialize(),await J.readTopic(V)===null)await J.writeTopic(V,"","overwrite");let K=process.env.EDITOR||process.env.VISUAL||"vi";if(Z.sendMessage(`正在用 ${K} 打开 ${V}.md ...`),await xY(H))Z.sendMessage(`[OK] ${V}.md 编辑完成`);else Z.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
1159
+ ${H}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",H=r8.join(J.getMemoryDir(),`${V}.md`);if(await J.initialize(),await J.readTopic(V)===null)await J.writeTopic(V,"","overwrite");let B=process.env.EDITOR||process.env.VISUAL||"vi";if(Z.sendMessage(`正在用 ${B} 打开 ${V}.md ...`),await xY(H))Z.sendMessage(`[OK] ${V}.md 编辑完成`);else Z.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
1160
1160
  ${H}
1161
1161
 
1162
1162
  `+"设置 EDITOR 环境变量来指定编辑器(如 export EDITOR=code)");return{success:!0,message:"编辑完成"}}case"clear":{let V=await J.clearAll();return Z.sendMessage(`已清除 ${V} 个记忆文件`),{success:!0,message:`已清除 ${V} 个记忆文件`}}default:return Z.sendMessage(`**Auto Memory 命令:**
@@ -1164,12 +1164,12 @@ ${H}
1164
1164
  `+`/memory list — 列出所有记忆文件
1165
1165
  `+`/memory show [topic] — 查看记忆内容(默认 MEMORY)
1166
1166
  `+`/memory edit [topic] — 用编辑器打开记忆文件(默认 MEMORY)
1167
- `+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},n8=CY;async function yY($,W){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var PY={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:yY},R2=PY;import{readdir as a8,readFile as YZ,rm as o8}from"node:fs/promises";import*as M$ from"node:path";import{nanoid as O2}from"nanoid";var JZ=P("Service");class R1{static toUISafeMessages($){let W=Date.now(),Z=$.length,Y=[];return $.forEach((J,X)=>{if(J.role!=="user"&&J.role!=="assistant")return;let V;if(typeof J.content==="string")V=J.content;else if(Array.isArray(J.content))V=J.content.map((K)=>K.type==="text"?K.text:"[Image]").join("");else V="";let H=V.trim();if(!H)return;let B=Y[Y.length-1];if(B&&B.role===J.role&&B.content===H)return;Y.push({id:`restored-${W}-${X}`,role:J.role,content:H,timestamp:W-(Z-X)*1000,metadata:J.metadata&&typeof J.metadata==="object"?J.metadata:void 0})}),Y}static async listSessions(){let $=[],W=M$.join(V0(),"projects");try{let Z=await a8(W,{withFileTypes:!0});for(let Y of Z){if(!Y.isDirectory())continue;let J=M$.join(W,Y.name),X=t8(Y.name),H=(await a8(J)).filter((B)=>B.endsWith(".jsonl"));for(let B of H){let K=M$.join(J,B),Q=B.replace(".jsonl","");try{let U=await this.extractMetadata(K,Q,X);$.push(U)}catch(U){JZ.warn(`[SessionService] 跳过损坏的会话文件: ${K}`,U)}}}return $.sort((Y,J)=>new Date(J.lastMessageTime).getTime()-new Date(Y.lastMessageTime).getTime()),$}catch(Z){return JZ.error("[SessionService] 列出会话失败:",Z),[]}}static async extractMetadata($,W,Z){let Y=await YZ($,"utf-8"),J=_$(Y,$);if(J.length===0)throw Error("空的 JSONL 文件");let X=J[0],V=J[J.length-1],H=J.find((Q)=>Q.type==="session_created"),B=J.filter((Q)=>Q.type==="message_created"&&["user","assistant"].includes(Q.data.role)).length,K=J.some((Q)=>Q.type==="part_created"&&Q.data.partType==="tool_result"&&typeof Q.data.payload.error==="string");return{sessionId:W,projectPath:H?.cwd??X.cwd??Z,gitBranch:H?.gitBranch??X.gitBranch,parentId:H?.data.parentId,relationType:H?.data.relationType,status:H?.data.status,agentType:H?.data.agentType,model:H?.data.model,messageCount:B,firstMessageTime:X.timestamp,lastMessageTime:V.timestamp,hasErrors:K,filePath:$}}static async loadSession($,W){try{if(W){let J=this.getSessionFilePath(W,$);return await this.loadSessionFromFile(J)}let Y=(await this.listSessions()).find((J)=>J.sessionId===$);if(!Y)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(Y.filePath)}catch(Z){throw JZ.error(`[SessionService] 加载会话失败 (${$}):`,Z),Z}}static async forkSession($,W){let Z=W.newSessionId??`fork-${Date.now()}-${O2(8)}`;this.assertValidForkSessionId(Z);let Y=W.sourceProjectPath?o(W.sourceProjectPath,$):(await this.listSessions()).find((F)=>F.sessionId===$)?.filePath;if(!Y)throw Error(`未找到会话: ${$}`);let J=await YZ(Y,"utf-8"),X=_$(J,Y),V=X.find((F)=>F.type==="session_created");if(!V)throw Error(`Cannot fork session without session_created: ${$}`);let H=new Date().toISOString(),B=V.data.rootId||$,K=i1(W.targetProjectPath),Q=h$(),U={id:O2(),sessionId:Z,timestamp:H,type:"session_created",cwd:W.targetProjectPath,gitBranch:K,version:Q,data:{...V.data,sessionId:Z,rootId:B,parentId:$,relationType:"fork",status:"running",createdAt:H,updatedAt:H}},q=X.filter((F)=>F.type!=="session_created"&&F.type!=="inbox_acknowledged").map((F)=>{let R={...F,id:O2(),sessionId:Z,cwd:W.targetProjectPath,gitBranch:K,version:Q};if(F.type==="session_updated")return{...R,type:"session_updated",data:{...F.data,sessionId:Z,rootId:B,parentId:$,relationType:"fork"}};if(F.type==="message_created"){let{inboxMessageId:O,..._}=F.data;return{...R,type:"message_created",data:_}}return R}),w={id:O2(),sessionId:Z,timestamp:H,type:"session_updated",cwd:W.targetProjectPath,gitBranch:K,version:Q,data:{sessionId:Z,rootId:B,parentId:$,relationType:"fork",status:"running",updatedAt:H}},E=[U,...q,w],G=o(W.targetProjectPath,Z);try{await new n(G).createExclusive(E)}catch(F){if(F instanceof Error&&"code"in F&&F.code==="EEXIST")throw Error(`Fork session already exists: ${Z}`,{cause:F});throw F}return{sessionId:Z,parentSessionId:$,projectPath:W.targetProjectPath,messages:this.convertJSONLToMessages(E)}}static async deleteSession($){let Z=(await this.listSessions()).filter((Y)=>Y.sessionId===$);if(Z.length===0)return 0;return await Promise.all(Z.flatMap((Y)=>[o8(Y.filePath,{force:!0}),o8(M$.join(M$.dirname(Y.filePath),`${Y.sessionId}.inbox.json`),{force:!0})])),Z.length}static async loadSessionFromFile($){let W=await YZ($,"utf-8"),Z=_$(W,$);return this.convertJSONLToMessages(Z)}static convertJSONLToMessages($){let W=[],Z=new Map,Y=new Map,J=new Map,X=new Map;for(let V of $){if(V.type==="message_created"){let H=V.data.role==="assistant"&&V.data.parentMessageId?J.get(V.data.parentMessageId):void 0,B=H??{role:V.data.role,content:"",...V.data.inboxMessageId?{metadata:{inboxMessageId:V.data.inboxMessageId}}:{}};if(Z.set(V.data.messageId,B),Y.set(V.data.messageId,[]),!H)W.push(B)}if(V.type==="part_created"){if(V.data.partType==="text"){let H=Z.get(V.data.messageId);if(H){let B=V.data.payload,K=Y.get(V.data.messageId);if(K)K.push({type:"text",text:B.text??""}),H.content=s8(K);else H.content=B.text??""}}if(V.data.partType==="image"){let H=Z.get(V.data.messageId);if(H){let B=V.data.payload,K=Y.get(V.data.messageId);if(K&&B.dataUrl)K.push({type:"image_url",image_url:{url:B.dataUrl}}),H.content=s8(K)}}if(V.data.partType==="tool_call"){let H=Z.get(V.data.messageId);if(H?.role!=="assistant"){if(H=J.get(V.data.messageId),!H)H={role:"assistant",content:"",tool_calls:[]},J.set(V.data.messageId,H),W.push(H)}if(H.role==="assistant"){let B=V.data.payload,K=B.toolCallId??V.data.partId;X.set(V.data.partId,K),H.tool_calls??=[],H.tool_calls.push({id:K,type:"function",function:{name:B.toolName??"unknown",arguments:JSON.stringify(B.input??{})}})}}if(V.data.partType==="tool_result"){let H=V.data.payload,B=typeof H.error==="string"?`Error: ${H.error}`:typeof H.output==="string"?H.output:JSON.stringify(H.output??""),K=H;W.push({role:"tool",content:B,tool_call_id:X.get(V.data.messageId)??H.toolCallId,name:H.toolName,metadata:K})}if(V.data.partType==="summary"){let H=V.data.payload,B=V.data.payload;W.push({role:"system",content:H.text??"",metadata:B})}if(V.data.partType==="subtask_ref"){let H=Z.get(V.data.messageId);if(H){let B=V.data.payload,K=H.metadata??{};H.metadata={...K,subtaskRef:B}}}}}return W}static getSessionFilePath($,W){return o($,W)}static assertValidForkSessionId($){if($==="."||$===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test($))throw Error(`Invalid fork session ID: ${$}`)}}function s8($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}var fY={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,W){let Z=C(W),Y=L().restoreSession;if($.length>0){let J=$[0];try{let X=await R1.loadSession(J);if(X.length===0)return Z.sendMessage(`[FAIL] 会话 \`${J}\` 为空或无法加载`),{success:!1,error:"会话为空"};let V=R1.toUISafeMessages(X);return Y(J,V,X),Z.sendMessage(`[OK] 已恢复会话 \`${J}\`
1167
+ `+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},n8=CY;async function yY($,W){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var fY={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:yY},R2=fY;import{readdir as a8,readFile as YZ,rm as o8}from"node:fs/promises";import*as M$ from"node:path";import{nanoid as O2}from"nanoid";var JZ=f("Service");class R1{static toUISafeMessages($){let W=Date.now(),Z=$.length,Y=[];return $.forEach((J,X)=>{if(J.role!=="user"&&J.role!=="assistant")return;let V;if(typeof J.content==="string")V=J.content;else if(Array.isArray(J.content))V=J.content.map((B)=>B.type==="text"?B.text:"[Image]").join("");else V="";let H=V.trim();if(!H)return;let K=Y[Y.length-1];if(K&&K.role===J.role&&K.content===H)return;Y.push({id:`restored-${W}-${X}`,role:J.role,content:H,timestamp:W-(Z-X)*1000,metadata:J.metadata&&typeof J.metadata==="object"?J.metadata:void 0})}),Y}static async listSessions(){let $=[],W=M$.join(V0(),"projects");try{let Z=await a8(W,{withFileTypes:!0});for(let Y of Z){if(!Y.isDirectory())continue;let J=M$.join(W,Y.name),X=t8(Y.name),H=(await a8(J)).filter((K)=>K.endsWith(".jsonl"));for(let K of H){let B=M$.join(J,K),U=K.replace(".jsonl","");try{let Q=await this.extractMetadata(B,U,X);$.push(Q)}catch(Q){JZ.warn(`[SessionService] 跳过损坏的会话文件: ${B}`,Q)}}}return $.sort((Y,J)=>new Date(J.lastMessageTime).getTime()-new Date(Y.lastMessageTime).getTime()),$}catch(Z){return JZ.error("[SessionService] 列出会话失败:",Z),[]}}static async extractMetadata($,W,Z){let Y=await YZ($,"utf-8"),J=D$(Y,$);if(J.length===0)throw Error("空的 JSONL 文件");let X=J[0],V=J[J.length-1],H=J.find((U)=>U.type==="session_created"),K=J.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,B=J.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string");return{sessionId:W,projectPath:H?.cwd??X.cwd??Z,gitBranch:H?.gitBranch??X.gitBranch,parentId:H?.data.parentId,relationType:H?.data.relationType,status:H?.data.status,agentType:H?.data.agentType,model:H?.data.model,messageCount:K,firstMessageTime:X.timestamp,lastMessageTime:V.timestamp,hasErrors:B,filePath:$}}static async loadSession($,W){try{if(W){let J=this.getSessionFilePath(W,$);return await this.loadSessionFromFile(J)}let Y=(await this.listSessions()).find((J)=>J.sessionId===$);if(!Y)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(Y.filePath)}catch(Z){throw JZ.error(`[SessionService] 加载会话失败 (${$}):`,Z),Z}}static async forkSession($,W){let Z=W.newSessionId??`fork-${Date.now()}-${O2(8)}`;this.assertValidForkSessionId(Z);let Y=W.sourceProjectPath?o(W.sourceProjectPath,$):(await this.listSessions()).find((F)=>F.sessionId===$)?.filePath;if(!Y)throw Error(`未找到会话: ${$}`);let J=await YZ(Y,"utf-8"),X=D$(J,Y),V=X.find((F)=>F.type==="session_created");if(!V)throw Error(`Cannot fork session without session_created: ${$}`);let H=new Date().toISOString(),K=V.data.rootId||$,B=i1(W.targetProjectPath),U=h$(),Q={id:O2(),sessionId:Z,timestamp:H,type:"session_created",cwd:W.targetProjectPath,gitBranch:B,version:U,data:{...V.data,sessionId:Z,rootId:K,parentId:$,relationType:"fork",status:"running",createdAt:H,updatedAt:H}},q=X.filter((F)=>F.type!=="session_created"&&F.type!=="inbox_acknowledged").map((F)=>{let z={...F,id:O2(),sessionId:Z,cwd:W.targetProjectPath,gitBranch:B,version:U};if(F.type==="session_updated")return{...z,type:"session_updated",data:{...F.data,sessionId:Z,rootId:K,parentId:$,relationType:"fork"}};if(F.type==="message_created"){let{inboxMessageId:O,..._}=F.data;return{...z,type:"message_created",data:_}}return z}),w={id:O2(),sessionId:Z,timestamp:H,type:"session_updated",cwd:W.targetProjectPath,gitBranch:B,version:U,data:{sessionId:Z,rootId:K,parentId:$,relationType:"fork",status:"running",updatedAt:H}},E=[Q,...q,w],G=o(W.targetProjectPath,Z);try{await new n(G).createExclusive(E)}catch(F){if(F instanceof Error&&"code"in F&&F.code==="EEXIST")throw Error(`Fork session already exists: ${Z}`,{cause:F});throw F}return{sessionId:Z,parentSessionId:$,projectPath:W.targetProjectPath,messages:this.convertJSONLToMessages(E)}}static async deleteSession($){let Z=(await this.listSessions()).filter((Y)=>Y.sessionId===$);if(Z.length===0)return 0;return await Promise.all(Z.flatMap((Y)=>[o8(Y.filePath,{force:!0}),o8(M$.join(M$.dirname(Y.filePath),`${Y.sessionId}.inbox.json`),{force:!0})])),Z.length}static async loadSessionFromFile($){let W=await YZ($,"utf-8"),Z=D$(W,$);return this.convertJSONLToMessages(Z)}static convertJSONLToMessages($){let W=[],Z=new Map,Y=new Map,J=new Map,X=new Map;for(let V of $){if(V.type==="message_created"){let H=V.data.role==="assistant"&&V.data.parentMessageId?J.get(V.data.parentMessageId):void 0,K=H??{role:V.data.role,content:"",...V.data.inboxMessageId?{metadata:{inboxMessageId:V.data.inboxMessageId}}:{}};if(Z.set(V.data.messageId,K),Y.set(V.data.messageId,[]),!H)W.push(K)}if(V.type==="part_created"){if(V.data.partType==="text"){let H=Z.get(V.data.messageId);if(H){let K=V.data.payload,B=Y.get(V.data.messageId);if(B)B.push({type:"text",text:K.text??""}),H.content=s8(B);else H.content=K.text??""}}if(V.data.partType==="image"){let H=Z.get(V.data.messageId);if(H){let K=V.data.payload,B=Y.get(V.data.messageId);if(B&&K.dataUrl)B.push({type:"image_url",image_url:{url:K.dataUrl}}),H.content=s8(B)}}if(V.data.partType==="tool_call"){let H=Z.get(V.data.messageId);if(H?.role!=="assistant"){if(H=J.get(V.data.messageId),!H)H={role:"assistant",content:"",tool_calls:[]},J.set(V.data.messageId,H),W.push(H)}if(H.role==="assistant"){let K=V.data.payload,B=K.toolCallId??V.data.partId;X.set(V.data.partId,B),H.tool_calls??=[],H.tool_calls.push({id:B,type:"function",function:{name:K.toolName??"unknown",arguments:JSON.stringify(K.input??{})}})}}if(V.data.partType==="tool_result"){let H=V.data.payload,K=typeof H.error==="string"?`Error: ${H.error}`:typeof H.output==="string"?H.output:JSON.stringify(H.output??""),B=H;W.push({role:"tool",content:K,tool_call_id:X.get(V.data.messageId)??H.toolCallId,name:H.toolName,metadata:B})}if(V.data.partType==="summary"){let H=V.data.payload,K=V.data.payload;W.push({role:"system",content:H.text??"",metadata:K})}if(V.data.partType==="subtask_ref"){let H=Z.get(V.data.messageId);if(H){let K=V.data.payload,B=H.metadata??{};H.metadata={...B,subtaskRef:K}}}}}return W}static getSessionFilePath($,W){return o($,W)}static assertValidForkSessionId($){if($==="."||$===".."||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test($))throw Error(`Invalid fork session ID: ${$}`)}}function s8($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}var PY={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,W){let Z=C(W),Y=k().restoreSession;if($.length>0){let J=$[0];try{let X=await R1.loadSession(J);if(X.length===0)return Z.sendMessage(`[FAIL] 会话 \`${J}\` 为空或无法加载`),{success:!1,error:"会话为空"};let V=R1.toUISafeMessages(X);return Y(J,V,X),Z.sendMessage(`[OK] 已恢复会话 \`${J}\`
1168
1168
 
1169
- 共 ${V.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:J,messageCount:V.length}}}catch(X){let V=X instanceof Error?X.message:"未知错误";return Z.sendMessage(`[FAIL] 加载会话失败: ${V}`),{success:!1,error:`加载会话失败: ${V}`}}}try{let J=await R1.listSessions();if(J.length===0)return Z.sendMessage("**没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:J}}}catch(J){let X=J instanceof Error?J.message:"未知错误";return Z.sendMessage(`获取会话列表失败: ${X}`),{success:!1,error:`获取会话列表失败: ${X}`}}}},e8=fY;import{promises as D2}from"node:fs";import $6 from"node:path";async function SY($){let W=$6.join(V0(),"file-history",$),Z=[];try{let Y=await D2.readdir(W);for(let J of Y){let X=J.match(/^(.+)@v(\d+)$/);if(!X)continue;let V=$6.join(W,J),H=await D2.stat(V);Z.push({filePath:X[1],version:parseInt(X[2],10),snapshotPath:V,mtime:H.mtime})}}catch{}return Z.sort((Y,J)=>J.mtime.getTime()-Y.mtime.getTime())}var IY={name:"rewind",description:"Revert files to their state before the last edit",fullDescription:"回退文件到编辑前的快照状态。不带参数列出可回退的文件,带文件路径则执行回退。",usage:"/rewind [file_path]",aliases:["undo"],async handler($,W){let Z=C(W),J=Z0().session?.sessionId;if(!J)return Z.sendMessage("无活跃会话,无法查找快照。"),{success:!1,message:"No active session"};let X=await SY(J);if(X.length===0)return Z.sendMessage("当前会话没有可回退的文件快照。"),{success:!0,message:"No snapshots available"};if($.length===0){let K=new Map;for(let U of X)if(!K.has(U.filePath))K.set(U.filePath,{version:U.version,mtime:U.mtime});let Q=`**可回退的文件快照:**
1169
+ 共 ${V.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:J,messageCount:V.length}}}catch(X){let V=X instanceof Error?X.message:"未知错误";return Z.sendMessage(`[FAIL] 加载会话失败: ${V}`),{success:!1,error:`加载会话失败: ${V}`}}}try{let J=await R1.listSessions();if(J.length===0)return Z.sendMessage("**没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:J}}}catch(J){let X=J instanceof Error?J.message:"未知错误";return Z.sendMessage(`获取会话列表失败: ${X}`),{success:!1,error:`获取会话列表失败: ${X}`}}}},e8=PY;import{promises as _2}from"node:fs";import $6 from"node:path";async function SY($){let W=$6.join(V0(),"file-history",$),Z=[];try{let Y=await _2.readdir(W);for(let J of Y){let X=J.match(/^(.+)@v(\d+)$/);if(!X)continue;let V=$6.join(W,J),H=await _2.stat(V);Z.push({filePath:X[1],version:parseInt(X[2],10),snapshotPath:V,mtime:H.mtime})}}catch{}return Z.sort((Y,J)=>J.mtime.getTime()-Y.mtime.getTime())}var IY={name:"rewind",description:"Revert files to their state before the last edit",fullDescription:"回退文件到编辑前的快照状态。不带参数列出可回退的文件,带文件路径则执行回退。",usage:"/rewind [file_path]",aliases:["undo"],async handler($,W){let Z=C(W),J=Z0().session?.sessionId;if(!J)return Z.sendMessage("无活跃会话,无法查找快照。"),{success:!1,message:"No active session"};let X=await SY(J);if(X.length===0)return Z.sendMessage("当前会话没有可回退的文件快照。"),{success:!0,message:"No snapshots available"};if($.length===0){let B=new Map;for(let Q of X)if(!B.has(Q.filePath))B.set(Q.filePath,{version:Q.version,mtime:Q.mtime});let U=`**可回退的文件快照:**
1170
1170
 
1171
- `;for(let[U,q]of K)Q+=`- \`${U}\` (v${q.version}, ${q.mtime.toLocaleTimeString()})
1172
- `;return Q+="\n使用 `/rewind <file_path>` 回退指定文件。",Z.sendMessage(Q),{success:!0,message:`${K.size} snapshots available`}}let V=$[0],H=X.filter((K)=>{return K.filePath===V||V.endsWith(K.filePath)||K.filePath.endsWith(V)});if(H.length===0)return Z.sendMessage(`未找到文件 "${V}" 的快照。`),{success:!1,message:"Snapshot not found"};let B=H[0];try{let K=await D2.readFile(B.snapshotPath,"utf-8");return await D2.writeFile(V,K,"utf-8"),Z.sendMessage(`已回退 \`${V}\` 到 v${B.version} (${B.mtime.toLocaleTimeString()})`),{success:!0,message:`Reverted ${V}`}}catch(K){return Z.sendMessage(`回退失败: ${K.message}`),{success:!1,error:K.message}}}},W6=IY;var hY={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,W){let Z=C(W),Y=`**可用的 Slash Commands:**
1171
+ `;for(let[Q,q]of B)U+=`- \`${Q}\` (v${q.version}, ${q.mtime.toLocaleTimeString()})
1172
+ `;return U+="\n使用 `/rewind <file_path>` 回退指定文件。",Z.sendMessage(U),{success:!0,message:`${B.size} snapshots available`}}let V=$[0],H=X.filter((B)=>{return B.filePath===V||V.endsWith(B.filePath)||B.filePath.endsWith(V)});if(H.length===0)return Z.sendMessage(`未找到文件 "${V}" 的快照。`),{success:!1,message:"Snapshot not found"};let K=H[0];try{let B=await _2.readFile(K.snapshotPath,"utf-8");return await _2.writeFile(V,B,"utf-8"),Z.sendMessage(`已回退 \`${V}\` 到 v${K.version} (${K.mtime.toLocaleTimeString()})`),{success:!0,message:`Reverted ${V}`}}catch(B){return Z.sendMessage(`回退失败: ${B.message}`),{success:!1,error:B.message}}}},W6=IY;var hY={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,W){let Z=C(W),Y=`**可用的 Slash Commands:**
1173
1173
 
1174
1174
  **/init** - 分析当前项目并生成 BLADE.md 配置文件
1175
1175
  **/git** - Git 仓库查询和 AI 辅助 (status/log/diff/review/commit)
@@ -1189,10 +1189,10 @@ ${H}
1189
1189
  **自定义命令:**
1190
1190
  `;let{project:V,user:H}=J.getCommandsBySource();if(V.length>0){Y+=`
1191
1191
  **项目命令** (.blade/commands/):
1192
- `;for(let B of V){let K=B.config.argumentHint?` ${B.config.argumentHint}`:"",Q=B.config.description||"(无描述)",U=B.namespace?` (${B.namespace})`:"";Y+=`**/${B.name}**${K} - ${Q}${U}
1192
+ `;for(let K of V){let B=K.config.argumentHint?` ${K.config.argumentHint}`:"",U=K.config.description||"(无描述)",Q=K.namespace?` (${K.namespace})`:"";Y+=`**/${K.name}**${B} - ${U}${Q}
1193
1193
  `}}if(H.length>0){Y+=`
1194
1194
  **用户命令** (~/.blade/commands/):
1195
- `;for(let B of H){let K=B.config.argumentHint?` ${B.config.argumentHint}`:"",Q=B.config.description||"(无描述)",U=B.namespace?` (${B.namespace})`:"";Y+=`**/${B.name}**${K} - ${Q}${U}
1195
+ `;for(let K of H){let B=K.config.argumentHint?` ${K.config.argumentHint}`:"",U=K.config.description||"(无描述)",Q=K.namespace?` (${K.namespace})`:"";Y+=`**/${K.name}**${B} - ${U}${Q}
1196
1196
  `}}}}return Y+=`
1197
1197
 
1198
1198
  **使用提示:**
@@ -1210,17 +1210,17 @@ ${H}
1210
1210
  - 智能 AI 对话
1211
1211
  - 项目自动分析
1212
1212
  - 自定义系统提示
1213
- - 多工具集成支持`;return Z.sendMessage(J),{success:!0,message:"版本信息已显示"}}},dY={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,W){let Z=C(W),{cwd:Y}=W;try{let J=Y6.join(Y,"BLADE.md"),X=await Z6.access(J).then(()=>!0).catch(()=>!1),V=Y6.join(Y,"package.json"),H="未知项目",B="未知类型";try{let E=await Z6.readFile(V,"utf-8"),G=JSON.parse(E);H=G.name||"未知项目";let F={...G.dependencies,...G.devDependencies};if(F.react)B="React 项目";else if(F.vue)B="Vue 项目";else if(F.next)B="Next.js 项目";else if(F.express)B="Express 项目";else B="Node.js 项目"}catch{}let K=Y0(),Q=j0(),q=Z0().session.tokenUsage,w=`**当前状态**
1213
+ - 多工具集成支持`;return Z.sendMessage(J),{success:!0,message:"版本信息已显示"}}},dY={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,W){let Z=C(W),{cwd:Y}=W;try{let J=Y6.join(Y,"BLADE.md"),X=await Z6.access(J).then(()=>!0).catch(()=>!1),V=Y6.join(Y,"package.json"),H="未知项目",K="未知类型";try{let E=await Z6.readFile(V,"utf-8"),G=JSON.parse(E);H=G.name||"未知项目";let F={...G.dependencies,...G.devDependencies};if(F.react)K="React 项目";else if(F.vue)K="Vue 项目";else if(F.next)K="Next.js 项目";else if(F.express)K="Express 项目";else K="Node.js 项目"}catch{}let B=Y0(),U=j0(),q=Z0().session.tokenUsage,w=`**当前状态**
1214
1214
 
1215
1215
  **项目信息:**
1216
1216
  - 名称: ${H}
1217
- - 类型: ${B}
1217
+ - 类型: ${K}
1218
1218
  - 路径: ${Y}
1219
1219
 
1220
1220
  **模型配置:**
1221
- - 当前模型: ${Q?.name??"N/A"} (${Q?.model??"N/A"})
1222
- - Provider: ${Q?.provider??"N/A"}
1223
- - 可用模型数: ${K?.models?.length??0}
1221
+ - 当前模型: ${U?.name??"N/A"} (${U?.model??"N/A"})
1222
+ - Provider: ${U?.provider??"N/A"}
1223
+ - 可用模型数: ${B?.models?.length??0}
1224
1224
 
1225
1225
  **会话统计:**
1226
1226
  - Turn: ${q.turnCount}
@@ -1235,23 +1235,23 @@ ${H}
1235
1235
  - 工作目录: ${D()} (process.cwd: ${process.cwd()})
1236
1236
  - Node.js: ${process.version}
1237
1237
 
1238
- ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return Z.sendMessage(w),{success:!0,message:"状态信息已显示"}}catch(J){return{success:!1,error:`获取状态信息失败: ${J instanceof Error?J.message:"未知错误"}`}}}},gY={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,W){return{success:!0,message:"exit_application"}}},mY={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,W){let Z=C(W),Y=Y0(),J=j0(),V=Z0().session.messages||[],H=V.map((F)=>({role:F.role,content:F.content})),B=J?.model||"gpt-4",K=H.length>0?z2.countTokens(H,B):0,Q=J?.maxContextTokens??Y?.maxContextTokens??128000,U=Q>0?(K/Q*100).toFixed(1):"0",q=(100-parseFloat(U)).toFixed(1),w=parseFloat(U),E;if(w<50)E="[OK] 正常";else if(w<80)E="[WARN] 中等";else E="[CRITICAL] 高负载";let G=`**上下文使用情况**
1238
+ ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return Z.sendMessage(w),{success:!0,message:"状态信息已显示"}}catch(J){return{success:!1,error:`获取状态信息失败: ${J instanceof Error?J.message:"未知错误"}`}}}},gY={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,W){return{success:!0,message:"exit_application"}}},mY={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,W){let Z=C(W),Y=Y0(),J=j0(),V=Z0().session.messages||[],H=V.map((F)=>({role:F.role,content:F.content})),K=J?.model||"gpt-4",B=H.length>0?z2.countTokens(H,K):0,U=J?.maxContextTokens??Y?.maxContextTokens??128000,Q=U>0?(B/U*100).toFixed(1):"0",q=(100-parseFloat(Q)).toFixed(1),w=parseFloat(Q),E;if(w<50)E="[OK] 正常";else if(w<80)E="[WARN] 中等";else E="[CRITICAL] 高负载";let G=`**上下文使用情况**
1239
1239
 
1240
1240
  **当前会话:**
1241
1241
  - 消息数量: ${V.length}
1242
- - Token 使用: ${K.toLocaleString()} / ${Q.toLocaleString()}
1243
- - 使用率: ${U}%
1242
+ - Token 使用: ${B.toLocaleString()} / ${U.toLocaleString()}
1243
+ - 使用率: ${Q}%
1244
1244
  - 剩余容量: ${q}%
1245
1245
 
1246
1246
  **模型信息:**
1247
1247
  - 模型: ${J?.model||"未配置"}
1248
- - 上下文窗口: ${Q.toLocaleString()} tokens
1248
+ - 上下文窗口: ${U.toLocaleString()} tokens
1249
1249
 
1250
1250
  **状态:** ${E}
1251
1251
 
1252
1252
  使用 \`/compact\` 可手动压缩上下文`;return Z.sendMessage(G),{success:!0,message:"上下文信息已显示"}}},cY={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,W){let Z=C(W),J=Z0().session.tokenUsage,X=j0(),V=J.estimatedCostUsd>0?`$${J.estimatedCostUsd<0.01?J.estimatedCostUsd.toFixed(6):J.estimatedCostUsd.toFixed(4)}`:"N/A (unknown model pricing)",H=J.cacheReadTokens>0||J.cacheWriteTokens>0?`
1253
1253
  - Cache read: ${J.cacheReadTokens.toLocaleString()} tokens
1254
- - Cache write: ${J.cacheWriteTokens.toLocaleString()} tokens`:"",B=`**Session Cost Summary**
1254
+ - Cache write: ${J.cacheWriteTokens.toLocaleString()} tokens`:"",K=`**Session Cost Summary**
1255
1255
 
1256
1256
  - Model: ${X?.model??"unknown"}
1257
1257
  - Turns: ${J.turnCount}
@@ -1260,10 +1260,10 @@ ${!X?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
1260
1260
  - **Total input: ${J.totalInputTokens.toLocaleString()} tokens**
1261
1261
  - **Total output: ${J.totalOutputTokens.toLocaleString()} tokens**${H}
1262
1262
  - Context remaining: ${J.maxContextTokens>0?Math.round((1-J.inputTokens/J.maxContextTokens)*100):"?"}%
1263
- - **Estimated cost: ${V}**`;return Z.sendMessage(B),{success:!0,message:"Cost summary displayed"}}},lY={name:"doctor",description:"Diagnose API connectivity and configuration health",fullDescription:"诊断 API 连通性和配置健康状况",usage:"/doctor",aliases:[],async handler($,W){let Z=C(W),J=Y0()?.models??[];if(J.length===0)return Z.sendMessage("❌ 没有配置任何模型。请先运行 `/init` 或编辑 `~/.blade/config.json`"),{success:!1,message:"No models configured"};let X=[`**API Connectivity Diagnosis**
1264
- `];for(let V of J){let H=Date.now();try{let{createChatServiceAsync:B}=await import("./chunk-1vngdr7p.js"),Q=await(await B({provider:V.provider,apiKey:V.apiKey,baseUrl:V.baseUrl,model:V.model,maxOutputTokens:10,temperature:0,timeout:1e4})).chat([{role:"user",content:"hi"}],void 0,AbortSignal.timeout(1e4)),U=Date.now()-H,q=!!Q.content;X.push(`✅ **${V.name}** (${V.model}) — ${U}ms${q?"":" ⚠️ empty response"}`)}catch(B){let K=Date.now()-H,Q=B instanceof Error?B.message.slice(0,80):"Unknown error";X.push(`❌ **${V.name}** (${V.model}) — ${K}ms — ${Q}`)}}return Z.sendMessage(X.join(`
1265
- `)),{success:!0,message:"Doctor diagnosis complete"}}},J6={help:hY,clear:uY,version:pY,status:dY,exit:gY,context:mY,cost:cY,doctor:lY,permissions:R2,resume:e8,rewind:W6,compact:m8,mcp:i8,memory:n8,agents:d8};import{execFile as X6,spawn as iY}from"child_process";import{promisify as rY}from"util";var nF=rY(X6);async function O1($,W){return new Promise((Z)=>{X6("git",W,{cwd:$,maxBuffer:10485760,encoding:"utf8"},(Y,J,X)=>{let V=Y==null?0:typeof Y.code==="number"?Y.code:1;Z({code:V,stdout:J||"",stderr:X||""})})})}async function nY($,W){let{code:Z}=await O1($,W);return Z===0}async function y0($,W){let{stdout:Z}=await O1($,W);return Z.trim()}async function XZ($){return nY($,["rev-parse","--is-inside-work-tree"])}async function _2($){return(await y0($,["status","--porcelain"])).length>0}async function aF($){return y0($,["branch","--show-current"])}async function j2($,W=10){return y0($,["log","-n",String(W),"--pretty=format:%s"])}async function VZ($){let{code:W,stderr:Z}=await O1($,["add","."]);if(W!==0){let Y=Z||"Unknown error";if(Y.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${Y}`)}}async function V6($,W,Z=!1,Y){let J=["commit","-m",W];if(Z)J.push("--no-verify");if(!Y){let{code:X,stderr:V}=await O1($,J);if(X!==0)throw Error(V||"Commit failed");return}return new Promise((X,V)=>{let H=iY("git",J,{cwd:$}),B="",K=(q,w,E)=>{let F=(E+q.toString()).split(`
1266
- `),R=F.pop()||"";for(let O of F)if(O.trim())Y(O,w);return R},Q="",U="";H.stdout?.on("data",(q)=>{Q=K(q,"stdout",Q)}),H.stderr?.on("data",(q)=>{B+=q.toString(),U=K(q,"stderr",U)}),H.on("error",(q)=>{V(q)}),H.on("close",(q)=>{if(Q.trim())Y(Q,"stdout");if(U.trim())Y(U,"stderr");if(q===0)X();else V(Error(B||"Commit failed"))})})}async function H6($){let{cwd:W}=$;if(!await XZ(W))return null;let[Z,Y,J,X,V]=await Promise.all([y0(W,["branch","--show-current"]),y0(W,["rev-parse","--abbrev-ref","origin/HEAD"]).then((B)=>B.replace("origin/","")).catch(()=>"main"),y0(W,["status","--short"]),y0(W,["log","--oneline","-n","5"]),y0(W,["config","user.email"])]),H=V?await y0(W,["log","--author",V,"--oneline","-n","5"]):"";return{branch:Z,mainBranch:Y,status:J,log:X,author:V,authorLog:H}}function B6($){if(!$)return null;return`
1263
+ - **Estimated cost: ${V}**`;return Z.sendMessage(K),{success:!0,message:"Cost summary displayed"}}},lY={name:"doctor",description:"Diagnose API connectivity and configuration health",fullDescription:"诊断 API 连通性和配置健康状况",usage:"/doctor",aliases:[],async handler($,W){let Z=C(W),J=Y0()?.models??[];if(J.length===0)return Z.sendMessage("❌ 没有配置任何模型。请先运行 `/init` 或编辑 `~/.blade/config.json`"),{success:!1,message:"No models configured"};let X=[`**API Connectivity Diagnosis**
1264
+ `];for(let V of J){let H=Date.now();try{let{createChatServiceAsync:K}=await import("./chunk-1vngdr7p.js"),U=await(await K({provider:V.provider,apiKey:V.apiKey,baseUrl:V.baseUrl,model:V.model,maxOutputTokens:10,temperature:0,timeout:1e4})).chat([{role:"user",content:"hi"}],void 0,AbortSignal.timeout(1e4)),Q=Date.now()-H,q=!!U.content;X.push(`✅ **${V.name}** (${V.model}) — ${Q}ms${q?"":" ⚠️ empty response"}`)}catch(K){let B=Date.now()-H,U=K instanceof Error?K.message.slice(0,80):"Unknown error";X.push(`❌ **${V.name}** (${V.model}) — ${B}ms — ${U}`)}}return Z.sendMessage(X.join(`
1265
+ `)),{success:!0,message:"Doctor diagnosis complete"}}},J6={help:hY,clear:uY,version:pY,status:dY,exit:gY,context:mY,cost:cY,doctor:lY,permissions:R2,resume:e8,rewind:W6,compact:m8,mcp:i8,memory:n8,agents:d8};import{execFile as X6,spawn as iY}from"child_process";import{promisify as rY}from"util";var nF=rY(X6);async function O1($,W){return new Promise((Z)=>{X6("git",W,{cwd:$,maxBuffer:10485760,encoding:"utf8"},(Y,J,X)=>{let V=Y==null?0:typeof Y.code==="number"?Y.code:1;Z({code:V,stdout:J||"",stderr:X||""})})})}async function nY($,W){let{code:Z}=await O1($,W);return Z===0}async function y0($,W){let{stdout:Z}=await O1($,W);return Z.trim()}async function XZ($){return nY($,["rev-parse","--is-inside-work-tree"])}async function D2($){return(await y0($,["status","--porcelain"])).length>0}async function aF($){return y0($,["branch","--show-current"])}async function j2($,W=10){return y0($,["log","-n",String(W),"--pretty=format:%s"])}async function VZ($){let{code:W,stderr:Z}=await O1($,["add","."]);if(W!==0){let Y=Z||"Unknown error";if(Y.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${Y}`)}}async function V6($,W,Z=!1,Y){let J=["commit","-m",W];if(Z)J.push("--no-verify");if(!Y){let{code:X,stderr:V}=await O1($,J);if(X!==0)throw Error(V||"Commit failed");return}return new Promise((X,V)=>{let H=iY("git",J,{cwd:$}),K="",B=(q,w,E)=>{let F=(E+q.toString()).split(`
1266
+ `),z=F.pop()||"";for(let O of F)if(O.trim())Y(O,w);return z},U="",Q="";H.stdout?.on("data",(q)=>{U=B(q,"stdout",U)}),H.stderr?.on("data",(q)=>{K+=q.toString(),Q=B(q,"stderr",Q)}),H.on("error",(q)=>{V(q)}),H.on("close",(q)=>{if(U.trim())Y(U,"stdout");if(Q.trim())Y(Q,"stderr");if(q===0)X();else V(Error(K||"Commit failed"))})})}async function H6($){let{cwd:W}=$;if(!await XZ(W))return null;let[Z,Y,J,X,V]=await Promise.all([y0(W,["branch","--show-current"]),y0(W,["rev-parse","--abbrev-ref","origin/HEAD"]).then((K)=>K.replace("origin/","")).catch(()=>"main"),y0(W,["status","--short"]),y0(W,["log","--oneline","-n","5"]),y0(W,["config","user.email"])]),H=V?await y0(W,["log","--author",V,"--oneline","-n","5"]):"";return{branch:Z,mainBranch:Y,status:J,log:X,author:V,authorLog:H}}function B6($){if(!$)return null;return`
1267
1267
  Git repository status (snapshot at conversation start):
1268
1268
  Current branch: ${$.branch}
1269
1269
  Main branch (target for PRs): ${$.mainBranch}
@@ -1276,14 +1276,14 @@ ${$.log||"(no commits)"}
1276
1276
 
1277
1277
  Your recent commits:
1278
1278
  ${$.authorLog||"(no recent commits)"}
1279
- `.trim()}async function D1($){return y0($,["diff","--cached","--name-status"])}async function _1($){let Z=["diff","--cached","--",...[":!bun.lock",":!pnpm-lock.yaml",":!package-lock.json",":!yarn.lock",":!*.min.js",":!*.bundle.js",":!dist/**",":!build/**",":!*.gz",":!*.zip",":!*.tar",":!*.tgz",":!*.woff",":!*.woff2",":!*.ttf",":!*.png",":!*.jpg",":!*.jpeg",":!*.gif",":!*.ico",":!*.svg",":!*.pdf"]],{code:Y,stdout:J,stderr:X}=await O1($,Z);if(Y!==0){let H=X||"Unknown error";if(H.includes("bad revision"))throw Error("Failed to get staged diff: Invalid Git revision or corrupt repository");if(H.includes("fatal: not a git repository"))throw Error("Not a Git repository");throw Error(`Failed to get staged diff: ${H}`)}let V=102400;if(J.length>V)return J.substring(0,V)+`
1279
+ `.trim()}async function _1($){return y0($,["diff","--cached","--name-status"])}async function D1($){let Z=["diff","--cached","--",...[":!bun.lock",":!pnpm-lock.yaml",":!package-lock.json",":!yarn.lock",":!*.min.js",":!*.bundle.js",":!dist/**",":!build/**",":!*.gz",":!*.zip",":!*.tar",":!*.tgz",":!*.woff",":!*.woff2",":!*.ttf",":!*.png",":!*.jpg",":!*.jpeg",":!*.gif",":!*.ico",":!*.svg",":!*.pdf"]],{code:Y,stdout:J,stderr:X}=await O1($,Z);if(Y!==0){let H=X||"Unknown error";if(H.includes("bad revision"))throw Error("Failed to get staged diff: Invalid Git revision or corrupt repository");if(H.includes("fatal: not a git repository"))throw Error("Not a Git repository");throw Error(`Failed to get staged diff: ${H}`)}let V=102400;if(J.length>V)return J.substring(0,V)+`
1280
1280
 
1281
1281
  [Diff truncated due to size. Total diff size: `+(J.length/1024).toFixed(2)+"KB]";return J}var aY={name:"git",description:"Git 仓库查询和 AI 辅助",usage:"/git [status|log|diff|review|commit|pre-commit]",aliases:["g"],examples:["/git","/git status","/git log 10","/git review","/git commit","/git pre-commit"],async handler($,W){let{cwd:Z}=W,Y=$[0]?.toLowerCase();if(!await XZ(Z))return{success:!1,error:"当前目录不在 Git 仓库中"};try{switch(Y){case"status":case"s":return K6(W);case"log":case"l":return oY(W,$[1]);case"diff":case"d":return sY(W);case"review":case"r":return tY(W);case"commit":case"c":return $J(W);case"pre-commit":case"pc":return eY(W);default:return K6(W)}}catch(J){return{success:!1,error:`Git 命令失败: ${J instanceof Error?J.message:"未知错误"}`}}}};async function K6($){let W=C($),Z=await H6({cwd:$.cwd});if(!Z)return{success:!1,error:"无法获取 Git 状态"};let Y=B6(Z);if(Y)W.sendMessage(`\`\`\`
1282
1282
  ${Y}
1283
1283
  \`\`\``);else W.sendMessage("无法获取 Git 状态信息");return{success:!0}}async function oY($,W){let Z=C($),Y=Math.min(Math.max(parseInt(W||"5",10)||5,1),50),J=await j2($.cwd,Y);if(!J)Z.sendMessage("暂无提交记录");else Z.sendMessage(`**最近 ${Y} 条提交:**
1284
1284
  \`\`\`
1285
1285
  ${J}
1286
- \`\`\``);return{success:!0}}async function sY($){let W=C($),{cwd:Z}=$,Y=await D1(Z);if(!Y)return W.sendMessage("暂存区为空,没有待提交的改动"),{success:!0};let J=await _1(Z),X=`**暂存文件:**
1286
+ \`\`\``);return{success:!0}}async function sY($){let W=C($),{cwd:Z}=$,Y=await _1(Z);if(!Y)return W.sendMessage("暂存区为空,没有待提交的改动"),{success:!0};let J=await D1(Z),X=`**暂存文件:**
1287
1287
  \`\`\`
1288
1288
  ${Y}
1289
1289
  \`\`\`
@@ -1291,7 +1291,7 @@ ${Y}
1291
1291
  **Diff:**
1292
1292
  \`\`\`diff
1293
1293
  ${J||"(无差异)"}
1294
- \`\`\``;return W.sendMessage(X),{success:!0}}async function tY($){let W=C($),{cwd:Z,signal:Y}=$;if(!await _2(Z))return W.sendMessage("没有未提交的改动,无需 Review"),{success:!0};W.sendMessage("正在分析代码改动...");let J=await D1(Z),X=await _1(Z);if(!X&&!J)return W.sendMessage("请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let V=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let H=Z0().session.sessionId,B=`请对以下 Git 改动进行 Code Review。
1294
+ \`\`\``;return W.sendMessage(X),{success:!0}}async function tY($){let W=C($),{cwd:Z,signal:Y}=$;if(!await D2(Z))return W.sendMessage("没有未提交的改动,无需 Review"),{success:!0};W.sendMessage("正在分析代码改动...");let J=await _1(Z),X=await D1(Z);if(!X&&!J)return W.sendMessage("请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let V=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let H=Z0().session.sessionId,K=`请对以下 Git 改动进行 Code Review。
1295
1295
 
1296
1296
  **暂存文件:**
1297
1297
  ${J||"(无)"}
@@ -1307,7 +1307,7 @@ ${X||"(无差异)"}
1307
1307
  3. **潜在问题**:指出可能的 bug、安全问题或性能问题
1308
1308
  4. **改进建议**:具体的代码改进建议
1309
1309
 
1310
- 如果改动很好,也请说明优点。保持简洁专业。`,Q=(await N0(V.chatStream(B,{messages:[],userId:"cli-user",sessionId:H||"git-review",workspaceRoot:Z,signal:Y}))).finalMessage||"";return W.sendMessage(Q),{success:!0}}async function eY($){let W=C($),{cwd:Z,signal:Y}=$;if(!await _2(Z))return W.sendMessage("没有未提交的改动"),{success:!0};W.sendMessage("暂存所有改动..."),await VZ(Z);let J=await D1(Z),X=await _1(Z);if(!J)return W.sendMessage("没有需要提交的改动"),{success:!0};W.sendMessage("正在生成 commit message...");let V=await j2(Z,5),H=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let B=Z0().session.sessionId,K=Q6(J,X,V),q=((await N0(H.chatStream(K,{messages:[],userId:"cli-user",sessionId:B||"git-pre-commit",workspaceRoot:Z,signal:Y}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return W.sendMessage(`**生成的 Commit Message:**
1310
+ 如果改动很好,也请说明优点。保持简洁专业。`,U=(await N0(V.chatStream(K,{messages:[],userId:"cli-user",sessionId:H||"git-review",workspaceRoot:Z,signal:Y}))).finalMessage||"";return W.sendMessage(U),{success:!0}}async function eY($){let W=C($),{cwd:Z,signal:Y}=$;if(!await D2(Z))return W.sendMessage("没有未提交的改动"),{success:!0};W.sendMessage("暂存所有改动..."),await VZ(Z);let J=await _1(Z),X=await D1(Z);if(!J)return W.sendMessage("没有需要提交的改动"),{success:!0};W.sendMessage("正在生成 commit message...");let V=await j2(Z,5),H=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let K=Z0().session.sessionId,B=U6(J,X,V),q=((await N0(H.chatStream(B,{messages:[],userId:"cli-user",sessionId:K||"git-pre-commit",workspaceRoot:Z,signal:Y}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return W.sendMessage(`**生成的 Commit Message:**
1311
1311
  \`\`\`
1312
1312
  ${q}
1313
1313
  \`\`\`
@@ -1316,10 +1316,10 @@ ${q}
1316
1316
  \`\`\`bash
1317
1317
  git commit -m "${q.split(`
1318
1318
  `)[0]}"
1319
- \`\`\``),{success:!0}}async function $J($){let W=C($),{cwd:Z,signal:Y}=$;if(!await _2(Z))return W.sendMessage("没有未提交的改动"),{success:!0};W.sendMessage("暂存所有改动..."),await VZ(Z);let J=await D1(Z),X=await _1(Z);if(!J)return W.sendMessage("没有需要提交的改动"),{success:!0};W.sendMessage("正在生成 commit message...");let V=await j2(Z,5),H=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let B=Z0().session.sessionId,K=Q6(J,X,V),q=((await N0(H.chatStream(K,{messages:[],userId:"cli-user",sessionId:B||"git-commit",workspaceRoot:Z,signal:Y}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();W.sendMessage(`**生成的 Commit Message:**
1319
+ \`\`\``),{success:!0}}async function $J($){let W=C($),{cwd:Z,signal:Y}=$;if(!await D2(Z))return W.sendMessage("没有未提交的改动"),{success:!0};W.sendMessage("暂存所有改动..."),await VZ(Z);let J=await _1(Z),X=await D1(Z);if(!J)return W.sendMessage("没有需要提交的改动"),{success:!0};W.sendMessage("正在生成 commit message...");let V=await j2(Z,5),H=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let K=Z0().session.sessionId,B=U6(J,X,V),q=((await N0(H.chatStream(B,{messages:[],userId:"cli-user",sessionId:K||"git-commit",workspaceRoot:Z,signal:Y}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();W.sendMessage(`**生成的 Commit Message:**
1320
1320
  \`\`\`
1321
1321
  ${q}
1322
- \`\`\``);try{await V6(Z,q),W.sendMessage("[OK] 提交成功!")}catch(w){let E=w instanceof Error?w.message:"未知错误";return W.sendMessage(`[FAIL] 提交失败: ${E}`),{success:!1,error:E}}return{success:!0}}function Q6($,W,Z){let Y=Z&&Z.trim().length>0;return`请根据以下 Git 改动生成一条 commit message。
1322
+ \`\`\``);try{await V6(Z,q),W.sendMessage("[OK] 提交成功!")}catch(w){let E=w instanceof Error?w.message:"未知错误";return W.sendMessage(`[FAIL] 提交失败: ${E}`),{success:!1,error:E}}return{success:!0}}function U6($,W,Z){let Y=Z&&Z.trim().length>0;return`请根据以下 Git 改动生成一条 commit message。
1323
1323
 
1324
1324
  **暂存文件:**
1325
1325
  ${$}
@@ -1340,7 +1340,7 @@ ${Z}
1340
1340
  1. ${Y?"严格模仿历史提交的语言和格式风格":"使用英文,遵循 Conventional Commits 格式(feat:, fix:, docs:, refactor:, chore: 等)"}
1341
1341
  2. 第一行简明扼要,不超过 72 字符
1342
1342
  3. 如有必要,可添加空行后的详细说明
1343
- 4. 只输出 commit message 内容,不要其他解释或代码块标记`}var U6=aY;var WJ={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
1343
+ 4. 只输出 commit message 内容,不要其他解释或代码块标记`}var Q6=aY;var WJ={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
1344
1344
 
1345
1345
  子命令:
1346
1346
  /hooks - 打开交互式 hooks 管理界面(添加新 hook)
@@ -1348,15 +1348,15 @@ ${Z}
1348
1348
  /hooks status - 显示 hooks 启用状态和统计
1349
1349
  /hooks enable - 启用当前会话的 hooks
1350
1350
  /hooks disable - 禁用当前会话的 hooks
1351
- /hooks list - 列出所有配置的 hooks`,usage:"/hooks [add|status|enable|disable|list]",category:"system",examples:["/hooks","/hooks add","/hooks status","/hooks enable","/hooks disable","/hooks list"],handler:async($,W)=>{let Z=$[0]?.toLowerCase()||"",Y=w0.getInstance();switch(Z){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return ZJ(Y);case"enable":return Y.enable(),L().addAssistantMessage("[OK] Hooks 已启用(当前会话)"),{success:!0,message:"Hooks enabled"};case"disable":return Y.disable(),L().addAssistantMessage("Hooks 已禁用(当前会话)"),{success:!0,message:"Hooks disabled"};case"list":return YJ(Y);default:return L().addAssistantMessage(`未知子命令: ${Z}
1352
- 使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${Z}`}}}};function ZJ($){let W=$.isEnabled(),Z=$.getConfig(),Y={};for(let X of Object.values(HZ)){let V=Z[X];if(V&&Array.isArray(V)){let H=V.reduce((B,K)=>B+(K.hooks?.length||0),0);if(H>0)Y[X]=H}}let J=["## Hooks 状态","",`**状态**: ${W?"[OK] 启用":"禁用"}`,""];if(Object.keys(Y).length>0){J.push("**已配置的 Hooks**:"),J.push("");for(let[X,V]of Object.entries(Y))J.push(`- ${X}: ${V} 个 hook`)}else J.push("*没有配置任何 hooks*");return J.push(""),J.push("---"),J.push("使用 `/hooks list` 查看详细配置"),J.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),L().addAssistantMessage(J.join(`
1353
- `)),{success:!0,message:"Hooks status displayed"}}function YJ($){let W=$.getConfig(),Z=["## Hooks 配置详情",""],Y=!1;for(let J of Object.values(HZ)){let X=W[J];if(!X||!Array.isArray(X)||X.length===0)continue;Y=!0,Z.push(`### ${J}`),Z.push("");for(let V=0;V<X.length;V++){let H=X[V],B=H.name||`Matcher ${V+1}`,K=H.matcher,Q="所有";if(K){let U=[];if(K.tools){let q=Array.isArray(K.tools)?K.tools.join(", "):K.tools;U.push(`工具: ${q}`)}if(K.paths){let q=Array.isArray(K.paths)?K.paths.join(", "):K.paths;U.push(`路径: ${q}`)}if(K.commands){let q=Array.isArray(K.commands)?K.commands.join(", "):K.commands;U.push(`命令: ${q}`)}if(U.length>0)Q=U.join("; ")}Z.push(`**${B}** (匹配: ${Q})`);for(let U of H.hooks||[])if(U.type==="command")Z.push(` - \`${U.command}\``);else if(U.type==="prompt"){let q=U.prompt.slice(0,50)+(U.prompt.length>50?"...":"");Z.push(` - [prompt] ${q}`)}Z.push("")}}if(!Y)Z.push("*没有配置任何 hooks*"),Z.push(""),Z.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return L().addAssistantMessage(Z.join(`
1354
- `)),{success:!0,message:"Hooks config listed"}}var q6=WJ;import{existsSync as BJ,readFileSync as KJ}from"fs";import{homedir as QJ}from"os";import{join as UJ}from"path";import{exec as JJ}from"child_process";import{promisify as XJ}from"util";var w6=XJ(JJ);class BZ{static async detectIde(){let $=process.env.TERM_PROGRAM,W=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;if($==="vscode"||W||Z)return await this.detectVsCode();let Y=await this.detectVsCode();if(Y)return Y;return null}static async detectVsCode(){try{let{stdout:$}=await w6("code --version"),Z=$.trim().split(`
1351
+ /hooks list - 列出所有配置的 hooks`,usage:"/hooks [add|status|enable|disable|list]",category:"system",examples:["/hooks","/hooks add","/hooks status","/hooks enable","/hooks disable","/hooks list"],handler:async($,W)=>{let Z=$[0]?.toLowerCase()||"",Y=w0.getInstance();switch(Z){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return ZJ(Y);case"enable":return Y.enable(),k().addAssistantMessage("[OK] Hooks 已启用(当前会话)"),{success:!0,message:"Hooks enabled"};case"disable":return Y.disable(),k().addAssistantMessage("Hooks 已禁用(当前会话)"),{success:!0,message:"Hooks disabled"};case"list":return YJ(Y);default:return k().addAssistantMessage(`未知子命令: ${Z}
1352
+ 使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${Z}`}}}};function ZJ($){let W=$.isEnabled(),Z=$.getConfig(),Y={};for(let X of Object.values(HZ)){let V=Z[X];if(V&&Array.isArray(V)){let H=V.reduce((K,B)=>K+(B.hooks?.length||0),0);if(H>0)Y[X]=H}}let J=["## Hooks 状态","",`**状态**: ${W?"[OK] 启用":"禁用"}`,""];if(Object.keys(Y).length>0){J.push("**已配置的 Hooks**:"),J.push("");for(let[X,V]of Object.entries(Y))J.push(`- ${X}: ${V} 个 hook`)}else J.push("*没有配置任何 hooks*");return J.push(""),J.push("---"),J.push("使用 `/hooks list` 查看详细配置"),J.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),k().addAssistantMessage(J.join(`
1353
+ `)),{success:!0,message:"Hooks status displayed"}}function YJ($){let W=$.getConfig(),Z=["## Hooks 配置详情",""],Y=!1;for(let J of Object.values(HZ)){let X=W[J];if(!X||!Array.isArray(X)||X.length===0)continue;Y=!0,Z.push(`### ${J}`),Z.push("");for(let V=0;V<X.length;V++){let H=X[V],K=H.name||`Matcher ${V+1}`,B=H.matcher,U="所有";if(B){let Q=[];if(B.tools){let q=Array.isArray(B.tools)?B.tools.join(", "):B.tools;Q.push(`工具: ${q}`)}if(B.paths){let q=Array.isArray(B.paths)?B.paths.join(", "):B.paths;Q.push(`路径: ${q}`)}if(B.commands){let q=Array.isArray(B.commands)?B.commands.join(", "):B.commands;Q.push(`命令: ${q}`)}if(Q.length>0)U=Q.join("; ")}Z.push(`**${K}** (匹配: ${U})`);for(let Q of H.hooks||[])if(Q.type==="command")Z.push(` - \`${Q.command}\``);else if(Q.type==="prompt"){let q=Q.prompt.slice(0,50)+(Q.prompt.length>50?"...":"");Z.push(` - [prompt] ${q}`)}Z.push("")}}if(!Y)Z.push("*没有配置任何 hooks*"),Z.push(""),Z.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return k().addAssistantMessage(Z.join(`
1354
+ `)),{success:!0,message:"Hooks config listed"}}var q6=WJ;import{existsSync as BJ,readFileSync as KJ}from"fs";import{homedir as UJ}from"os";import{join as QJ}from"path";import{exec as JJ}from"child_process";import{promisify as XJ}from"util";var w6=XJ(JJ);class BZ{static async detectIde(){let $=process.env.TERM_PROGRAM,W=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;if($==="vscode"||W||Z)return await this.detectVsCode();let Y=await this.detectVsCode();if(Y)return Y;return null}static async detectVsCode(){try{let{stdout:$}=await w6("code --version"),Z=$.trim().split(`
1355
1355
  `)[0]||"unknown",Y=[];try{let{stdout:J}=await w6("code --list-extensions");Y=J.trim().split(`
1356
1356
  `).filter(Boolean)}catch{}return{name:"VS Code",version:Z,extensions:Y}}catch{return null}}static isRunningInIdeTerminal(){let $=process.env.TERM_PROGRAM,W=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;return $==="vscode"||!!W||!!Z}}import{exec as VJ}from"child_process";import{promisify as HJ}from"util";var A2=HJ(VJ);class j1{static async getInstalledIdes(){let $=[],W=await this.checkVsCode();if(W)$.push(W);let Z=await this.checkVsCodeInsiders();if(Z)$.push(Z);let Y=await this.checkCursor();if(Y)$.push(Y);return $}static async isIdeInstalled($){switch($){case"vscode":return await this.checkVsCode()!==null;case"vscode-insiders":return await this.checkVsCodeInsiders()!==null;case"cursor":return await this.checkCursor()!==null;default:return!1}}static async installExtension($){let W;switch($){case"vscode":W="code --install-extension blade-code.blade-code";break;case"vscode-insiders":W="code-insiders --install-extension blade-code.blade-code";break;case"cursor":W="cursor --install-extension blade-code.blade-code";break;default:return{success:!1,message:"不支持的 IDE: "+$}}try{return await A2(W),{success:!0,message:"扩展安装成功"}}catch(Z){return{success:!1,message:"安装失败: "+(Z instanceof Error?Z.message:"未知错误")}}}static async checkVsCode(){try{let{stdout:$}=await A2("code --version");return{id:"vscode",name:"VS Code",version:$.trim().split(`
1357
1357
  `)[0]||"unknown"}}catch{return null}}static async checkVsCodeInsiders(){try{let{stdout:$}=await A2("code-insiders --version");return{id:"vscode-insiders",name:"VS Code Insiders",version:$.trim().split(`
1358
1358
  `)[0]||"unknown"}}catch{return null}}static async checkCursor(){try{let{stdout:$}=await A2("cursor --version");return{id:"cursor",name:"Cursor",version:$.trim().split(`
1359
- `)[0]||"unknown"}}catch{return null}}}var G6=UJ(QJ(),".blade","ide-port");var n$="disconnected",KZ=null,QZ=null;function qJ(){switch(n$){case"connected":return{type:"info",content:`[OK] 已连接到 ${KZ||"IDE"} (端口: ${QZ})`};case"connecting":return{type:"info",content:"正在连接..."};default:return{type:"error",content:"未连接到 IDE"}}}function E6(){try{if(BJ(G6)){let $=KJ(G6,"utf-8");return JSON.parse($)}}catch{}return null}function F6(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let W=E6();if(W)return W.port;return null}async function wJ(){let $=[],W=qJ();$.push(W.content),$.push(""),$.push("已安装的 IDE:");let Z=await j1.getInstalledIdes();if(Z.length===0)$.push(" (未检测到支持的 IDE)");else for(let V of Z)$.push(` • ${V.name} ${V.version}`);$.push("");let Y=await BZ.detectIde();if(Y){if($.push(`当前环境: ${Y.name} ${Y.version}`),Y.extensions.length>0)$.push(` 已安装扩展: ${Y.extensions.length} 个`)}let J=F6(),X=E6();if(J){if($.push(`IDE 端口: ${J}`),X&&X.workspaceFolders.length>0)$.push(` 工作区: ${X.workspaceFolders[0]}`)}else $.push(""),$.push("提示: 在 VS Code 中安装 Blade Code 插件后,运行 /ide connect 连接");return $.join(`
1359
+ `)[0]||"unknown"}}catch{return null}}}var G6=QJ(UJ(),".blade","ide-port");var n$="disconnected",KZ=null,UZ=null;function qJ(){switch(n$){case"connected":return{type:"info",content:`[OK] 已连接到 ${KZ||"IDE"} (端口: ${UZ})`};case"connecting":return{type:"info",content:"正在连接..."};default:return{type:"error",content:"未连接到 IDE"}}}function E6(){try{if(BJ(G6)){let $=KJ(G6,"utf-8");return JSON.parse($)}}catch{}return null}function F6(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let W=E6();if(W)return W.port;return null}async function wJ(){let $=[],W=qJ();$.push(W.content),$.push(""),$.push("已安装的 IDE:");let Z=await j1.getInstalledIdes();if(Z.length===0)$.push(" (未检测到支持的 IDE)");else for(let V of Z)$.push(` • ${V.name} ${V.version}`);$.push("");let Y=await BZ.detectIde();if(Y){if($.push(`当前环境: ${Y.name} ${Y.version}`),Y.extensions.length>0)$.push(` 已安装扩展: ${Y.extensions.length} 个`)}let J=F6(),X=E6();if(J){if($.push(`IDE 端口: ${J}`),X&&X.workspaceFolders.length>0)$.push(` 工作区: ${X.workspaceFolders[0]}`)}else $.push(""),$.push("提示: 在 VS Code 中安装 Blade Code 插件后,运行 /ide connect 连接");return $.join(`
1360
1360
  `)}async function GJ(){let $=F6();if(!$)return`未检测到 IDE 端口
1361
1361
 
1362
1362
  请确保:
@@ -1365,7 +1365,7 @@ ${Z}
1365
1365
  3. 在 VS Code 终端中运行 blade
1366
1366
 
1367
1367
  或手动设置端口:
1368
- export BLADE_IDE_PORT=9527`;n$="connecting";try{let Z=new(await import("ws")).default(`ws://127.0.0.1:${$}`);return await new Promise((Y,J)=>{let X=setTimeout(()=>{Z.close(),J(Error("连接超时"))},5000);Z.on("open",()=>{clearTimeout(X),n$="connected",QZ=$,KZ="VS Code",Z.close(),Y()}),Z.on("error",(V)=>{clearTimeout(X),J(V)})}),`[OK] 成功连接到 IDE (端口: ${$})
1368
+ export BLADE_IDE_PORT=9527`;n$="connecting";try{let Z=new(await import("ws")).default(`ws://127.0.0.1:${$}`);return await new Promise((Y,J)=>{let X=setTimeout(()=>{Z.close(),J(Error("连接超时"))},5000);Z.on("open",()=>{clearTimeout(X),n$="connected",UZ=$,KZ="VS Code",Z.close(),Y()}),Z.on("error",(V)=>{clearTimeout(X),J(V)})}),`[OK] 成功连接到 IDE (端口: ${$})
1369
1369
 
1370
1370
  现在可以使用以下功能:
1371
1371
  • 在 IDE 中打开文件
@@ -1377,13 +1377,13 @@ ${Z}
1377
1377
  2. 端口 ${$} 是否正确
1378
1378
  3. 防火墙设置`}}async function EJ(){let $=[];if($.push("安装 Blade Code VS Code 插件"),$.push(""),!await j1.isIdeInstalled("vscode"))return $.push("未检测到 VS Code"),$.push(""),$.push("请先安装 VS Code:"),$.push(" https://code.visualstudio.com/"),$.join(`
1379
1379
  `);return $.push("[OK] 检测到 VS Code"),$.push(""),$.push("安装方式:"),$.push(""),$.push("从 VSIX 文件安装:"),$.push(" 1. 下载插件: https://github.com/anthropics/blade-code/releases"),$.push(" 2. 运行: code --install-extension blade-code-x.x.x.vsix"),$.push(""),$.push("或从源码构建:"),$.push(" cd packages/vscode && bun install && bun run package"),$.push(" code --install-extension blade-code-0.0.1.vsix"),$.push(""),$.push("安装完成后,在 VS Code 终端中运行 blade 即可自动连接"),$.join(`
1380
- `)}async function FJ(){if(n$==="disconnected")return"[WARN] 当前未连接到任何 IDE";return n$="disconnected",KZ=null,QZ=null,"[OK] 已断开与 IDE 的连接"}var zJ={name:"ide",aliases:[],description:"Manage IDE integrations and show status",usage:"/ide [status|connect|install|disconnect]",category:"system",async handler($,W){let Z=($[0]||"").toLowerCase(),Y;switch(Z){case"":case"status":Y=await wJ();break;case"connect":Y=await GJ();break;case"install":Y=await EJ();break;case"disconnect":Y=await FJ();break;default:Y=`未知的子命令: ${Z}
1380
+ `)}async function FJ(){if(n$==="disconnected")return"[WARN] 当前未连接到任何 IDE";return n$="disconnected",KZ=null,UZ=null,"[OK] 已断开与 IDE 的连接"}var zJ={name:"ide",aliases:[],description:"Manage IDE integrations and show status",usage:"/ide [status|connect|install|disconnect]",category:"system",async handler($,W){let Z=($[0]||"").toLowerCase(),Y;switch(Z){case"":case"status":Y=await wJ();break;case"connect":Y=await GJ();break;case"install":Y=await EJ();break;case"disconnect":Y=await FJ();break;default:Y=`未知的子命令: ${Z}
1381
1381
 
1382
1382
  可用命令:
1383
1383
  /ide status - 显示连接状态
1384
1384
  /ide connect - 连接到 IDE
1385
1385
  /ide install - 安装 VS Code 插件
1386
- /ide disconnect - 断开连接`}return{success:!0,message:Y}}},z6=zJ;import{promises as A1}from"fs";import*as R6 from"path";var a$=P("Agent"),RJ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,W){try{let{cwd:Z,signal:Y}=W,J=C(W),X=(E)=>{J.sendMessage(`${E}`)},V=Z0().session.sessionId,H=R6.join(Z,"BLADE.md"),B=!1,K=!1;try{if(B=(await A1.stat(H)).isFile(),B)K=(await A1.readFile(H,"utf-8")).trim().length===0}catch{B=!1}if(B&&!K){J.sendMessage("[WARN] BLADE.md 已存在。"),J.sendMessage("正在分析现有文件并提供改进建议...");let E=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let G=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1386
+ /ide disconnect - 断开连接`}return{success:!0,message:Y}}},z6=zJ;import{promises as A1}from"fs";import*as R6 from"path";var a$=f("Agent"),RJ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,W){try{let{cwd:Z,signal:Y}=W,J=C(W),X=(E)=>{J.sendMessage(`${E}`)},V=Z0().session.sessionId,H=R6.join(Z,"BLADE.md"),K=!1,B=!1;try{if(K=(await A1.stat(H)).isFile(),K)B=(await A1.readFile(H,"utf-8")).trim().length===0}catch{K=!1}if(K&&!B){J.sendMessage("[WARN] BLADE.md 已存在。"),J.sendMessage("正在分析现有文件并提供改进建议...");let E=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let G=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1387
1387
 
1388
1388
  **Important**:
1389
1389
  - After each step, briefly describe what you found before proceeding
@@ -1422,7 +1422,7 @@ ${Z}
1422
1422
  - 具体的改进建议(附带示例)
1423
1423
  - 如果需要重大修改,提供完整的改进版本内容
1424
1424
 
1425
- **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;a$.info(`[/init] Starting agent.chatStream, signal.aborted: ${Y?.aborted}`);let R=(await N0(E.chatStream(G,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:Z,signal:Y}),async(O)=>{switch(O.kind){case"tool_start":{let _=O.toolCall;if(!("function"in _))return;try{let z=JSON.parse(_.function.arguments),N=dW(_.function.name,z);X(N)}catch{}break}case"tool_result":{if(!("function"in O.toolCall))return;let z=O.result.metadata?.summary;if(z)X(z);break}default:break}})).finalMessage||"";if(a$.info(`[/init] agent.chatStream completed, signal.aborted: ${Y?.aborted}`),Y?.aborted)return a$.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return J.sendMessage(R),{success:!0,message:"[OK] 分析完成"}}if(K)J.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");J.sendMessage("正在分析项目结构...");let Q=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let U=`Please analyze this codebase and generate BLADE.md content.
1425
+ **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;a$.info(`[/init] Starting agent.chatStream, signal.aborted: ${Y?.aborted}`);let z=(await N0(E.chatStream(G,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:Z,signal:Y}),async(O)=>{switch(O.kind){case"tool_start":{let _=O.toolCall;if(!("function"in _))return;try{let R=JSON.parse(_.function.arguments),j=dW(_.function.name,R);X(j)}catch{}break}case"tool_result":{if(!("function"in O.toolCall))return;let R=O.result.metadata?.summary;if(R)X(R);break}default:break}})).finalMessage||"";if(a$.info(`[/init] agent.chatStream completed, signal.aborted: ${Y?.aborted}`),Y?.aborted)return a$.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return J.sendMessage(z),{success:!0,message:"[OK] 分析完成"}}if(B)J.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");J.sendMessage("正在分析项目结构...");let U=await B0.create();if(Y?.aborted)return{success:!1,message:"操作已取消"};let Q=`Please analyze this codebase and generate BLADE.md content.
1426
1426
 
1427
1427
  **Important**: After each step, briefly describe what you found before proceeding.
1428
1428
 
@@ -1468,7 +1468,7 @@ ${Z}
1468
1468
  - Focus on non-obvious insights
1469
1469
  - Be concise but comprehensive for complex projects
1470
1470
 
1471
- **Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;a$.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${Y?.aborted}`);let w=(await N0(Q.chatStream(U,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:Z,signal:Y}),async(E)=>{switch(E.kind){case"tool_start":{let G=E.toolCall;if(!("function"in G))return;try{let F=JSON.parse(G.function.arguments),R=dW(G.function.name,F);X(R)}catch{}break}case"tool_result":{if(!("function"in E.toolCall))return;let F=E.result?.metadata;if(F?.summary){if(typeof F.summary==="string")X(F.summary)}break}default:break}})).finalMessage||"";if(a$.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${Y?.aborted}`),Y?.aborted)return a$.info("[/init] Returning cancelled after agent.chat (new BLADE.md)"),{success:!1,message:"操作已取消"};if(!w||w.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return J.sendMessage("正在写入 BLADE.md..."),await A1.writeFile(H,w,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(Z){return{success:!1,error:`初始化失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}},O6=RJ;var OJ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
1471
+ **Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;a$.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${Y?.aborted}`);let w=(await N0(U.chatStream(Q,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:Z,signal:Y}),async(E)=>{switch(E.kind){case"tool_start":{let G=E.toolCall;if(!("function"in G))return;try{let F=JSON.parse(G.function.arguments),z=dW(G.function.name,F);X(z)}catch{}break}case"tool_result":{if(!("function"in E.toolCall))return;let F=E.result?.metadata;if(F?.summary){if(typeof F.summary==="string")X(F.summary)}break}default:break}})).finalMessage||"";if(a$.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${Y?.aborted}`),Y?.aborted)return a$.info("[/init] Returning cancelled after agent.chat (new BLADE.md)"),{success:!1,message:"操作已取消"};if(!w||w.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return J.sendMessage("正在写入 BLADE.md..."),await A1.writeFile(H,w,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(Z){return{success:!1,error:`初始化失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}},O6=RJ;var OJ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
1472
1472
  管理和切换模型配置
1473
1473
 
1474
1474
  子命令:
@@ -1486,7 +1486,7 @@ ${Z}
1486
1486
 
1487
1487
  使用 /model add 添加模型`};return{success:!0,message:"show_model_selector",data:{action:"show_model_selector"}}}switch(Z){case"add":return{success:!0,message:"show_model_add_wizard",data:{action:"show_model_add_wizard",mode:"add"}};case"remove":{let Y=$.slice(1).join(" ");if(!Y)return{success:!1,message:`请指定要删除的模型名称
1488
1488
  用法: /model remove <名称>`};let X=W$().find((V)=>V.name.toLowerCase().includes(Y.toLowerCase()));if(!X)return{success:!1,message:`未找到匹配的模型配置: ${Y}`};try{return await a0().removeModel(X.id),{success:!0,message:`[OK] 已删除模型配置: ${X.name}`}}catch(V){return{success:!1,message:`${V.message}`}}}case"once":{let Y=$[1],J=$.slice(2).join(" ").trim();if(!Y||!J)return{success:!1,message:"用法: /model once <模型> <内容>"};let X=W$(),V=X.find((H)=>H.id===Y)||X.find((H)=>H.name.toLowerCase().includes(Y.toLowerCase()));if(!V)return{success:!1,message:`未找到匹配的模型配置: ${Y}`};return{success:!0,data:{action:"invoke_once_model",modelId:V.id,prompt:J}}}default:return{success:!1,message:`未知的子命令: ${Z}
1489
- 使用 /model 查看可用操作`}}}},D6=OJ;var DJ={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
1489
+ 使用 /model 查看可用操作`}}}},_6=OJ;var _J={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
1490
1490
 
1491
1491
  子命令:
1492
1492
  /plugins - 打开插件管理界面
@@ -1498,27 +1498,27 @@ ${Z}
1498
1498
  /plugins enable <name> - 启用插件
1499
1499
  /plugins disable <name> - 禁用插件
1500
1500
  /plugins refresh - 刷新插件列表
1501
- /plugins stats - 显示插件统计信息`,usage:"/plugins [list|info|install|uninstall|update|enable|disable|refresh|stats] [name/url]",category:"system",examples:["/plugins","/plugins list","/plugins info my-plugin","/plugins install user/repo","/plugins install https://github.com/user/repo","/plugins uninstall my-plugin","/plugins update my-plugin","/plugins enable my-plugin","/plugins disable my-plugin","/plugins refresh","/plugins stats"],handler:async($,W)=>{let Z=$[0]?.toLowerCase()||"",Y=m0();switch(Z){case"":return await TJ(Y),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return _J(Y);case"info":return jJ(Y,$[1]);case"install":case"add":return MJ($[1]);case"uninstall":case"remove":case"rm":return vJ($[1]);case"update":case"upgrade":return xJ($[1]);case"enable":return AJ(Y,$[1]);case"disable":return NJ(Y,$[1]);case"refresh":return LJ(Y);case"stats":return kJ(Y);default:return L().addAssistantMessage(`未知子命令: ${Z}
1502
- 使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${Z}`}}}};function _J($){if($.getAll().length===0)return L().addAssistantMessage(`没有已加载的插件。
1503
-
1504
- `+"使用 `--plugin-dir <path>` 参数加载插件,或将插件放置在:\n"+"- `~/.blade/plugins/` - 用户级插件\n"+"- `.blade/plugins/` - 项目级插件"),{success:!0,message:"No plugins loaded"};let Z=["## 已加载的插件",""],Y=$.getBySource();if(Y.cli.length>0){Z.push("### CLI 指定");for(let J of Y.cli){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}Z.push("")}if(Y.project.length>0){Z.push("### 项目级");for(let J of Y.project){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}Z.push("")}if(Y.user.length>0){Z.push("### 用户级");for(let J of Y.user){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}}return L().addAssistantMessage(Z.join(`
1505
- `)),{success:!0,message:"Plugins listed"}}function jJ($,W){if(!W)return L().addAssistantMessage("请指定插件名称: `/plugins info <name>`"),{success:!1,error:"Plugin name required"};let Z=$.get(W);if(!Z)return L().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};let Y=[`## ${Z.manifest.name}`,"",`**版本**: ${Z.manifest.version}`,`**描述**: ${Z.manifest.description}`,`**状态**: ${Z.status==="active"?"[OK] 启用":"禁用"}`,`**来源**: ${bJ(Z.source)}`,`**路径**: \`${Z.basePath}\``,""];if(Z.manifest.author)Y.push(`**作者**: ${Z.manifest.author.name}`);if(Z.manifest.license)Y.push(`**许可证**: ${Z.manifest.license}`);if(Z.manifest.repository)Y.push(`**仓库**: ${Z.manifest.repository}`);if(Z.commands.length>0){Y.push(""),Y.push(`### 命令 (${Z.commands.length})`);for(let J of Z.commands){let X=J.config.argumentHint?` ${J.config.argumentHint}`:"",V=J.config.description?` - ${J.config.description}`:"";Y.push(`- \`/${J.namespacedName}${X}\`${V}`)}}if(Z.skills.length>0){Y.push(""),Y.push(`### 技能 (${Z.skills.length})`);for(let J of Z.skills)Y.push(`- \`${J.namespacedName}\` - ${J.metadata.description}`)}if(Z.agents.length>0){Y.push(""),Y.push(`### 代理 (${Z.agents.length})`);for(let J of Z.agents)Y.push(`- \`${J.namespacedName}\` - ${J.config.description}`)}if(Z.mcpServers){let J=Object.keys(Z.mcpServers).length;Y.push(""),Y.push(`### MCP 服务器 (${J})`);for(let X of Object.keys(Z.mcpServers))Y.push(`- \`${X}\``)}if(Z.hooks)Y.push(""),Y.push("### Hooks"),Y.push("插件已配置 hooks");return L().addAssistantMessage(Y.join(`
1506
- `)),{success:!0,message:"Plugin info displayed"}}function AJ($,W){if(!W)return L().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(W))return L().addAssistantMessage(`[OK] 已启用插件: ${W}`),{success:!0,message:`Plugin ${W} enabled`};if(!$.get(W))return L().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};return L().addAssistantMessage(`插件 ${W} 已经是启用状态`),{success:!0,message:`Plugin ${W} already enabled`}}function NJ($,W){if(!W)return L().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(W))return L().addAssistantMessage(`已禁用插件: ${W}`),{success:!0,message:`Plugin ${W} disabled`};if(!$.get(W))return L().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};return L().addAssistantMessage(`插件 ${W} 已经是禁用状态`),{success:!0,message:`Plugin ${W} already disabled`}}async function TJ($){F2(),await $.refresh(),await E2()}async function LJ($){try{F2();let W=await $.refresh(),Z=await E2(),Y=["[OK] 已刷新插件列表","",`- 加载了 ${W.plugins.length} 个插件`,`- 集成了 ${Z.totalCommands} 个命令, ${Z.totalSkills} 个技能, ${Z.totalAgents} 个代理`];if(W.errors.length>0){Y.push(`- ${W.errors.length} 个加载错误`),Y.push(""),Y.push("### 错误");for(let J of W.errors)Y.push(`- \`${J.path}\`: ${J.error}`)}if(Z.errors.length>0){Y.push(""),Y.push("### 集成错误");for(let J of Z.errors)Y.push(`- ${J}`)}return L().addAssistantMessage(Y.join(`
1507
- `)),{success:!0,message:"Plugins refreshed"}}catch(W){let Z=W instanceof Error?W.message:String(W);return L().addAssistantMessage(`刷新失败: ${Z}`),{success:!1,error:Z}}}function kJ($){let W=$.getStats(),Z=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${W.total} |`,`| 启用 | ${W.active} |`,`| 禁用 | ${W.inactive} |`,`| 命令 | ${W.commands} |`,`| 技能 | ${W.skills} |`,`| 代理 | ${W.agents} |`];return L().addAssistantMessage(Z.join(`
1508
- `)),{success:!0,message:"Stats displayed"}}function bJ($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function MJ($){if(!$)return L().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
1509
- `+"- GitHub 简写: `user/repo`\n"+"- 完整 URL: `https://github.com/user/repo`"),{success:!1,error:"Plugin URL required"};L().addAssistantMessage(`正在安装插件: ${$}...`);let Z=await z1().install($);if(Z.success){let Y=["[OK] 插件安装成功!","",`**名称**: ${Z.pluginName}`,`**路径**: \`${Z.pluginPath}\``];if(Z.manifest)Y.push(`**版本**: ${Z.manifest.version}`),Y.push(`**描述**: ${Z.manifest.description}`);return Y.push(""),Y.push("使用 `/plugins refresh` 加载新安装的插件。"),L().addAssistantMessage(Y.join(`
1510
- `)),{success:!0,message:`Installed ${Z.pluginName}`}}return L().addAssistantMessage(`安装失败: ${Z.error}`),{success:!1,error:Z.error}}async function vJ($){if(!$)return L().addAssistantMessage("请指定插件名称: `/plugins uninstall <name>`"),{success:!1,error:"Plugin name required"};let Z=await z1().uninstall($);if(Z.success)return L().addAssistantMessage(`[OK] 已卸载插件: ${Z.pluginName}
1511
-
1512
- `+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${Z.pluginName}`};return L().addAssistantMessage(`卸载失败: ${Z.error}`),{success:!1,error:Z.error}}async function xJ($){if(!$)return L().addAssistantMessage("请指定插件名称: `/plugins update <name>`"),{success:!1,error:"Plugin name required"};L().addAssistantMessage(`正在更新插件: ${$}...`);let Z=await z1().update($);if(Z.success){let Y=["[OK] 插件更新成功!","",`**名称**: ${Z.pluginName}`];if(Z.manifest)Y.push(`**版本**: ${Z.manifest.version}`);return Y.push(""),Y.push("使用 `/plugins refresh` 重新加载插件。"),L().addAssistantMessage(Y.join(`
1513
- `)),{success:!0,message:`Updated ${Z.pluginName}`}}return L().addAssistantMessage(`更新失败: ${Z.error}`),{success:!1,error:Z.error}}var _6=DJ;import{createReadStream as CJ}from"node:fs";import*as N2 from"node:fs/promises";import*as T2 from"node:path";import{createInterface as yJ}from"node:readline";async function j6($,W={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:J,storagePath:X}=W,V=X??$$(J??D()),H;try{H=(await N2.readdir(V)).filter((w)=>w.endsWith(".jsonl")&&!w.startsWith("agent_")).map((w)=>T2.join(V,w))}catch{return[]}let K=(await Promise.all(H.map(async(q)=>{try{let w=await N2.stat(q);return{path:q,mtime:w.mtimeMs}}catch{return null}}))).filter((q)=>q!==null).sort((q,w)=>w.mtime-q.mtime).map((q)=>q.path),Q=[],U=Y?$:$.toLowerCase();for(let q of K){if(Q.length>=Z)break;let w=T2.basename(q,".jsonl"),E=await PJ(q,U,Y,w);if(Q.push(...E),Q.length>=Z){Q.length=Z;break}}return Q}async function PJ($,W,Z,Y){let J=[];try{let X=CJ($,{encoding:"utf-8"}),V=yJ({input:X,crlfDelay:1/0}),H=0;for await(let B of V){if(H++,!B.trim())continue;try{let K=JSON.parse(B);if(K.type!=="message")continue;if(!K.message?.content)continue;let Q=K.message.role;if(Q!=="user"&&Q!=="assistant")continue;let U=typeof K.message.content==="string"?K.message.content:Array.isArray(K.message.content)?K.message.content.filter((R)=>R.type==="text").map((R)=>R.text).join(" "):"";if(!U)continue;let q=Z?U:U.toLowerCase();if(!q.includes(W))continue;let w=q.indexOf(W),E=Math.max(0,w-80),G=Math.min(U.length,w+W.length+80),F=(E>0?"...":"")+U.slice(E,G).replace(/\n/g," ")+(G<U.length?"...":"");J.push({sessionId:Y,role:Q,content:F,timestamp:K.timestamp,lineNumber:H})}catch{}}}catch{}return J}function A6($){if($.length===0)return"没有找到匹配的历史记录";let W=[`**找到 ${$.length} 条匹配:**
1501
+ /plugins stats - 显示插件统计信息`,usage:"/plugins [list|info|install|uninstall|update|enable|disable|refresh|stats] [name/url]",category:"system",examples:["/plugins","/plugins list","/plugins info my-plugin","/plugins install user/repo","/plugins install https://github.com/user/repo","/plugins uninstall my-plugin","/plugins update my-plugin","/plugins enable my-plugin","/plugins disable my-plugin","/plugins refresh","/plugins stats"],handler:async($,W)=>{let Z=$[0]?.toLowerCase()||"",Y=m0();switch(Z){case"":return await TJ(Y),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return DJ(Y);case"info":return jJ(Y,$[1]);case"install":case"add":return MJ($[1]);case"uninstall":case"remove":case"rm":return vJ($[1]);case"update":case"upgrade":return xJ($[1]);case"enable":return AJ(Y,$[1]);case"disable":return NJ(Y,$[1]);case"refresh":return LJ(Y);case"stats":return kJ(Y);default:return k().addAssistantMessage(`未知子命令: ${Z}
1502
+ 使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${Z}`}}}};function DJ($){if($.getAll().length===0)return k().addAssistantMessage(`没有已加载的插件。
1503
+
1504
+ `+"使用 `--plugin-dir <path>` 参数加载插件,或将插件放置在:\n"+"- `~/.blade/plugins/` - 用户级插件\n"+"- `.blade/plugins/` - 项目级插件"),{success:!0,message:"No plugins loaded"};let Z=["## 已加载的插件",""],Y=$.getBySource();if(Y.cli.length>0){Z.push("### CLI 指定");for(let J of Y.cli){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}Z.push("")}if(Y.project.length>0){Z.push("### 项目级");for(let J of Y.project){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}Z.push("")}if(Y.user.length>0){Z.push("### 用户级");for(let J of Y.user){let X=J.status==="inactive"?" [PAUSED]":" [OK]";Z.push(`- **${J.manifest.name}** v${J.manifest.version}${X}`),Z.push(` ${J.manifest.description}`)}}return k().addAssistantMessage(Z.join(`
1505
+ `)),{success:!0,message:"Plugins listed"}}function jJ($,W){if(!W)return k().addAssistantMessage("请指定插件名称: `/plugins info <name>`"),{success:!1,error:"Plugin name required"};let Z=$.get(W);if(!Z)return k().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};let Y=[`## ${Z.manifest.name}`,"",`**版本**: ${Z.manifest.version}`,`**描述**: ${Z.manifest.description}`,`**状态**: ${Z.status==="active"?"[OK] 启用":"禁用"}`,`**来源**: ${bJ(Z.source)}`,`**路径**: \`${Z.basePath}\``,""];if(Z.manifest.author)Y.push(`**作者**: ${Z.manifest.author.name}`);if(Z.manifest.license)Y.push(`**许可证**: ${Z.manifest.license}`);if(Z.manifest.repository)Y.push(`**仓库**: ${Z.manifest.repository}`);if(Z.commands.length>0){Y.push(""),Y.push(`### 命令 (${Z.commands.length})`);for(let J of Z.commands){let X=J.config.argumentHint?` ${J.config.argumentHint}`:"",V=J.config.description?` - ${J.config.description}`:"";Y.push(`- \`/${J.namespacedName}${X}\`${V}`)}}if(Z.skills.length>0){Y.push(""),Y.push(`### 技能 (${Z.skills.length})`);for(let J of Z.skills)Y.push(`- \`${J.namespacedName}\` - ${J.metadata.description}`)}if(Z.agents.length>0){Y.push(""),Y.push(`### 代理 (${Z.agents.length})`);for(let J of Z.agents)Y.push(`- \`${J.namespacedName}\` - ${J.config.description}`)}if(Z.mcpServers){let J=Object.keys(Z.mcpServers).length;Y.push(""),Y.push(`### MCP 服务器 (${J})`);for(let X of Object.keys(Z.mcpServers))Y.push(`- \`${X}\``)}if(Z.hooks)Y.push(""),Y.push("### Hooks"),Y.push("插件已配置 hooks");return k().addAssistantMessage(Y.join(`
1506
+ `)),{success:!0,message:"Plugin info displayed"}}function AJ($,W){if(!W)return k().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(W))return k().addAssistantMessage(`[OK] 已启用插件: ${W}`),{success:!0,message:`Plugin ${W} enabled`};if(!$.get(W))return k().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};return k().addAssistantMessage(`插件 ${W} 已经是启用状态`),{success:!0,message:`Plugin ${W} already enabled`}}function NJ($,W){if(!W)return k().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(W))return k().addAssistantMessage(`已禁用插件: ${W}`),{success:!0,message:`Plugin ${W} disabled`};if(!$.get(W))return k().addAssistantMessage(`未找到插件: ${W}`),{success:!1,error:`Plugin not found: ${W}`};return k().addAssistantMessage(`插件 ${W} 已经是禁用状态`),{success:!0,message:`Plugin ${W} already disabled`}}async function TJ($){F2(),await $.refresh(),await E2()}async function LJ($){try{F2();let W=await $.refresh(),Z=await E2(),Y=["[OK] 已刷新插件列表","",`- 加载了 ${W.plugins.length} 个插件`,`- 集成了 ${Z.totalCommands} 个命令, ${Z.totalSkills} 个技能, ${Z.totalAgents} 个代理`];if(W.errors.length>0){Y.push(`- ${W.errors.length} 个加载错误`),Y.push(""),Y.push("### 错误");for(let J of W.errors)Y.push(`- \`${J.path}\`: ${J.error}`)}if(Z.errors.length>0){Y.push(""),Y.push("### 集成错误");for(let J of Z.errors)Y.push(`- ${J}`)}return k().addAssistantMessage(Y.join(`
1507
+ `)),{success:!0,message:"Plugins refreshed"}}catch(W){let Z=W instanceof Error?W.message:String(W);return k().addAssistantMessage(`刷新失败: ${Z}`),{success:!1,error:Z}}}function kJ($){let W=$.getStats(),Z=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${W.total} |`,`| 启用 | ${W.active} |`,`| 禁用 | ${W.inactive} |`,`| 命令 | ${W.commands} |`,`| 技能 | ${W.skills} |`,`| 代理 | ${W.agents} |`];return k().addAssistantMessage(Z.join(`
1508
+ `)),{success:!0,message:"Stats displayed"}}function bJ($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function MJ($){if(!$)return k().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
1509
+ `+"- GitHub 简写: `user/repo`\n"+"- 完整 URL: `https://github.com/user/repo`"),{success:!1,error:"Plugin URL required"};k().addAssistantMessage(`正在安装插件: ${$}...`);let Z=await z1().install($);if(Z.success){let Y=["[OK] 插件安装成功!","",`**名称**: ${Z.pluginName}`,`**路径**: \`${Z.pluginPath}\``];if(Z.manifest)Y.push(`**版本**: ${Z.manifest.version}`),Y.push(`**描述**: ${Z.manifest.description}`);return Y.push(""),Y.push("使用 `/plugins refresh` 加载新安装的插件。"),k().addAssistantMessage(Y.join(`
1510
+ `)),{success:!0,message:`Installed ${Z.pluginName}`}}return k().addAssistantMessage(`安装失败: ${Z.error}`),{success:!1,error:Z.error}}async function vJ($){if(!$)return k().addAssistantMessage("请指定插件名称: `/plugins uninstall <name>`"),{success:!1,error:"Plugin name required"};let Z=await z1().uninstall($);if(Z.success)return k().addAssistantMessage(`[OK] 已卸载插件: ${Z.pluginName}
1511
+
1512
+ `+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${Z.pluginName}`};return k().addAssistantMessage(`卸载失败: ${Z.error}`),{success:!1,error:Z.error}}async function xJ($){if(!$)return k().addAssistantMessage("请指定插件名称: `/plugins update <name>`"),{success:!1,error:"Plugin name required"};k().addAssistantMessage(`正在更新插件: ${$}...`);let Z=await z1().update($);if(Z.success){let Y=["[OK] 插件更新成功!","",`**名称**: ${Z.pluginName}`];if(Z.manifest)Y.push(`**版本**: ${Z.manifest.version}`);return Y.push(""),Y.push("使用 `/plugins refresh` 重新加载插件。"),k().addAssistantMessage(Y.join(`
1513
+ `)),{success:!0,message:`Updated ${Z.pluginName}`}}return k().addAssistantMessage(`更新失败: ${Z.error}`),{success:!1,error:Z.error}}var D6=_J;import{createReadStream as CJ}from"node:fs";import*as N2 from"node:fs/promises";import*as T2 from"node:path";import{createInterface as yJ}from"node:readline";async function j6($,W={}){let{maxResults:Z=20,caseSensitive:Y=!1,projectPath:J,storagePath:X}=W,V=X??$$(J??D()),H;try{H=(await N2.readdir(V)).filter((w)=>w.endsWith(".jsonl")&&!w.startsWith("agent_")).map((w)=>T2.join(V,w))}catch{return[]}let B=(await Promise.all(H.map(async(q)=>{try{let w=await N2.stat(q);return{path:q,mtime:w.mtimeMs}}catch{return null}}))).filter((q)=>q!==null).sort((q,w)=>w.mtime-q.mtime).map((q)=>q.path),U=[],Q=Y?$:$.toLowerCase();for(let q of B){if(U.length>=Z)break;let w=T2.basename(q,".jsonl"),E=await fJ(q,Q,Y,w);if(U.push(...E),U.length>=Z){U.length=Z;break}}return U}async function fJ($,W,Z,Y){let J=[];try{let X=CJ($,{encoding:"utf-8"}),V=yJ({input:X,crlfDelay:1/0}),H=0;for await(let K of V){if(H++,!K.trim())continue;try{let B=JSON.parse(K);if(B.type!=="message")continue;if(!B.message?.content)continue;let U=B.message.role;if(U!=="user"&&U!=="assistant")continue;let Q=typeof B.message.content==="string"?B.message.content:Array.isArray(B.message.content)?B.message.content.filter((z)=>z.type==="text").map((z)=>z.text).join(" "):"";if(!Q)continue;let q=Z?Q:Q.toLowerCase();if(!q.includes(W))continue;let w=q.indexOf(W),E=Math.max(0,w-80),G=Math.min(Q.length,w+W.length+80),F=(E>0?"...":"")+Q.slice(E,G).replace(/\n/g," ")+(G<Q.length?"...":"");J.push({sessionId:Y,role:U,content:F,timestamp:B.timestamp,lineNumber:H})}catch{}}}catch{}return J}function A6($){if($.length===0)return"没有找到匹配的历史记录";let W=[`**找到 ${$.length} 条匹配:**
1514
1514
  `];for(let Z of $){let Y=Z.timestamp?new Date(Z.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",J=Z.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";W.push(`${J} \`${Z.sessionId.slice(0,8)}\` (${Y})`),W.push(` ${Z.content}`),W.push("")}return W.join(`
1515
- `)}var fJ={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($,W){let Z=C(W);if($.length===0)return Z.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");Z.sendMessage(`正在搜索: "${Y}" ...`);try{let J=await j6(Y,{maxResults:15,projectPath:W.cwd}),X=A6(J);return Z.sendMessage(X),{success:!0,message:`found ${J.length} results`,data:{matches:J.length}}}catch(J){let X=J instanceof Error?J.message:"未知错误";return Z.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},N6=fJ;var SJ={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,W)=>{try{return await Q0().refresh(),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(Z){let Y=`获取 Skills 失败: ${Z instanceof Error?Z.message:"未知错误"}`;return L().addAssistantMessage(Y),{success:!1,error:Y}}}},T6=SJ;function L2($){if($<1000)return`${$}ms`;let W=Math.floor($/1000);if(W<60)return`${W}s`;let Z=Math.floor(W/60);if(Z<60)return`${Z}m ${W%60}s`;return`${Math.floor(Z/60)}h ${Z%60}m`}function L6($){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 k6($,W){if($.length<=W)return $;return $.slice(0,W-3)+"..."}async function IJ($,W){let Z=C(W),Y=$[0],J=$0.getInstance(),X=e.getInstance(),V=W.sessionId??"";if(Y==="clean"){let q=X.cleanupExpiredSessionsForParent(V,0);return Z.sendMessage(`已清理 ${q} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${q} agent sessions`}}let H=[`**后台任务列表**
1516
- `],B=J.listForSession(V);if(B.length>0){H.push(`### Shells
1517
- `),H.push("| ID | 状态 | 命令 | PID | 运行时间 |"),H.push("|:---|:-----|:-----|:----|:---------|");for(let q of B){let w=q.endTime?L2(q.endTime-q.startTime):L2(Date.now()-q.startTime),E=L6(q.status);H.push(`| \`${q.id.slice(0,12)}...\` | ${E} ${q.status} | \`${k6(q.command,30)}\` | ${q.pid||"-"} | ${w} |`)}H.push("")}let K=X.listForSession(V);if(K.length>0){H.push(`### Agents
1518
- `),H.push("| ID | 状态 | 类型 | 描述 | 运行时间 |"),H.push("|:---|:-----|:-----|:-----|:---------|");for(let q of K){let w=q.completedAt?L2(q.completedAt-q.createdAt):L2(Date.now()-q.createdAt),E=L6(q.status);H.push(`| \`${q.id.slice(0,12)}...\` | ${E} ${q.status} | ${q.subagentType} | ${k6(q.description,25)} | ${w} |`)}H.push("")}let Q=B.filter((q)=>q.status==="running").length,U=K.filter((q)=>q.status==="running").length;if(B.length===0&&K.length===0)H.push(`*暂无后台任务*
1519
- `);else H.push(`**统计**: ${B.length} shells (${Q} 运行中), ${K.length} agents (${U} 运行中)`);return H.push(`
1515
+ `)}var PJ={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($,W){let Z=C(W);if($.length===0)return Z.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");Z.sendMessage(`正在搜索: "${Y}" ...`);try{let J=await j6(Y,{maxResults:15,projectPath:W.cwd}),X=A6(J);return Z.sendMessage(X),{success:!0,message:`found ${J.length} results`,data:{matches:J.length}}}catch(J){let X=J instanceof Error?J.message:"未知错误";return Z.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},N6=PJ;var SJ={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,W)=>{try{return await U0().refresh(),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(Z){let Y=`获取 Skills 失败: ${Z instanceof Error?Z.message:"未知错误"}`;return k().addAssistantMessage(Y),{success:!1,error:Y}}}},T6=SJ;function L2($){if($<1000)return`${$}ms`;let W=Math.floor($/1000);if(W<60)return`${W}s`;let Z=Math.floor(W/60);if(Z<60)return`${Z}m ${W%60}s`;return`${Math.floor(Z/60)}h ${Z%60}m`}function L6($){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 k6($,W){if($.length<=W)return $;return $.slice(0,W-3)+"..."}async function IJ($,W){let Z=C(W),Y=$[0],J=$0.getInstance(),X=e.getInstance(),V=W.sessionId??"";if(Y==="clean"){let q=X.cleanupExpiredSessionsForParent(V,0);return Z.sendMessage(`已清理 ${q} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${q} agent sessions`}}let H=[`**后台任务列表**
1516
+ `],K=J.listForSession(V);if(K.length>0){H.push(`### Shells
1517
+ `),H.push("| ID | 状态 | 命令 | PID | 运行时间 |"),H.push("|:---|:-----|:-----|:----|:---------|");for(let q of K){let w=q.endTime?L2(q.endTime-q.startTime):L2(Date.now()-q.startTime),E=L6(q.status);H.push(`| \`${q.id.slice(0,12)}...\` | ${E} ${q.status} | \`${k6(q.command,30)}\` | ${q.pid||"-"} | ${w} |`)}H.push("")}let B=X.listForSession(V);if(B.length>0){H.push(`### Agents
1518
+ `),H.push("| ID | 状态 | 类型 | 描述 | 运行时间 |"),H.push("|:---|:-----|:-----|:-----|:---------|");for(let q of B){let w=q.completedAt?L2(q.completedAt-q.createdAt):L2(Date.now()-q.createdAt),E=L6(q.status);H.push(`| \`${q.id.slice(0,12)}...\` | ${E} ${q.status} | ${q.subagentType} | ${k6(q.description,25)} | ${w} |`)}H.push("")}let U=K.filter((q)=>q.status==="running").length,Q=B.filter((q)=>q.status==="running").length;if(K.length===0&&B.length===0)H.push(`*暂无后台任务*
1519
+ `);else H.push(`**统计**: ${K.length} shells (${U} 运行中), ${B.length} agents (${Q} 运行中)`);return H.push(`
1520
1520
  ---`),H.push("**命令**:"),H.push("- `/tasks` - 列出所有后台任务"),H.push("- `/tasks clean` - 清理已完成的 Agent 会话"),Z.sendMessage(H.join(`
1521
- `)),{success:!0,message:`Listed ${B.length} shells and ${K.length} agents`}}var hJ={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
1521
+ `)),{success:!0,message:`Listed ${K.length} shells and ${B.length} agents`}}var hJ={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
1522
1522
 
1523
1523
  **功能**:
1524
1524
  - 列出所有后台 shell 进程
@@ -1527,8 +1527,8 @@ ${Z}
1527
1527
 
1528
1528
  **使用示例**:
1529
1529
  - \`/tasks\` - 显示所有后台任务
1530
- - \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:IJ},b6=hJ;async function uJ($,W){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var pJ={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:uJ},M6=pJ;var N1={...J6,init:O6,theme:M6,permissions:R2,model:D6,git:U6,ide:z6,search:N6,skills:T6,hooks:q6,tasks:b6,plugins:_6};function UR($){return $.trim().startsWith("/")}function gJ($){let W=$.trim();if(!W.startsWith("/"))throw Error("不是有效的 slash command");let Z=W.slice(1).split(/\s+/),Y=Z[0]||"",J=Z.slice(1);return{command:Y,args:J}}function mJ($){if(N1[$])return N1[$];for(let W of Object.values(N1))if(W.aliases?.includes($))return W;return}function v6($){let W=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
1530
+ - \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:IJ},b6=hJ;async function uJ($,W){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var pJ={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:uJ},M6=pJ;var N1={...J6,init:O6,theme:M6,permissions:R2,model:_6,git:Q6,ide:z6,search:N6,skills:T6,hooks:q6,tasks:b6,plugins:D6};function QR($){return $.trim().startsWith("/")}function gJ($){let W=$.trim();if(!W.startsWith("/"))throw Error("不是有效的 slash command");let Z=W.slice(1).split(/\s+/),Y=Z[0]||"",J=Z.slice(1);return{command:Y,args:J}}function mJ($){if(N1[$])return N1[$];for(let W of Object.values(N1))if(W.aliases?.includes($))return W;return}function v6($){let W=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
1531
1531
 
1532
- **When to use:** ${$.whenToUse}`:""}`,usage:W,category:"skill",examples:[W],handler:async(Z,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:Z.join(" ")}}}}}function cJ($){return Q0().getUserInvocableSkills().find((Y)=>Y.name===$)}async function lJ(){await u$()}async function qR($){return await r.getInstance().initialize($)}async function wR($,W){try{let{command:Z,args:Y}=gJ($),J=mJ(Z);if(J)return await J.handler(Y,W);let X=r.getInstance();if(X.hasCommand(Z)){let K=X.getCommand(Z);if(K){let Q=W.workspaceRoot||D(),U=await X.executeCommand(Z,{args:Y,workspaceRoot:Q,signal:W.signal});if(U)return{success:!0,message:`执行自定义命令: /${Z}`,data:{action:"invoke_custom_command",commandName:Z,processedContent:U,config:K.config}}}}let H=m0().findCommand(Z);if(H){let K=W.workspaceRoot||D(),Q=await X.executePluginCommand(H.namespacedName,{args:Y,workspaceRoot:K,signal:W.signal});if(Q)return{success:!0,message:`执行插件命令: /${H.namespacedName}`,data:{action:"invoke_plugin_command",commandName:H.namespacedName,pluginName:H.pluginName,processedContent:Q,config:H.config}}}await lJ();let B=cJ(Z);if(B)return await v6(B).handler(Y,W);return{success:!1,error:`未知命令: /${Z}
1533
- 使用 /help 查看可用命令`}}catch(Z){return{success:!1,error:`命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}function GR(){let $=Object.values(N1),Z=r.getInstance().getAllCommands().map((H)=>({name:H.name,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.name} ${H.config.argumentHint}`:`/${H.name}`,category:"custom",handler:async()=>({success:!0})})),J=m0().getAllCommands().map((H)=>({name:H.namespacedName,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.namespacedName} ${H.config.argumentHint}`:`/${H.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),V=Q0().getUserInvocableSkills().map(v6);return[...$,...Z,...J,...V]}function ER($){let W=($.startsWith("/")?$.slice(1):$).trim(),Z=Object.values(N1).map((w)=>({name:w.name,description:w.description,aliases:w.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),Y=r.getInstance(),J=Y.getAllCommands().map((w)=>({name:w.name,description:w.config.description||w.content.slice(0,50),aliases:[],label:Y.getCommandLabel(w),argumentHint:w.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),V=m0().getAllCommands().map((w)=>({name:w.namespacedName,description:w.config.description||w.content.slice(0,50),aliases:[w.originalName],label:`(plugin: ${w.pluginName})`,argumentHint:w.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),B=Q0().getUserInvocableSkills().map((w)=>({name:w.name,description:w.description,aliases:[],label:"(skill)",argumentHint:w.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),K=[...Z,...J,...V,...B];if(!W)return K.map((w)=>({command:`/${w.name}`,description:w.label?`${w.description} ${w.label}`:w.description,argumentHint:w.argumentHint,matchScore:50}));return new dJ(K,{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(W).map((w)=>{let E=w.score??1,G=Math.round((1-E)*100),F=w.item;return{command:`/${F.name}`,description:F.label?`${F.description} ${F.label}`:F.description,argumentHint:F.argumentHint,matchScore:G}}).filter((w)=>(w.matchScore||0)>=40)}
1534
- export{dX as z,P$ as A,b as B,G$ as C,f9 as D,$0 as E,c1 as F,f as G,e1 as H,T$ as I,dW as J,n5 as K,a5 as L,t5 as M,B0 as N,m0 as O,E2 as P,R1 as Q,XZ as R,aF as S,UR as T,qR as U,wR as V,GR as W,ER as X};
1532
+ **When to use:** ${$.whenToUse}`:""}`,usage:W,category:"skill",examples:[W],handler:async(Z,Y)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:Z.join(" ")}}}}}function cJ($){return U0().getUserInvocableSkills().find((Y)=>Y.name===$)}async function lJ(){await u$()}async function qR($){return await r.getInstance().initialize($)}async function wR($,W){try{let{command:Z,args:Y}=gJ($),J=mJ(Z);if(J)return await J.handler(Y,W);let X=r.getInstance();if(X.hasCommand(Z)){let B=X.getCommand(Z);if(B){let U=W.workspaceRoot||D(),Q=await X.executeCommand(Z,{args:Y,workspaceRoot:U,signal:W.signal});if(Q)return{success:!0,message:`执行自定义命令: /${Z}`,data:{action:"invoke_custom_command",commandName:Z,processedContent:Q,config:B.config}}}}let H=m0().findCommand(Z);if(H){let B=W.workspaceRoot||D(),U=await X.executePluginCommand(H.namespacedName,{args:Y,workspaceRoot:B,signal:W.signal});if(U)return{success:!0,message:`执行插件命令: /${H.namespacedName}`,data:{action:"invoke_plugin_command",commandName:H.namespacedName,pluginName:H.pluginName,processedContent:U,config:H.config}}}await lJ();let K=cJ(Z);if(K)return await v6(K).handler(Y,W);return{success:!1,error:`未知命令: /${Z}
1533
+ 使用 /help 查看可用命令`}}catch(Z){return{success:!1,error:`命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}function GR(){let $=Object.values(N1),Z=r.getInstance().getAllCommands().map((H)=>({name:H.name,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.name} ${H.config.argumentHint}`:`/${H.name}`,category:"custom",handler:async()=>({success:!0})})),J=m0().getAllCommands().map((H)=>({name:H.namespacedName,description:H.config.description||H.content.slice(0,50),usage:H.config.argumentHint?`/${H.namespacedName} ${H.config.argumentHint}`:`/${H.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),V=U0().getUserInvocableSkills().map(v6);return[...$,...Z,...J,...V]}function ER($){let W=($.startsWith("/")?$.slice(1):$).trim(),Z=Object.values(N1).map((w)=>({name:w.name,description:w.description,aliases:w.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),Y=r.getInstance(),J=Y.getAllCommands().map((w)=>({name:w.name,description:w.config.description||w.content.slice(0,50),aliases:[],label:Y.getCommandLabel(w),argumentHint:w.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),V=m0().getAllCommands().map((w)=>({name:w.namespacedName,description:w.config.description||w.content.slice(0,50),aliases:[w.originalName],label:`(plugin: ${w.pluginName})`,argumentHint:w.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),K=U0().getUserInvocableSkills().map((w)=>({name:w.name,description:w.description,aliases:[],label:"(skill)",argumentHint:w.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),B=[...Z,...J,...V,...K];if(!W)return B.map((w)=>({command:`/${w.name}`,description:w.label?`${w.description} ${w.label}`:w.description,argumentHint:w.argumentHint,matchScore:50}));return new dJ(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(W).map((w)=>{let E=w.score??1,G=Math.round((1-E)*100),F=w.item;return{command:`/${F.name}`,description:F.label?`${F.description} ${F.label}`:F.description,argumentHint:F.argumentHint,matchScore:G}}).filter((w)=>(w.matchScore||0)>=40)}
1534
+ export{dX as z,f$ as A,M as B,G$ as C,P9 as D,$0 as E,c1 as F,P as G,e1 as H,T$ as I,dW as J,n5 as K,a5 as L,t5 as M,B0 as N,m0 as O,E2 as P,R1 as Q,XZ as R,aF as S,QR as T,qR as U,wR as V,GR as W,ER as X};