blade-code 0.5.18 → 0.5.19

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{X as D,Y as F$}from"./chunk-w157j0bx.js";import{Z as K4}from"./chunk-mxrre2n3.js";import{ba as M1}from"./chunk-fym8fmvq.js";import{ga as m}from"./chunk-68ctb04g.js";import{Aa as C1,Ba as l$,Ca as j$,Da as c0,Ea as L$,Fa as I1,Ga as x$,ra as l4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-x9zj0r7s.js";import{Ia as v1}from"./chunk-mz6n4w13.js";import{Ma as r9,Na as Q$,Oa as D0,Pa as y$,Sa as N$,db as n1,eb as $2,hb as Q9}from"./chunk-0a5rp0hh.js";import{ib as G9,jb as F9,kb as K8,lb as Y9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as X$}from"./chunk-yk91w5p2.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as s$}from"./chunk-j2ag7hh6.js";import{spawn as m2}from"child_process";import{randomUUID as c2}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
2
- [error] ${Y.message}`}),this.processes.set(Z,X),X}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let J={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};return Z.pendingStdout="",Z.pendingStderr="",J}getProcess($){return this.processes.get($)}kill($){let Z=this.processes.get($);if(!Z)return;if(Z.status!=="running"||!Z.process)return{success:!1,alreadyExited:!0,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};if(!Z.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};return Z.status="killed",Z.endTime=Date.now(),Z.process=void 0,{success:!0,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal}}killAll(){for(let[$,Z]of this.processes)if(Z.status==="running"&&Z.process)try{Z.process.kill("SIGTERM"),Z.status="killed",Z.endTime=Date.now(),Z.process=void 0}catch{}this.processes.clear()}}import Y5 from"node:fs";import X1 from"node:os";import k$ from"node:path";import l2 from"yaml";var u8={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{X as D,Y as O$}from"./chunk-e2h6cdnx.js";import{Z as K4}from"./chunk-mxrre2n3.js";import{ba as M1}from"./chunk-c7rvs5ev.js";import{ga as m}from"./chunk-68ctb04g.js";import{Aa as C1,Ba as i$,Ca as N$,Da as c0,Ea as E$,Fa as I1,Ga as f$,ra as l4,sa as s,ua as l0,va as i,wa as A,za as t}from"./chunk-x9zj0r7s.js";import{Ia as v1}from"./chunk-mz6n4w13.js";import{Ma as r9,Na as Q$,Oa as L0,Pa as x$,Sa as D$,db as n1,eb as $2,hb as Q9}from"./chunk-0a5rp0hh.js";import{ib as G9,jb as F9,kb as K8,lb as Y9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as X$}from"./chunk-yk91w5p2.js";import{rb as S1}from"./chunk-37rethcy.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as S}from"./chunk-set7v1rf.js";import{Db as o$}from"./chunk-j2ag7hh6.js";import{spawn as m2}from"child_process";import{randomUUID as c2}from"crypto";class n{static instance=null;processes=new Map;static getInstance(){if(!n.instance)n.instance=new n;return n.instance}startBackgroundProcess($){let Z=`bash_${c2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=m2("bash",["-c",$.command],{cwd:$.cwd||N(),env:J,stdio:["ignore","pipe","pipe"]}),X={id:Z,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return W.stdout?.setEncoding("utf8"),W.stderr?.setEncoding("utf8"),W.stdout?.on("data",(Y)=>{X.pendingStdout+=Y.toString()}),W.stderr?.on("data",(Y)=>{X.pendingStderr+=Y.toString()}),W.on("close",(Y,V)=>{X.status=X.status==="killed"?"killed":"exited",X.exitCode=Y,X.signal=V,X.endTime=Date.now(),X.process=void 0}),W.on("error",(Y)=>{X.status="error",X.errorMessage=Y.message,X.endTime=Date.now(),X.process=void 0,X.pendingStderr+=`
2
+ [error] ${Y.message}`}),this.processes.set(Z,X),X}consumeOutput($){let Z=this.processes.get($);if(!Z)return;let J={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};return Z.pendingStdout="",Z.pendingStderr="",J}getProcess($){return this.processes.get($)}kill($){let Z=this.processes.get($);if(!Z)return;if(Z.status!=="running"||!Z.process)return{success:!1,alreadyExited:!0,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};if(!Z.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal};return Z.status="killed",Z.endTime=Date.now(),Z.process=void 0,{success:!0,alreadyExited:!1,status:Z.status,pid:Z.pid,exitCode:Z.exitCode,signal:Z.signal}}killAll(){for(let[$,Z]of this.processes)if(Z.status==="running"&&Z.process)try{Z.process.kill("SIGTERM"),Z.status="killed",Z.endTime=Date.now(),Z.process=void 0}catch{}this.processes.clear()}}import Y5 from"node:fs";import X1 from"node:os";import b$ from"node:path";import l2 from"yaml";var u8={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
 
@@ -159,15 +159,15 @@ You are a software architect specializing in implementation planning.
159
159
 
160
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"]},u8];function g8($){switch($){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}var V5=M("Agent");class m8{subagents=new Map;register($){if(this.subagents.has($.name))throw Error(`Subagent '${$.name}' already registered`);this.subagents.set($.name,$)}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((J)=>{let W=!J.tools||J.tools.length===0?"All tools":J.tools.join(", ");return`- ${J.name}: ${J.description} (Tools: ${W})`}).join(`
162
- `)}`}loadFromDirectory($,Z){if(!Y5.existsSync($))return;let J=Y5.readdirSync($);for(let W of J){if(!W.endsWith(".md"))continue;let X=k$.join($,W);try{let Y=this.parseConfigFile(X,Z);this.subagents.set(Y.name,Y)}catch(Y){V5.warn(`Failed to load subagent config from ${X}:`,Y)}}}parseConfigFile($,Z){let W=Y5.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!W)throw Error(`No YAML frontmatter found in ${$}`);let[,X,Y]=W,V=l2.parse(X);if(!V.name||!V.description)throw Error(`Missing required fields (name, description) in ${$}`);let B=Y.trim(),K=this.parseStringOrArray(V.tools),Q=this.parseStringOrArray(V.skills),U=g8(V.permissionMode);return{name:V.name,description:V.description,systemPrompt:B,tools:K,color:V.color,configPath:$,model:V.model||"inherit",permissionMode:U,skills:Q,source:Z}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>Z.trim()).filter(Boolean);return $.split(",").map((Z)=>Z.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=k$.join(X1.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let Z=k$.join(N(),".claude","agents");this.loadFromDirectory(Z,"claude-code-project");let J=k$.join(X1.homedir(),".blade","agents");this.loadFromDirectory(J,"blade-user");let W=k$.join(N(),".blade","agents");this.loadFromDirectory(W,"blade-project");let X=this.getAllNames().length;return V5.debug(`Loaded ${X} subagents from standard locations`),X}loadBuiltinAgents(){for(let $ of X5)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});V5.debug(`Loaded ${X5.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],plugin:[]};for(let Z of this.subagents.values()){let J=Z.source||"builtin",W=J.startsWith("plugin:")?"plugin":J;$[W].push(Z)}return $}clearPluginAgents(){let $=[];for(let[Z,J]of this.subagents.entries())if(J.source?.startsWith("plugin:"))$.push(Z);for(let Z of $)this.subagents.delete(Z)}static getClaudeCodeAgentsDir($){if($==="user")return k$.join(X1.homedir(),".claude","agents");return k$.join(N(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return k$.join(X1.homedir(),".blade","agents");return k$.join(N(),".blade","agents")}}var P=new m8;import*as d9 from"os";import*as u9 from"path";import i2 from"fs/promises";import a2 from"path";var c8=M("General");async function Y1($){for(let Z of $)try{let J;if(Z.trim().startsWith("{")){let Y=JSON.parse(Z);if(Y.name&&Y.type){let{name:V,...B}=Y;J={[V]:B}}else J=Y}else{let Y=a2.resolve(l8(),Z),V=await i2.readFile(Y,"utf-8"),B=JSON.parse(V);J=B.mcpServers||B}let X={...L$(),...J};i().config.actions.updateConfig({mcpServers:X}),c8.debug(`[OK] Loaded MCP config from CLI: ${Object.keys(J).join(", ")}`)}catch(J){c8.warn(`[WARN] Failed to load MCP config "${Z}":`,J)}}import{promises as B4}from"fs";import J7 from"path";import*as u from"node:fs/promises";import*as e$ from"node:path";import{execSync as n2}from"node:child_process";import*as B5 from"node:os";import*as o$ from"node:path";function r2($){return o$.resolve($).replace(/[/\\]/g,"-").replace(/:/g,"_")}function i8($){let Z=$.replace(/_/g,":");if(Z.startsWith("-"))Z="/"+Z.slice(1);return Z.replace(/-/g,"/")}function t$($){let Z=B5.homedir(),J=r2($);return o$.join(Z,".blade","projects",J)}function W$($,Z){return o$.join(t$($),`${Z}.jsonl`)}function a8($){try{return n2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function b$(){return o$.join(B5.homedir(),".blade")}async function n8(){let{readdir:$}=await import("node:fs/promises");try{let Z=o$.join(b$(),"projects");return(await $(Z,{withFileTypes:!0})).filter((W)=>W.isDirectory()).map((W)=>W.name)}catch{return[]}}var r8={enabled:!0,maxIndexLines:200};var s2="memory",s8="MEMORY.md";class T${memoryDir;config;initialized=!1;constructor($,Z,J){if(J)this.memoryDir=J;else{let W=t$($);this.memoryDir=e$.join(W,s2)}this.config={...r8,...Z}}async initialize(){if(this.initialized)return;await u.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=e$.join(this.memoryDir,s8);try{let Z=await u.readFile($,"utf-8");if(!Z.trim())return null;let J=Z.split(`
162
+ `)}`}loadFromDirectory($,Z){if(!Y5.existsSync($))return;let J=Y5.readdirSync($);for(let W of J){if(!W.endsWith(".md"))continue;let X=b$.join($,W);try{let Y=this.parseConfigFile(X,Z);this.subagents.set(Y.name,Y)}catch(Y){V5.warn(`Failed to load subagent config from ${X}:`,Y)}}}parseConfigFile($,Z){let W=Y5.readFileSync($,"utf-8").match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!W)throw Error(`No YAML frontmatter found in ${$}`);let[,X,Y]=W,V=l2.parse(X);if(!V.name||!V.description)throw Error(`Missing required fields (name, description) in ${$}`);let B=Y.trim(),K=this.parseStringOrArray(V.tools),Q=this.parseStringOrArray(V.skills),U=g8(V.permissionMode);return{name:V.name,description:V.description,systemPrompt:B,tools:K,color:V.color,configPath:$,model:V.model||"inherit",permissionMode:U,skills:Q,source:Z}}parseStringOrArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>Z.trim()).filter(Boolean);return $.split(",").map((Z)=>Z.trim()).filter(Boolean)}loadFromStandardLocations(){this.loadBuiltinAgents();let $=b$.join(X1.homedir(),".claude","agents");this.loadFromDirectory($,"claude-code-user");let Z=b$.join(N(),".claude","agents");this.loadFromDirectory(Z,"claude-code-project");let J=b$.join(X1.homedir(),".blade","agents");this.loadFromDirectory(J,"blade-user");let W=b$.join(N(),".blade","agents");this.loadFromDirectory(W,"blade-project");let X=this.getAllNames().length;return V5.debug(`Loaded ${X} subagents from standard locations`),X}loadBuiltinAgents(){for(let $ of X5)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});V5.debug(`Loaded ${X5.length} builtin subagents`)}clear(){this.subagents.clear()}getSubagentsBySource(){let $={builtin:[],"claude-code-user":[],"claude-code-project":[],"blade-user":[],"blade-project":[],plugin:[]};for(let Z of this.subagents.values()){let J=Z.source||"builtin",W=J.startsWith("plugin:")?"plugin":J;$[W].push(Z)}return $}clearPluginAgents(){let $=[];for(let[Z,J]of this.subagents.entries())if(J.source?.startsWith("plugin:"))$.push(Z);for(let Z of $)this.subagents.delete(Z)}static getClaudeCodeAgentsDir($){if($==="user")return b$.join(X1.homedir(),".claude","agents");return b$.join(N(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return b$.join(X1.homedir(),".blade","agents");return b$.join(N(),".blade","agents")}}var P=new m8;import*as d9 from"os";import*as u9 from"path";import i2 from"fs/promises";import a2 from"path";var c8=M("General");async function Y1($){for(let Z of $)try{let J;if(Z.trim().startsWith("{")){let Y=JSON.parse(Z);if(Y.name&&Y.type){let{name:V,...B}=Y;J={[V]:B}}else J=Y}else{let Y=a2.resolve(l8(),Z),V=await i2.readFile(Y,"utf-8"),B=JSON.parse(V);J=B.mcpServers||B}let X={...E$(),...J};i().config.actions.updateConfig({mcpServers:X}),c8.debug(`[OK] Loaded MCP config from CLI: ${Object.keys(J).join(", ")}`)}catch(J){c8.warn(`[WARN] Failed to load MCP config "${Z}":`,J)}}import{promises as B4}from"fs";import J7 from"path";import*as u from"node:fs/promises";import*as $0 from"node:path";import{execSync as n2}from"node:child_process";import*as B5 from"node:os";import*as t$ from"node:path";function r2($){return t$.resolve($).replace(/[/\\]/g,"-").replace(/:/g,"_")}function i8($){let Z=$.replace(/_/g,":");if(Z.startsWith("-"))Z="/"+Z.slice(1);return Z.replace(/-/g,"/")}function e$($){let Z=B5.homedir(),J=r2($);return t$.join(Z,".blade","projects",J)}function W$($,Z){return t$.join(e$($),`${Z}.jsonl`)}function a8($){try{return n2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function T$(){return t$.join(B5.homedir(),".blade")}async function n8(){let{readdir:$}=await import("node:fs/promises");try{let Z=t$.join(T$(),"projects");return(await $(Z,{withFileTypes:!0})).filter((W)=>W.isDirectory()).map((W)=>W.name)}catch{return[]}}var r8={enabled:!0,maxIndexLines:200};var s2="memory",s8="MEMORY.md";class M${memoryDir;config;initialized=!1;constructor($,Z,J){if(J)this.memoryDir=J;else{let W=e$($);this.memoryDir=$0.join(W,s2)}this.config={...r8,...Z}}async initialize(){if(this.initialized)return;await u.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=$0.join(this.memoryDir,s8);try{let Z=await u.readFile($,"utf-8");if(!Z.trim())return null;let J=Z.split(`
163
163
  `),X=J.slice(0,this.config.maxIndexLines).join(`
164
164
  `).trim();if(J.length>this.config.maxIndexLines)return X+`
165
165
 
166
166
  <!-- ${J.length-this.config.maxIndexLines} more lines in MEMORY.md, use MemoryRead to access -->`;return X||null}catch(Z){if(Z instanceof Error&&"code"in Z&&Z.code==="ENOENT")return null;throw Z}}async readTopic($){await this.initialize();let Z=this.resolveTopicPath($);try{return await u.readFile(Z,"utf-8")||null}catch(J){if(J instanceof Error&&"code"in J&&J.code==="ENOENT")return null;throw J}}async writeTopic($,Z,J="append"){await this.initialize();let W=this.resolveTopicPath($);if(J==="append"){let X="";try{X=await u.readFile(W,"utf-8")}catch{}let Y=X&&!X.endsWith(`
167
167
  `)?`
168
- `:"";await u.writeFile(W,X+Y+Z,"utf-8")}else await u.writeFile(W,Z,"utf-8")}async updateIndex($,Z="overwrite"){await this.initialize();let J=e$.join(this.memoryDir,s8);if(Z==="append"){let W="";try{W=await u.readFile(J,"utf-8")}catch{}let X=W&&!W.endsWith(`
168
+ `:"";await u.writeFile(W,X+Y+Z,"utf-8")}else await u.writeFile(W,Z,"utf-8")}async updateIndex($,Z="overwrite"){await this.initialize();let J=$0.join(this.memoryDir,s8);if(Z==="append"){let W="";try{W=await u.readFile(J,"utf-8")}catch{}let X=W&&!W.endsWith(`
169
169
  `)?`
170
- `:"";await u.writeFile(J,W+X+$,"utf-8")}else await u.writeFile(J,$,"utf-8")}async listTopics(){await this.initialize();try{let $=await u.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isFile()||!J.name.endsWith(".md"))continue;let W=e$.join(this.memoryDir,J.name),X=await u.stat(W);Z.push({name:J.name.replace(/\.md$/,""),size:X.size,lastModified:X.mtime})}return Z.sort((J,W)=>W.lastModified.getTime()-J.lastModified.getTime())}catch{return[]}}async deleteTopic($){let Z=this.resolveTopicPath($);try{return await u.unlink(Z),!0}catch{return!1}}async clearAll(){let $=await this.listTopics(),Z=0;for(let J of $){let W=e$.join(this.memoryDir,`${J.name}.md`);try{await u.unlink(W),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath($){let Z=$.replace(/[/\\:*?"<>|]/g,"-"),J=Z.endsWith(".md")?Z:`${Z}.md`,W=e$.join(this.memoryDir,J);if(!W.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${$}`);return W}}function o8(){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.
170
+ `:"";await u.writeFile(J,W+X+$,"utf-8")}else await u.writeFile(J,$,"utf-8")}async listTopics(){await this.initialize();try{let $=await u.readdir(this.memoryDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isFile()||!J.name.endsWith(".md"))continue;let W=$0.join(this.memoryDir,J.name),X=await u.stat(W);Z.push({name:J.name.replace(/\.md$/,""),size:X.size,lastModified:X.mtime})}return Z.sort((J,W)=>W.lastModified.getTime()-J.lastModified.getTime())}catch{return[]}}async deleteTopic($){let Z=this.resolveTopicPath($);try{return await u.unlink(Z),!0}catch{return!1}}async clearAll(){let $=await this.listTopics(),Z=0;for(let J of $){let W=$0.join(this.memoryDir,`${J.name}.md`);try{await u.unlink(W),Z++}catch{}}return Z}getMemoryDir(){return this.memoryDir}resolveTopicPath($){let Z=$.replace(/[/\\:*?"<>|]/g,"-"),J=Z.endsWith(".md")?Z:`${Z}.md`,W=$0.join(this.memoryDir,J);if(!W.startsWith(this.memoryDir))throw Error(`Invalid topic name: ${$}`);return W}}function o8(){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.
171
171
 
172
172
  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.
173
173
  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 t8(){return`# System
@@ -304,7 +304,7 @@ Your plan should include:
304
304
  3. **Steps** - Detailed implementation steps with file paths
305
305
  4. **Testing** - How to verify changes
306
306
  5. **Risks** - Potential issues and mitigations
307
- `;function C0($){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>
307
+ `;function I0($){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
309
  `+$}var $7=`
310
310
  # Spec-Driven Development Mode
@@ -487,7 +487,7 @@ You are in Spec Mode (${s[$]} phase).
487
487
  - Use Spec tools: UpdateSpec, GetSpecContext, TransitionSpecPhase, ValidateSpec
488
488
  - Follow the workflow: Requirements -> Design -> Tasks -> Implementation
489
489
  - Update spec files as you work
490
- </spec-mode-reminder>`}var W7=/<available_skills>\s*<\/available_skills>/;async function $0($={}){let{projectPath:Z,replaceDefault:J,append:W,mode:X,includeEnvironment:Y=!0,environmentOptions:V,currentSpec:B,steeringContext:K,language:Q}=$,U=[],q=[],H=X==="plan",G=X==="spec",O,F;if(G)O=V1(B??null,K??null),F="spec_mode_prompt";else if(H)O=V4,F="plan_mode_prompt";else O=J??Y4,F=J?"replace_default":"default";if(U.push(O),q.push({name:F,loaded:!0,length:O.length}),Z){let w=await B7(Z);if(w)U.push(w),q.push({name:"blade_md",loaded:!0,length:w.length});else q.push({name:"blade_md",loaded:!1})}if(Z&&process.env.BLADE_AUTO_MEMORY!=="0")try{let L=await new T$(Z).loadIndex();if(L)U.push(`<auto-memory>
490
+ </spec-mode-reminder>`}var W7=/<available_skills>\s*<\/available_skills>/;async function Z0($={}){let{projectPath:Z,replaceDefault:J,append:W,mode:X,includeEnvironment:Y=!0,environmentOptions:V,currentSpec:B,steeringContext:K,language:Q}=$,U=[],q=[],H=X==="plan",G=X==="spec",O,F;if(G)O=V1(B??null,K??null),F="spec_mode_prompt";else if(H)O=V4,F="plan_mode_prompt";else O=J??Y4,F=J?"replace_default":"default";if(U.push(O),q.push({name:F,loaded:!0,length:O.length}),Z){let w=await B7(Z);if(w)U.push(w),q.push({name:"blade_md",loaded:!0,length:w.length});else q.push({name:"blade_md",loaded:!1})}if(Z&&process.env.BLADE_AUTO_MEMORY!=="0")try{let L=await new M$(Z).loadIndex();if(L)U.push(`<auto-memory>
491
491
  ${L}
492
492
  </auto-memory>`),q.push({name:"auto_memory",loaded:!0,length:L.length});else q.push({name:"auto_memory",loaded:!1})}catch{q.push({name:"auto_memory",loaded:!1})}if(Y){let w=K4(V);if(w)U.push(w),q.push({name:"environment",loaded:!0,length:w.length})}if(W?.trim())U.push(W.trim()),q.push({name:"append",loaded:!0,length:W.trim().length});let z=U.join(`
493
493
 
@@ -495,17 +495,17 @@ ${L}
495
495
 
496
496
  `);return z=X7(z),z=V7(z,Q),{prompt:z,sources:q}}function X7($){let J=Q$().generateAvailableSkillsList();if(!J)return $;return $.replace(W7,`<available_skills>
497
497
  ${J}
498
- </available_skills>`)}var Y7={"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 V7($,Z){let J=Z||"zh-CN",W=Y7[J]||J,X=`IMPORTANT: Always respond in ${W}. All your responses must be in ${W}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",X)}async function B7($){let Z=J7.join($,"BLADE.md");try{return(await B4.readFile(Z,"utf-8")).trim()||null}catch{return null}}import U4 from"fast-glob";import*as z0 from"fs/promises";import*as q4 from"path";function XX($){return $.endsWith("/")||$.endsWith("\\")}function I0($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}import*as K1 from"fs/promises";import*as o from"path";var Q4=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class Z0 extends Error{code;constructor($,Z){super($);this.code=Z;this.name="PathSecurityError"}}class Q1{static normalize($,Z){let J=o.isAbsolute($)?$:o.resolve(Z,$),W=o.normalize(J),X=o.normalize(Z);if(!W.startsWith(X))throw new Z0(`Path outside workspace: ${$} (resolved to ${W}, workspace: ${X})`,"PATH_OUTSIDE_WORKSPACE");return W}static checkRestricted($){let Z=$.split(o.sep);for(let J of Q4)if(Z.includes(J))throw new Z0(`Access denied: "${J}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new Z0(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,Z){this.checkTraversal($);let J=this.normalize($,Z);this.checkRestricted(J);try{await K1.access(J)}catch(W){throw new Z0(`Path not found: ${$}`,"PATH_NOT_FOUND")}return J}static async resolveSymlink($,Z){try{let J=await K1.realpath($),W=o.normalize(Z);if(!J.startsWith(W))throw new Z0(`Symlink points outside workspace: ${$} -> ${J}`,"SYMLINK_OUTSIDE_WORKSPACE");return J}catch(J){if(J instanceof Z0)throw J;return $}}static getRelativePath($,Z){return o.relative(Z,$)}static isWithinWorkspace($,Z){let J=o.normalize($),W=o.normalize(Z);return J.startsWith(W)}static isRestricted($){let Z=$.split(o.sep);return Q4.some((J)=>Z.includes(J))}}class U1{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let Z=[],J;this.PATTERN.lastIndex=0;while((J=this.PATTERN.exec($))!==null){let W=J[0],X=J[1]||J[2],Y=this.parseLineRange(X);if(Y)X=X.replace(this.LINE_RANGE_PATTERN,"");let V=this.GLOB_PATTERN.test(X);Z.push({raw:W,path:X.trim(),lineRange:Y,startIndex:J.index,endIndex:J.index+W.length,isGlob:V})}return Z}static parseLineRange($){let Z=$.match(this.LINE_RANGE_PATTERN);if(!Z)return;let J=parseInt(Z[1],10),W=Z[2]?parseInt(Z[2],10):void 0;return{start:J,end:W}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let Z=["<",">","|","\x00"];for(let J of Z)if($.includes(J))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var O$=M("Prompts");function q1($){return $ instanceof Map}class S0{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},O$.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!U1.hasAtMentions($))return[];let Z=U1.extract($);if(Z.length===0)return[];O$.debug(`Found ${Z.length} @ mentions`);let J=Z.map((X)=>this.processOne(X));return(await Promise.allSettled(J)).map((X,Y)=>{if(X.status==="fulfilled")return X.value;else{let V=Z[Y],B=X.reason instanceof Error?X.reason.message:String(X.reason);return O$.warn(`Failed to process @${V.path}:`,B),{type:"error",path:V.path,content:"",error:B}}})}async processOne($){if($.isGlob)return O$.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let Z=await Q1.validatePath($.path,this.options.cwd),J=await Q1.resolveSymlink(Z,this.options.cwd);if((await z0.stat(J)).isDirectory())return O$.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(J,$.path);return O$.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(J,$.path,$.lineRange)}async readFile($,Z,J){let W=this.fileCache.get($);if(W&&Date.now()-W.timestamp<60000)return O$.debug(`Cache hit: ${Z}`),this.formatFileAttachment(Z,W.content,J);let X=await z0.stat($);if(X.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(X.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let Y;try{Y=await z0.readFile($,"utf-8")}catch(V){throw Error(`Cannot read file as text: ${Z}. It may be a binary file.`)}return this.fileCache.set($,{content:Y,timestamp:Date.now()}),this.formatFileAttachment(Z,Y,J)}formatFileAttachment($,Z,J){let W=Z.split(`
498
+ </available_skills>`)}var Y7={"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 V7($,Z){let J=Z||"zh-CN",W=Y7[J]||J,X=`IMPORTANT: Always respond in ${W}. All your responses must be in ${W}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",X)}async function B7($){let Z=J7.join($,"BLADE.md");try{return(await B4.readFile(Z,"utf-8")).trim()||null}catch{return null}}import U4 from"fast-glob";import*as w0 from"fs/promises";import*as q4 from"path";function VX($){return $.endsWith("/")||$.endsWith("\\")}function S0($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}import*as K1 from"fs/promises";import*as o from"path";var Q4=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class J0 extends Error{code;constructor($,Z){super($);this.code=Z;this.name="PathSecurityError"}}class Q1{static normalize($,Z){let J=o.isAbsolute($)?$:o.resolve(Z,$),W=o.normalize(J),X=o.normalize(Z);if(!W.startsWith(X))throw new J0(`Path outside workspace: ${$} (resolved to ${W}, workspace: ${X})`,"PATH_OUTSIDE_WORKSPACE");return W}static checkRestricted($){let Z=$.split(o.sep);for(let J of Q4)if(Z.includes(J))throw new J0(`Access denied: "${J}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new J0(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,Z){this.checkTraversal($);let J=this.normalize($,Z);this.checkRestricted(J);try{await K1.access(J)}catch(W){throw new J0(`Path not found: ${$}`,"PATH_NOT_FOUND")}return J}static async resolveSymlink($,Z){try{let J=await K1.realpath($),W=o.normalize(Z);if(!J.startsWith(W))throw new J0(`Symlink points outside workspace: ${$} -> ${J}`,"SYMLINK_OUTSIDE_WORKSPACE");return J}catch(J){if(J instanceof J0)throw J;return $}}static getRelativePath($,Z){return o.relative(Z,$)}static isWithinWorkspace($,Z){let J=o.normalize($),W=o.normalize(Z);return J.startsWith(W)}static isRestricted($){let Z=$.split(o.sep);return Q4.some((J)=>Z.includes(J))}}class U1{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let Z=[],J;this.PATTERN.lastIndex=0;while((J=this.PATTERN.exec($))!==null){let W=J[0],X=J[1]||J[2],Y=this.parseLineRange(X);if(Y)X=X.replace(this.LINE_RANGE_PATTERN,"");let V=this.GLOB_PATTERN.test(X);Z.push({raw:W,path:X.trim(),lineRange:Y,startIndex:J.index,endIndex:J.index+W.length,isGlob:V})}return Z}static parseLineRange($){let Z=$.match(this.LINE_RANGE_PATTERN);if(!Z)return;let J=parseInt(Z[1],10),W=Z[2]?parseInt(Z[2],10):void 0;return{start:J,end:W}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let Z=["<",">","|","\x00"];for(let J of Z)if($.includes(J))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var z$=M("Prompts");function q1($){return $ instanceof Map}class P0{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},z$.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!U1.hasAtMentions($))return[];let Z=U1.extract($);if(Z.length===0)return[];z$.debug(`Found ${Z.length} @ mentions`);let J=Z.map((X)=>this.processOne(X));return(await Promise.allSettled(J)).map((X,Y)=>{if(X.status==="fulfilled")return X.value;else{let V=Z[Y],B=X.reason instanceof Error?X.reason.message:String(X.reason);return z$.warn(`Failed to process @${V.path}:`,B),{type:"error",path:V.path,content:"",error:B}}})}async processOne($){if($.isGlob)return z$.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let Z=await Q1.validatePath($.path,this.options.cwd),J=await Q1.resolveSymlink(Z,this.options.cwd);if((await w0.stat(J)).isDirectory())return z$.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(J,$.path);return z$.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(J,$.path,$.lineRange)}async readFile($,Z,J){let W=this.fileCache.get($);if(W&&Date.now()-W.timestamp<60000)return z$.debug(`Cache hit: ${Z}`),this.formatFileAttachment(Z,W.content,J);let X=await w0.stat($);if(X.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(X.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let Y;try{Y=await w0.readFile($,"utf-8")}catch(V){throw Error(`Cannot read file as text: ${Z}. It may be a binary file.`)}return this.fileCache.set($,{content:Y,timestamp:Date.now()}),this.formatFileAttachment(Z,Y,J)}formatFileAttachment($,Z,J){let W=Z.split(`
499
499
  `),X=Z,Y=!1,V=J;if(J){let B=Math.max(0,J.start-1),K=J.end?J.end:J.start;if(B>=W.length)throw Error(`Line range start (${J.start}) exceeds file length (${W.length} lines)`);let Q=Math.min(K,W.length);X=W.slice(B,Q).join(`
500
500
  `);let U=Array.from({length:Q-B},(H,G)=>B+G+1);X=X.split(`
501
501
  `).map((H,G)=>`${U[G]}: ${H}`).join(`
502
502
  `),V={start:J.start,end:Q}}else if(W.length>this.options.maxLines)X=W.slice(0,this.options.maxLines).join(`
503
503
  `),X+=`
504
504
 
505
- [... truncated ${W.length-this.options.maxLines} lines ...]`,Y=!0;return{type:"file",path:$,content:X,metadata:{size:Z.length,lines:W.length,truncated:Y,lineRange:V}}}async renderDirectoryTree($,Z){let J=await U4("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(J.length===0)return{type:"directory",path:Z,content:"(empty directory)"};O$.debug(`Found ${J.length} files in directory: ${Z}`);let W=this.buildFileTree(J),X=this.printTree(W,Z),Y=500,V=J.length>Y?`
505
+ [... truncated ${W.length-this.options.maxLines} lines ...]`,Y=!0;return{type:"file",path:$,content:X,metadata:{size:Z.length,lines:W.length,truncated:Y,lineRange:V}}}async renderDirectoryTree($,Z){let J=await U4("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(J.length===0)return{type:"directory",path:Z,content:"(empty directory)"};z$.debug(`Found ${J.length} files in directory: ${Z}`);let W=this.buildFileTree(J),X=this.printTree(W,Z),Y=500,V=J.length>Y?`
506
506
 
507
- [... and ${J.length-Y} more files]`:"";return{type:"directory",path:Z,content:X+V,metadata:{lines:J.length,truncated:J.length>Y}}}buildFileTree($){let Z=new Map;for(let J of $){let W=I0(J),X=Z;for(let Y=0;Y<W.length;Y++){let V=W[Y],B=Y===W.length-1;if(!X.has(V))X.set(V,B?null:new Map);if(!B){let K=X.get(V);if(K&&q1(K))X=K}}}return Z}printTree($,Z,J="",W=!0){let X=[];if(J==="")X.push(`${Z}/`);let Y=Array.from($.entries()).sort((V,B)=>{let K=q1(V[1]),Q=q1(B[1]);if(K!==Q)return Q?1:-1;return V[0].localeCompare(B[0])});return Y.forEach(([V,B],K)=>{let Q=K===Y.length-1,U=Q?"└── ":"├── ",q=q1(B);if(X.push(`${J}${U}${V}${q?"/":""}`),q&&B.size>0){let H=J+(Q?" ":"│ ");X.push(this.printTree(B,"",H,Q))}}),X.filter((V)=>V).join(`
508
- `)}async processGlob($){let Z=await U4($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};O$.debug(`Glob pattern "${$}" matched ${Z.length} files`);let J=30,W=Z.slice(0,J),Y=(await Promise.allSettled(W.map(async(Q)=>{let U=q4.join(this.options.cwd,Q);try{let q=await z0.readFile(U,"utf-8"),H=q.split(`
507
+ [... and ${J.length-Y} more files]`:"";return{type:"directory",path:Z,content:X+V,metadata:{lines:J.length,truncated:J.length>Y}}}buildFileTree($){let Z=new Map;for(let J of $){let W=S0(J),X=Z;for(let Y=0;Y<W.length;Y++){let V=W[Y],B=Y===W.length-1;if(!X.has(V))X.set(V,B?null:new Map);if(!B){let K=X.get(V);if(K&&q1(K))X=K}}}return Z}printTree($,Z,J="",W=!0){let X=[];if(J==="")X.push(`${Z}/`);let Y=Array.from($.entries()).sort((V,B)=>{let K=q1(V[1]),Q=q1(B[1]);if(K!==Q)return Q?1:-1;return V[0].localeCompare(B[0])});return Y.forEach(([V,B],K)=>{let Q=K===Y.length-1,U=Q?"└── ":"├── ",q=q1(B);if(X.push(`${J}${U}${V}${q?"/":""}`),q&&B.size>0){let H=J+(Q?" ":"│ ");X.push(this.printTree(B,"",H,Q))}}),X.filter((V)=>V).join(`
508
+ `)}async processGlob($){let Z=await U4($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};z$.debug(`Glob pattern "${$}" matched ${Z.length} files`);let J=30,W=Z.slice(0,J),Y=(await Promise.allSettled(W.map(async(Q)=>{let U=q4.join(this.options.cwd,Q);try{let q=await w0.readFile(U,"utf-8"),H=q.split(`
509
509
  `),G=200,O=q,F=!1;if(H.length>200)O=H.slice(0,200).join(`
510
510
  `),O+=`
511
511
 
@@ -514,7 +514,7 @@ ${Q.content}`).join(`
514
514
 
515
515
  `),K=Z.length>J?`
516
516
 
517
- [... and ${Z.length-J} more files matched]`:"";return{type:"file",path:$,content:B+K,metadata:{lines:Y.reduce((Q,U)=>Q+U.lines,0),truncated:Z.length>J||Y.some((Q)=>Q.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[J,W]of this.fileCache.entries())if($-W.timestamp>60000)this.fileCache.delete(J),Z++;if(Z>0)O$.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),O$.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import*as h9 from"os";import*as p9 from"path";import{basename as U7,extname as q7}from"path";import{z as G1}from"zod";import{spawn as Q7}from"child_process";import*as z$ from"fs/promises";class S${async readTextFile($){return z$.readFile($,"utf-8")}async writeTextFile($,Z){await z$.writeFile($,Z,"utf-8")}async exists($){try{return await z$.access($),!0}catch{return!1}}async readBinaryFile($){return z$.readFile($)}async stat($){try{let Z=await z$.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await z$.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var K5=new S$;function w0(){return K5}function H1($){K5=$}function H4(){K5=new S$}var U$=M("Agent");class Q5{connection;sessionId;capabilities;fallback;constructor($,Z,J,W=new S$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=W}async readTextFile($){if(!this.capabilities.readTextFile)return U$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return U$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return U$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return U$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{U$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){return U$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${J}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return U$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),U$.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((V)=>J.includes(V)))return U$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=K7(J);return U$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return U$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return U$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return U$.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function K7($){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 E$=M("Agent");class U5{async execute($,Z){return new Promise((J)=>{let W=process.platform==="win32"?"cmd.exe":"/bin/bash",X=process.platform==="win32"?["/c",$]:["-c",$],Y=Q7(W,X,{cwd:Z?.cwd||N(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),V="",B="",K=!1,Q=Z?.timeout?setTimeout(()=>{K=!0,Y.kill("SIGTERM")},Z.timeout):null,U=null,q=()=>{if(Q)clearTimeout(Q);if(U&&Z?.signal)Z.signal.removeEventListener("abort",U),U=null};if(Z?.signal)U=()=>{K=!0,Y.kill("SIGTERM")},Z.signal.addEventListener("abort",U);Y.stdout.on("data",(H)=>{let G=H.toString();V+=G,Z?.onOutput?.(G)}),Y.stderr.on("data",(H)=>{let G=H.toString();B+=G,Z?.onOutput?.(G)}),Y.on("close",(H)=>{q(),J({success:H===0&&!K,stdout:V,stderr:B,exitCode:H,error:K?"Command was terminated":void 0})}),Y.on("error",(H)=>{q(),J({success:!1,stdout:V,stderr:B,exitCode:null,error:H.message})})})}isAvailable(){return!0}}class G4{connection;sessionId;fallback;constructor($,Z,J=new U5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{E$.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([Q,U])=>({name:Q,value:U})):void 0}),W=0,X=null;if(Z?.onOutput)X=setInterval(async()=>{try{let U=(await J.currentOutput()).output||"";if(U.length>W){let q=U.slice(W);W=U.length,Z.onOutput?.(q)}}catch{}},100);let Y=(Q=!1)=>{if(X)clearInterval(X),X=null;(Q?J.kill().then(()=>E$.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},V=[];if(V.push(J.waitForExit().then((Q)=>({type:"completed",exitCode:Q.exitCode??null}))),Z?.timeout)V.push(new Promise((Q)=>{setTimeout(()=>Q({type:"timeout"}),Z.timeout)}));if(Z?.signal)V.push(new Promise((Q)=>{if(Z.signal.aborted)Q({type:"aborted"});else Z.signal.addEventListener("abort",()=>Q({type:"aborted"}),{once:!0})}));let B=await Promise.race(V),K="";try{if(K=(await J.currentOutput()).output||"",Z?.onOutput&&K.length>W)Z.onOutput(K.slice(W))}catch{}switch(B.type){case"completed":return Y(!1),{success:B.exitCode===0,stdout:K,stderr:"",exitCode:B.exitCode};case"timeout":return E$.debug(`[AcpTerminal] Command timed out, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return E$.debug(`[AcpTerminal] Command aborted, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){return E$.warn("[AcpTerminal] ACP terminal failed, using fallback:",J),this.fallback.execute($,Z)}}isAvailable(){return!0}}class R{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new R}static initializeSession($,Z,J,W){let X=J?.fs?new Q5($,Z,J.fs):new S$;if(J?.fs)E$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let Y=new G4($,Z);E$.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),R.sessions.set(Z,{fileSystemService:X,terminalService:Y,connection:$,clientCapabilities:J||null,cwd:W}),R.currentSessionId=Z,H1(X),E$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:W})}static destroySession($){if(R.sessions.delete($),R.currentSessionId===$){let Z=Array.from(R.sessions.keys());if(R.currentSessionId=Z[0]||null,!R.currentSessionId)H4();else{let J=R.sessions.get(R.currentSessionId);if(J)H1(J.fileSystemService)}}E$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return R.sessions.get($)||null}static setCurrentSession($){if(R.sessions.has($)){R.currentSessionId=$;let Z=R.sessions.get($);if(Z)H1(Z.fileSystemService)}}static getCurrentSessionId(){return R.currentSessionId}initialize($,Z,J,W){R.initializeSession($,Z,J,W||N())}reset(){if(R.currentSessionId)R.destroySession(R.currentSessionId)}isAcpMode(){return R.currentSessionId!==null}getFileSystemService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.fileSystemService}return new S$}getTerminalService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.terminalService}return new U5}getConnection(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.connection}return null}getSessionId(){return R.currentSessionId}getClientCapabilities(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,W,X){let Y=R.currentSessionId;if(!Y)return;let V=R.sessions.get(Y);if(!V)return;try{await V.connection.sessionUpdate({sessionId:Y,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:W||[],kind:X||"other"}})}catch(B){E$.warn("[AcpServiceContext] Failed to send tool update:",B)}}}function F4(){return R.getInstance().getTerminalService()}function P$(){return R.getInstance().isAcpMode()}import{isAbsolute as O4}from"path";import{z as g}from"zod";var y={filePath:($)=>g.string().min(1,"File path is required").refine((Z)=>O4(Z),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>g.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Z=300000,J=30000)=>g.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(Z,`Cannot exceed ${Z}ms`).default(J).describe(`Timeout in milliseconds (default ${J}ms)`),pattern:($)=>g.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>g.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>g.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>g.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:()=>g.string().min(1,"Working directory is required").refine(($)=>O4($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>g.record(g.string(),g.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Z)=>{let J=g.enum($);return Z?J.default(Z):J},flag:($)=>g.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>g.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>g.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:($)=>g.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>g.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>g.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>g.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as q5 from"diff";function z4($,Z,J=4){if($===Z)return null;let W=q5.createPatch("file",$,Z,"","",{context:J}),X=W.split(`
517
+ [... and ${Z.length-J} more files matched]`:"";return{type:"file",path:$,content:B+K,metadata:{lines:Y.reduce((Q,U)=>Q+U.lines,0),truncated:Z.length>J||Y.some((Q)=>Q.truncated)}}}clearExpiredCache(){let $=Date.now(),Z=0;for(let[J,W]of this.fileCache.entries())if($-W.timestamp>60000)this.fileCache.delete(J),Z++;if(Z>0)z$.debug(`Cleared ${Z} expired cache entries`)}clearCache(){this.fileCache.clear(),z$.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import*as h9 from"os";import*as p9 from"path";import{basename as U7,extname as q7}from"path";import{z as G1}from"zod";import{spawn as Q7}from"child_process";import*as w$ from"fs/promises";class P${async readTextFile($){return w$.readFile($,"utf-8")}async writeTextFile($,Z){await w$.writeFile($,Z,"utf-8")}async exists($){try{return await w$.access($),!0}catch{return!1}}async readBinaryFile($){return w$.readFile($)}async stat($){try{let Z=await w$.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch{return null}}async mkdir($,Z){await w$.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var K5=new P$;function j0(){return K5}function H1($){K5=$}function H4(){K5=new P$}var U$=M("Agent");class Q5{connection;sessionId;capabilities;fallback;constructor($,Z,J,W=new P$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=W}async readTextFile($){if(!this.capabilities.readTextFile)return U$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return U$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return U$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return U$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{U$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){return U$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${J}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return U$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),U$.debug(`[AcpFileSystem] exists(${$}): true (ACP read success)`),!0}catch(Z){let J=String(Z).toLowerCase();if(["not found","no such file","enoent","does not exist","file not found","path not found"].some((V)=>J.includes(V)))return U$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=K7(J);return U$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return U$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return U$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return U$.debug(`[AcpFileSystem] mkdir fallback: ${$}`),this.fallback.mkdir($,Z)}getCapabilities(){return this.capabilities}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}}function K7($){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 _$=M("Agent");class U5{async execute($,Z){return new Promise((J)=>{let W=process.platform==="win32"?"cmd.exe":"/bin/bash",X=process.platform==="win32"?["/c",$]:["-c",$],Y=Q7(W,X,{cwd:Z?.cwd||N(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]}),V="",B="",K=!1,Q=Z?.timeout?setTimeout(()=>{K=!0,Y.kill("SIGTERM")},Z.timeout):null,U=null,q=()=>{if(Q)clearTimeout(Q);if(U&&Z?.signal)Z.signal.removeEventListener("abort",U),U=null};if(Z?.signal)U=()=>{K=!0,Y.kill("SIGTERM")},Z.signal.addEventListener("abort",U);Y.stdout.on("data",(H)=>{let G=H.toString();V+=G,Z?.onOutput?.(G)}),Y.stderr.on("data",(H)=>{let G=H.toString();B+=G,Z?.onOutput?.(G)}),Y.on("close",(H)=>{q(),J({success:H===0&&!K,stdout:V,stderr:B,exitCode:H,error:K?"Command was terminated":void 0})}),Y.on("error",(H)=>{q(),J({success:!1,stdout:V,stderr:B,exitCode:null,error:H.message})})})}isAvailable(){return!0}}class G4{connection;sessionId;fallback;constructor($,Z,J=new U5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{_$.debug(`[AcpTerminal] Executing command via ACP: ${$}`);let J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([Q,U])=>({name:Q,value:U})):void 0}),W=0,X=null;if(Z?.onOutput)X=setInterval(async()=>{try{let U=(await J.currentOutput()).output||"";if(U.length>W){let q=U.slice(W);W=U.length,Z.onOutput?.(q)}}catch{}},100);let Y=(Q=!1)=>{if(X)clearInterval(X),X=null;(Q?J.kill().then(()=>_$.debug("[AcpTerminal] Killed remote command")).catch(()=>{}).then(()=>J.release()).catch(()=>{}):J.release().catch(()=>{})).catch(()=>{})},V=[];if(V.push(J.waitForExit().then((Q)=>({type:"completed",exitCode:Q.exitCode??null}))),Z?.timeout)V.push(new Promise((Q)=>{setTimeout(()=>Q({type:"timeout"}),Z.timeout)}));if(Z?.signal)V.push(new Promise((Q)=>{if(Z.signal.aborted)Q({type:"aborted"});else Z.signal.addEventListener("abort",()=>Q({type:"aborted"}),{once:!0})}));let B=await Promise.race(V),K="";try{if(K=(await J.currentOutput()).output||"",Z?.onOutput&&K.length>W)Z.onOutput(K.slice(W))}catch{}switch(B.type){case"completed":return Y(!1),{success:B.exitCode===0,stdout:K,stderr:"",exitCode:B.exitCode};case"timeout":return _$.debug(`[AcpTerminal] Command timed out, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return _$.debug(`[AcpTerminal] Command aborted, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){return _$.warn("[AcpTerminal] ACP terminal failed, using fallback:",J),this.fallback.execute($,Z)}}isAvailable(){return!0}}class R{static sessions=new Map;static currentSessionId=null;constructor(){}static getInstance(){return new R}static initializeSession($,Z,J,W){let X=J?.fs?new Q5($,Z,J.fs):new P$;if(J?.fs)_$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let Y=new G4($,Z);_$.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),R.sessions.set(Z,{fileSystemService:X,terminalService:Y,connection:$,clientCapabilities:J||null,cwd:W}),R.currentSessionId=Z,H1(X),_$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile,cwd:W})}static destroySession($){if(R.sessions.delete($),R.currentSessionId===$){let Z=Array.from(R.sessions.keys());if(R.currentSessionId=Z[0]||null,!R.currentSessionId)H4();else{let J=R.sessions.get(R.currentSessionId);if(J)H1(J.fileSystemService)}}_$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static getSessionServices($){return R.sessions.get($)||null}static setCurrentSession($){if(R.sessions.has($)){R.currentSessionId=$;let Z=R.sessions.get($);if(Z)H1(Z.fileSystemService)}}static getCurrentSessionId(){return R.currentSessionId}initialize($,Z,J,W){R.initializeSession($,Z,J,W||N())}reset(){if(R.currentSessionId)R.destroySession(R.currentSessionId)}isAcpMode(){return R.currentSessionId!==null}getFileSystemService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.fileSystemService}return new P$}getTerminalService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.terminalService}return new U5}getConnection(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.connection}return null}getSessionId(){return R.currentSessionId}getClientCapabilities(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,W,X){let Y=R.currentSessionId;if(!Y)return;let V=R.sessions.get(Y);if(!V)return;try{await V.connection.sessionUpdate({sessionId:Y,update:{sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:W||[],kind:X||"other"}})}catch(B){_$.warn("[AcpServiceContext] Failed to send tool update:",B)}}}function F4(){return R.getInstance().getTerminalService()}function y$(){return R.getInstance().isAcpMode()}import{isAbsolute as O4}from"path";import{z as g}from"zod";var y={filePath:($)=>g.string().min(1,"File path is required").refine((Z)=>O4(Z),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>g.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Z=300000,J=30000)=>g.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(Z,`Cannot exceed ${Z}ms`).default(J).describe(`Timeout in milliseconds (default ${J}ms)`),pattern:($)=>g.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>g.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>g.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>g.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:()=>g.string().min(1,"Working directory is required").refine(($)=>O4($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>g.record(g.string(),g.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Z)=>{let J=g.enum($);return Z?J.default(Z):J},flag:($)=>g.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>g.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>g.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:($)=>g.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>g.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>g.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>g.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as q5 from"diff";function z4($,Z,J=4){if($===Z)return null;let W=q5.createPatch("file",$,Z,"","",{context:J}),X=W.split(`
518
518
  `),Y=1;for(let V of X){let B=V.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(B){Y=parseInt(B[1],10);break}}return`
519
519
  <<<DIFF>>>
520
520
  ${JSON.stringify({patch:W,startLine:Math.max(1,Y-J),matchLine:Y})}
@@ -538,11 +538,11 @@ ${JSON.stringify({patch:w,startLine:H+1,matchLine:B+1})}
538
538
  `),K=$.split(`
539
539
  `);for(let Q=0;Q<=K.length-J.length;Q++){let U=K[Q].match(/^(\s+)/),q=U?U[1]:"",H=K.slice(Q,Q+J.length);if(H.map((F)=>{if(F.startsWith(q))return F.slice(q.length);return F}).join(`
540
540
  `)===B)return H.join(`
541
- `)}return null}import*as D4 from"node:crypto";import{promises as _$}from"node:fs";import*as J0 from"node:path";class P0{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let Z=b$();this.snapshotDir=J0.join(Z,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await _$.mkdir(this.snapshotDir,{recursive:!0,mode:493}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,Z){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await _$.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let J=this.trackedFileBackups.get($),W=J?J.version+1:1,X=this.generateFileHash($,W),Y=J0.join(this.snapshotDir,`${X}@v${W}`);try{let V=await _$.readFile($,{encoding:"utf-8"});await _$.writeFile(Y,V,{encoding:"utf-8"});let B={backupFileName:X,version:W,backupTime:new Date};return this.trackedFileBackups.set($,B),this.snapshots.push({messageId:Z,backupFileName:X,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${X}@v${W}`),await this.cleanupOldSnapshots($),B}catch(V){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,V),V}}async restoreSnapshot($,Z){let J=this.snapshots.slice().reverse().find((Y)=>Y.messageId===Z&&Y.filePath===$);if(!J)throw Error(`未找到快照: messageId=${Z}, filePath=${$}`);let W=this.trackedFileBackups.get($);if(!W)throw Error(`未找到文件追踪信息: ${$}`);let X=J0.join(this.snapshotDir,`${J.backupFileName}@v${W.version}`);try{let Y=await _$.readFile(X,{encoding:"utf-8"});await _$.writeFile($,Y,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${J.backupFileName}@v${W.version}`)}catch(Y){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,Y),Y}}async listSnapshots($){return this.snapshots.filter((Z)=>Z.filePath===$)}async cleanupOldSnapshots($){let Z=this.snapshots.filter((X)=>X.filePath===$);if(Z.length<=this.maxSnapshots)return;let W=Z.sort((X,Y)=>X.timestamp.getTime()-Y.timestamp.getTime()).slice(0,Z.length-this.maxSnapshots);for(let X of W){let Y=this.trackedFileBackups.get(X.filePath);if(!Y)continue;let V=J0.join(this.snapshotDir,`${X.backupFileName}@v${Y.version}`);try{await _$.unlink(V),console.log(`[SnapshotManager] 删除旧快照: ${V}`)}catch(K){console.warn(`[SnapshotManager] 删除快照失败: ${V}`,K)}let B=this.snapshots.indexOf(X);if(B>-1)this.snapshots.splice(B,1)}}async cleanup($=0){try{let Z=await _$.readdir(this.snapshotDir);if(Z.length<=$)return;let J=await Promise.all(Z.map(async(X)=>{let Y=J0.join(this.snapshotDir,X),V=await _$.stat(Y);return{file:X,mtime:V.mtime.getTime()}}));J.sort((X,Y)=>Y.mtime-X.mtime);let W=J.slice($);for(let{file:X}of W){let Y=J0.join(this.snapshotDir,X);await _$.unlink(Y),console.log(`[SnapshotManager] 清理快照: ${Y}`)}}catch(Z){console.warn("[SnapshotManager] 清理快照失败:",Z)}}generateFileHash($,Z){let J=D4.createHash("md5");return J.update(`${$}:${Z}`),J.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var H5=D({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:G1.object({file_path:y.filePath({description:"Absolute path of the file to edit"}),old_string:G1.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:G1.string().describe("Replacement string (can be empty)"),replace_all:G1.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($,Z){let{file_path:J,old_string:W,new_string:X,replace_all:Y}=$,{updateOutput:V,sessionId:B,messageId:K}=Z,Q=Z.signal??new AbortController().signal;try{V?.("Starting to read file...");let U=w0(),q=P$(),H;try{if(q)V?.("通过 IDE 读取文件...");H=await U.readTextFile(J)}catch(v){let J$=v;if(J$.code==="ENOENT"||J$.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:"文件不存在"}};throw v}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(B){let v=y$.getInstance();if(!v.hasFileBeenRead(J,B))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 J$=await v.checkExternalModification(J);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 editing.
541
+ `)}return null}import*as D4 from"node:crypto";import{promises as A$}from"node:fs";import*as W0 from"node:path";class y0{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let Z=T$();this.snapshotDir=W0.join(Z,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await A$.mkdir(this.snapshotDir,{recursive:!0,mode:493}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,Z){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await A$.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let J=this.trackedFileBackups.get($),W=J?J.version+1:1,X=this.generateFileHash($,W),Y=W0.join(this.snapshotDir,`${X}@v${W}`);try{let V=await A$.readFile($,{encoding:"utf-8"});await A$.writeFile(Y,V,{encoding:"utf-8"});let B={backupFileName:X,version:W,backupTime:new Date};return this.trackedFileBackups.set($,B),this.snapshots.push({messageId:Z,backupFileName:X,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${X}@v${W}`),await this.cleanupOldSnapshots($),B}catch(V){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,V),V}}async restoreSnapshot($,Z){let J=this.snapshots.slice().reverse().find((Y)=>Y.messageId===Z&&Y.filePath===$);if(!J)throw Error(`未找到快照: messageId=${Z}, filePath=${$}`);let W=this.trackedFileBackups.get($);if(!W)throw Error(`未找到文件追踪信息: ${$}`);let X=W0.join(this.snapshotDir,`${J.backupFileName}@v${W.version}`);try{let Y=await A$.readFile(X,{encoding:"utf-8"});await A$.writeFile($,Y,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${J.backupFileName}@v${W.version}`)}catch(Y){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,Y),Y}}async listSnapshots($){return this.snapshots.filter((Z)=>Z.filePath===$)}async cleanupOldSnapshots($){let Z=this.snapshots.filter((X)=>X.filePath===$);if(Z.length<=this.maxSnapshots)return;let W=Z.sort((X,Y)=>X.timestamp.getTime()-Y.timestamp.getTime()).slice(0,Z.length-this.maxSnapshots);for(let X of W){let Y=this.trackedFileBackups.get(X.filePath);if(!Y)continue;let V=W0.join(this.snapshotDir,`${X.backupFileName}@v${Y.version}`);try{await A$.unlink(V),console.log(`[SnapshotManager] 删除旧快照: ${V}`)}catch(K){console.warn(`[SnapshotManager] 删除快照失败: ${V}`,K)}let B=this.snapshots.indexOf(X);if(B>-1)this.snapshots.splice(B,1)}}async cleanup($=0){try{let Z=await A$.readdir(this.snapshotDir);if(Z.length<=$)return;let J=await Promise.all(Z.map(async(X)=>{let Y=W0.join(this.snapshotDir,X),V=await A$.stat(Y);return{file:X,mtime:V.mtime.getTime()}}));J.sort((X,Y)=>Y.mtime-X.mtime);let W=J.slice($);for(let{file:X}of W){let Y=W0.join(this.snapshotDir,X);await A$.unlink(Y),console.log(`[SnapshotManager] 清理快照: ${Y}`)}}catch(Z){console.warn("[SnapshotManager] 清理快照失败:",Z)}}generateFileHash($,Z){let J=D4.createHash("md5");return J.update(`${$}:${Z}`),J.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var H5=D({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:G1.object({file_path:y.filePath({description:"Absolute path of the file to edit"}),old_string:G1.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:G1.string().describe("Replacement string (can be empty)"),replace_all:G1.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($,Z){let{file_path:J,old_string:W,new_string:X,replace_all:Y}=$,{updateOutput:V,sessionId:B,messageId:K}=Z,Q=Z.signal??new AbortController().signal;try{V?.("Starting to read file...");let U=j0(),q=y$(),H;try{if(q)V?.("通过 IDE 读取文件...");H=await U.readTextFile(J)}catch(v){let J$=v;if(J$.code==="ENOENT"||J$.message?.includes("not found"))return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:"文件不存在"}};throw v}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(B){let v=x$.getInstance();if(!v.hasFileBeenRead(J,B))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 J$=await v.checkExternalModification(J);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 editing.
542
542
 
543
- Details: ${J$.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:J$.message}}}}if(B&&K)try{let v=new P0({sessionId:B});await v.initialize(),await v.createSnapshot(J,K)}catch(v){console.warn("[EditTool] 创建快照失败:",v)}if(W===X)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let G=H7(H,W);if(!G.matched){let v=F7(H,W,J);return{success:!1,llmContent:v.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:v.metadata}}}let O=G.matched;if(G.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${G.strategy}`);let F=G7(H,O);if(F.length>1&&!Y){let v=H.split(`
544
- `),J$=0,v0=[];for(let K$=0;K$<v.length;K$++){let J5=v[K$],p8=J$,d8=J$+J5.length;for(let W5 of F)if(W5>=p8&&W5<d8){let p2=Math.max(0,K$-1),d2=Math.min(v.length-1,K$+1),u2=v.slice(p2,d2+1).map((g2)=>g2.trim()).join(" ").slice(0,80);v0.push({line:K$+1,column:W5-p8+1,context:u2})}J$=d8+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${F.length} locations (must be unique).`,"","**Matches found at:**",...v0.map((K$,J5)=>` ${J5+1}. Line ${K$.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 ${F.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
545
- `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:v0.map((K$)=>({line:K$.line,column:K$.column})),count:F.length}}}}else V?.(`找到 ${F.length} 个匹配项,开始替换...`);let z,w;if(Y)z=H.split(O).join(X),w=F.length;else{let v=H.indexOf(O);z=H.substring(0,v)+X+H.substring(v+O.length),w=1}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(q)V?.("通过 IDE 写入文件...");if(await U.writeTextFile(J,z),B)await y$.getInstance().recordFileEdit(J,B,"edit");let L=await U.stat(J),E=w4(H,z,O,X,4),j=U7(J),b=w===1?`替换 1 处匹配到 ${j}`:`替换 ${w} 处匹配到 ${j}`,a={file_path:J,matches_found:F.length,replacements_made:w,replace_all:Y,old_string_length:W.length,new_string_length:X.length,original_size:H.length,new_size:z.length,size_diff:z.length-H.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:!!(B&&K),session_id:B,message_id:K,diff_snippet:E,summary:b,kind:"edit",oldContent:H,newContent:z};return{success:!0,llmContent:E?`Edited ${J} (${w} replacement${w>1?"s":""}):
543
+ Details: ${J$.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:J$.message}}}}if(B&&K)try{let v=new y0({sessionId:B});await v.initialize(),await v.createSnapshot(J,K)}catch(v){console.warn("[EditTool] 创建快照失败:",v)}if(W===X)return{success:!1,llmContent:"New string is identical; no replacement needed",error:{type:"validation_error",message:"新旧字符串相同"}};let G=H7(H,W);if(!G.matched){let v=F7(H,W,J);return{success:!1,llmContent:v.llmContent,error:{type:"execution_error",message:"未找到匹配内容",details:v.metadata}}}let O=G.matched;if(G.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${G.strategy}`);let F=G7(H,O);if(F.length>1&&!Y){let v=H.split(`
544
+ `),J$=0,C0=[];for(let K$=0;K$<v.length;K$++){let J5=v[K$],p8=J$,d8=J$+J5.length;for(let W5 of F)if(W5>=p8&&W5<d8){let p2=Math.max(0,K$-1),d2=Math.min(v.length-1,K$+1),u2=v.slice(p2,d2+1).map((g2)=>g2.trim()).join(" ").slice(0,80);C0.push({line:K$+1,column:W5-p8+1,context:u2})}J$=d8+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${F.length} locations (must be unique).`,"","**Matches found at:**",...C0.map((K$,J5)=>` ${J5+1}. Line ${K$.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 ${F.length} occurrences`,"","**Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
545
+ `),error:{type:"validation_error",message:"old_string is not unique",details:{matches:C0.map((K$)=>({line:K$.line,column:K$.column})),count:F.length}}}}else V?.(`找到 ${F.length} 个匹配项,开始替换...`);let z,w;if(Y)z=H.split(O).join(X),w=F.length;else{let v=H.indexOf(O);z=H.substring(0,v)+X+H.substring(v+O.length),w=1}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(q)V?.("通过 IDE 写入文件...");if(await U.writeTextFile(J,z),B)await x$.getInstance().recordFileEdit(J,B,"edit");let L=await U.stat(J),E=w4(H,z,O,X,4),j=U7(J),b=w===1?`替换 1 处匹配到 ${j}`:`替换 ${w} 处匹配到 ${j}`,a={file_path:J,matches_found:F.length,replacements_made:w,replace_all:Y,old_string_length:W.length,new_string_length:X.length,original_size:H.length,new_size:z.length,size_diff:z.length-H.length,last_modified:L?.mtime instanceof Date?L.mtime.toISOString():void 0,snapshot_created:!!(B&&K),session_id:B,message_id:K,diff_snippet:E,summary:b,kind:"edit",oldContent:H,newContent:z};return{success:!0,llmContent:E?`Edited ${J} (${w} replacement${w>1?"s":""}):
546
546
  ${E}`:`Edited ${J} (${w} replacement${w>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 Z=q7($.file_path);return Z?`**/*${Z}`:"**/*"}});function L4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function H7($,Z){if($.includes(Z))return{matched:Z,strategy:"exact"};let J=L4(Z),X=L4($).indexOf(J);if(X!==-1)return{matched:$.substring(X,X+Z.length),strategy:"normalize_quotes"};let Y=j4(Z);if(Y!==Z&&$.includes(Y))return{matched:Y,strategy:"unescape"};let V=N4($,Z);if(V)return{matched:V,strategy:"flexible"};return{matched:null,strategy:"failed"}}function G7($,Z){if(Z.length===0)return[];let J=[],W=$.indexOf(Z);while(W!==-1)J.push(W),W=$.indexOf(Z,W+Z.length);return J}function F7($,Z,J){let W=$.split(`
547
547
  `),X=W.length,Y=O7($,Z,3),V=0,B=Math.min(20,X);if(Y.length>0){let H=Y[0];V=Math.max(0,H.lineNumber-10),B=Math.min(X,H.lineNumber+10)}let Q=W.slice(V,B).map((H,G)=>{return` ${(V+G+1).toString().padStart(4)}: ${H}`}).join(`
548
548
  `),U=`String not found in file.
@@ -577,15 +577,15 @@ Common issues:
577
577
  - Outdated mental model: File may have changed since you last read it`,{llmContent:U,metadata:{searchStringLength:Z.length,fuzzyMatches:Y.map((H)=>({line:H.lineNumber,similarity:H.similarity,preview:H.text.substring(0,100)})),excerptRange:[V+1,B],totalLines:X}}}function O7($,Z,J=3){let W=$.split(`
578
578
  `),X=Z.split(`
579
579
  `);if(X.length===1)return W.map((K,Q)=>({text:K,lineNumber:Q+1,similarity:E4(Z.trim(),K.trim())})).filter((K)=>K.similarity>0.5).sort((K,Q)=>Q.similarity-K.similarity).slice(0,J);let Y=X.length,V=[];for(let B=0;B<=W.length-Y;B++){let K=W.slice(B,B+Y).join(`
580
- `),Q=E4(Z,K);if(Q>0.5)V.push({text:K,lineNumber:B+1,similarity:Q})}return V.sort((B,K)=>K.similarity-B.similarity).slice(0,J)}function E4($,Z){let J=(H)=>H.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),W=J($),X=J(Z);if(W===X)return 1;let Y=W.length,V=X.length;if(Y===0)return V===0?1:0;if(V===0)return 0;let B=200,K=W.substring(0,B),Q=X.substring(0,B),U=z7(K,Q),q=Math.max(K.length,Q.length);return 1-U/q}function z7($,Z){let J=$.length,W=Z.length,X=Array(J+1).fill(null).map(()=>Array(W+1).fill(0));for(let Y=0;Y<=J;Y++)X[Y][0]=Y;for(let Y=0;Y<=W;Y++)X[0][Y]=Y;for(let Y=1;Y<=J;Y++)for(let V=1;V<=W;V++){let B=$[Y-1]===Z[V-1]?0:1;X[Y][V]=Math.min(X[Y-1][V]+1,X[Y][V-1]+1,X[Y-1][V-1]+B)}return X[J][W]}import{basename as w7,extname as _4}from"path";import{z as j7}from"zod";var G5=D({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:j7.object({file_path:y.filePath({description:"File path to read (must be absolute)"}),offset:y.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:y.lineLimit({description:"Number of lines to read (text files only)"}).optional(),encoding:y.encoding()}),description:{short:"Read files from the local filesystem",long:"Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.",usageNotes:["The file_path parameter must be an absolute path, not a relative path","By default, it reads up to 2000 lines starting from the beginning of the file","You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters","Any lines longer than 2000 characters will be truncated","Results are returned using cat -n format, with line numbers starting at 1","This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as this is a multimodal LLM.","This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.","This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.","This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.","You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.","You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.","If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."],examples:[{description:"Read the entire file (recommended)",params:{file_path:"/path/to/file.ts"}},{description:"Read the first 100 lines",params:{file_path:"/path/to/file.txt",limit:100}},{description:"Read 100 lines starting at line 50 (large file)",params:{file_path:"/path/to/large-file.log",offset:50,limit:100}}],important:["file_path must be absolute","Prefer reading the entire file (omit offset and limit)","Use offset/limit only for very large files","Line numbers start at 1 (cat -n format)"]},async execute($,Z){let{file_path:J,offset:W,limit:X,encoding:Y="utf8"}=$,{updateOutput:V,sessionId:B}=Z,K=Z.signal??new AbortController().signal;try{V?.("Starting file read...");let Q=w0(),U=P$();try{if(!await Q.exists(J))throw Error("File not found")}catch(j){return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:`File not found: ${J}`}}}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(B)await y$.getInstance().recordFileRead(J,B);let q=await Q.stat(J);if(q?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${J}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let H=_4(J).toLowerCase(),G=N7(H),O=D7(H),F,z={file_path:J,file_size:q?.size,file_type:H,last_modified:q?.mtime instanceof Date?q.mtime.toISOString():void 0,encoding:Y,acp_mode:U};if(O&&Y==="utf8"){if(U)V?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),z.acp_fallback=!0;else V?.("检测到二进制文件,使用 base64 编码...");F=(await Q.readBinaryFile(J)).toString("base64"),z.encoding="base64",z.is_binary=!0}else if(G){if(U)V?.("通过 IDE 读取文件...");F=await Q.readTextFile(J)}else{if(U)z.acp_fallback=!0;let j=await Q.readBinaryFile(J);if(Y==="base64")F=j.toString("base64");else if(Y==="binary")F=j.toString("binary");else F=j.toString("utf8")}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if((W!==void 0||X!==void 0)&&Y==="utf8"&&G){let j=F.split(`
581
- `),b=W||0,a=X!==void 0?b+X:j.length,v=j.slice(b,a);F=v.map((J$,v0)=>{let h8=b+v0+1,K$=J$.length>2000?`${J$.substring(0,2000)}...`:J$;return`${h8.toString().padStart(6)}|${K$}`}).join(`
582
- `),z.lines_read=v.length,z.total_lines=j.length,z.start_line=b+1,z.end_line=Math.min(a,j.length)}let w=w7(J),L=z.lines_read||z.total_lines,E=L?`读取 ${L} 行从 ${w}`:`读取 ${w}`;return z.summary=E,{success:!0,llmContent:F,metadata:z}}catch(Q){let U=Q;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 Z=_4($.file_path);return Z?`**/*${Z}`:"**/*"}});function N7($){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 D7($){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 L7}from"fs";import{basename as E7,dirname as _7,extname as A7}from"path";import{z as F5}from"zod";var O5=D({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:F5.object({file_path:y.filePath({description:"Absolute file path to write"}),content:F5.string().describe("Content to write"),encoding:y.encoding(),create_directories:F5.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($,Z){let{file_path:J,content:W,encoding:X,create_directories:Y}=$,{updateOutput:V,sessionId:B,messageId:K}=Z,Q=Z.signal??new AbortController().signal;try{V?.("开始写入文件...");let U=w0(),q=P$();if(Y){let j=_7(J);try{await U.mkdir(j,{recursive:!0,mode:493})}catch(b){if(b.code!=="EEXIST")throw b}}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let H=!1,G=null;try{if(H=await U.exists(J),H&&X==="utf8")try{G=await U.readTextFile(J)}catch(j){console.warn("[WriteTool] 读取旧文件内容失败:",j)}}catch{}if(H&&B){let j=y$.getInstance();if(!j.hasFileBeenRead(J,B))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 b=await j.checkExternalModification(J);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 writing.
580
+ `),Q=E4(Z,K);if(Q>0.5)V.push({text:K,lineNumber:B+1,similarity:Q})}return V.sort((B,K)=>K.similarity-B.similarity).slice(0,J)}function E4($,Z){let J=(H)=>H.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),W=J($),X=J(Z);if(W===X)return 1;let Y=W.length,V=X.length;if(Y===0)return V===0?1:0;if(V===0)return 0;let B=200,K=W.substring(0,B),Q=X.substring(0,B),U=z7(K,Q),q=Math.max(K.length,Q.length);return 1-U/q}function z7($,Z){let J=$.length,W=Z.length,X=Array(J+1).fill(null).map(()=>Array(W+1).fill(0));for(let Y=0;Y<=J;Y++)X[Y][0]=Y;for(let Y=0;Y<=W;Y++)X[0][Y]=Y;for(let Y=1;Y<=J;Y++)for(let V=1;V<=W;V++){let B=$[Y-1]===Z[V-1]?0:1;X[Y][V]=Math.min(X[Y-1][V]+1,X[Y][V-1]+1,X[Y-1][V-1]+B)}return X[J][W]}import{basename as w7,extname as _4}from"path";import{z as j7}from"zod";var G5=D({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:j7.object({file_path:y.filePath({description:"File path to read (must be absolute)"}),offset:y.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:y.lineLimit({description:"Number of lines to read (text files only)"}).optional(),encoding:y.encoding()}),description:{short:"Read files from the local filesystem",long:"Reads a file from the local filesystem. You can access any file directly by using this tool. Assume this tool is able to read all files on the machine. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.",usageNotes:["The file_path parameter must be an absolute path, not a relative path","By default, it reads up to 2000 lines starting from the beginning of the file","You can optionally specify a line offset and limit (especially handy for long files), but it's recommended to read the whole file by not providing these parameters","Any lines longer than 2000 characters will be truncated","Results are returned using cat -n format, with line numbers starting at 1","This tool allows reading images (eg PNG, JPG, etc). When reading an image file the contents are presented visually as this is a multimodal LLM.","This tool can read PDF files (.pdf). PDFs are processed page by page, extracting both text and visual content for analysis.","This tool can read Jupyter notebooks (.ipynb files) and returns all cells with their outputs, combining code, text, and visualizations.","This tool can only read files, not directories. To read a directory, use an ls command via the Bash tool.","You can call multiple tools in a single response. It is always better to speculatively read multiple potentially useful files in parallel.","You will regularly be asked to read screenshots. If the user provides a path to a screenshot, ALWAYS use this tool to view the file at the path. This tool will work with all temporary file paths.","If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents."],examples:[{description:"Read the entire file (recommended)",params:{file_path:"/path/to/file.ts"}},{description:"Read the first 100 lines",params:{file_path:"/path/to/file.txt",limit:100}},{description:"Read 100 lines starting at line 50 (large file)",params:{file_path:"/path/to/large-file.log",offset:50,limit:100}}],important:["file_path must be absolute","Prefer reading the entire file (omit offset and limit)","Use offset/limit only for very large files","Line numbers start at 1 (cat -n format)"]},async execute($,Z){let{file_path:J,offset:W,limit:X,encoding:Y="utf8"}=$,{updateOutput:V,sessionId:B}=Z,K=Z.signal??new AbortController().signal;try{V?.("Starting file read...");let Q=j0(),U=y$();try{if(!await Q.exists(J))throw Error("File not found")}catch(j){return{success:!1,llmContent:`File not found: ${J}`,error:{type:"execution_error",message:`File not found: ${J}`}}}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if(B)await x$.getInstance().recordFileRead(J,B);let q=await Q.stat(J);if(q?.isDirectory)return{success:!1,llmContent:`Cannot read a directory: ${J}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let H=_4(J).toLowerCase(),G=N7(H),O=D7(H),F,z={file_path:J,file_size:q?.size,file_type:H,last_modified:q?.mtime instanceof Date?q.mtime.toISOString():void 0,encoding:Y,acp_mode:U};if(O&&Y==="utf8"){if(U)V?.("[WARN] 二进制文件通过本地读取(ACP 不支持)..."),z.acp_fallback=!0;else V?.("检测到二进制文件,使用 base64 编码...");F=(await Q.readBinaryFile(J)).toString("base64"),z.encoding="base64",z.is_binary=!0}else if(G){if(U)V?.("通过 IDE 读取文件...");F=await Q.readTextFile(J)}else{if(U)z.acp_fallback=!0;let j=await Q.readBinaryFile(J);if(Y==="base64")F=j.toString("base64");else if(Y==="binary")F=j.toString("binary");else F=j.toString("utf8")}if(typeof K.throwIfAborted==="function")K.throwIfAborted();if((W!==void 0||X!==void 0)&&Y==="utf8"&&G){let j=F.split(`
581
+ `),b=W||0,a=X!==void 0?b+X:j.length,v=j.slice(b,a);F=v.map((J$,C0)=>{let h8=b+C0+1,K$=J$.length>2000?`${J$.substring(0,2000)}...`:J$;return`${h8.toString().padStart(6)}|${K$}`}).join(`
582
+ `),z.lines_read=v.length,z.total_lines=j.length,z.start_line=b+1,z.end_line=Math.min(a,j.length)}let w=w7(J),L=z.lines_read||z.total_lines,E=L?`读取 ${L} 行从 ${w}`:`读取 ${w}`;return z.summary=E,{success:!0,llmContent:F,metadata:z}}catch(Q){let U=Q;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 Z=_4($.file_path);return Z?`**/*${Z}`:"**/*"}});function N7($){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 D7($){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 L7}from"fs";import{basename as E7,dirname as _7,extname as A7}from"path";import{z as F5}from"zod";var O5=D({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:F5.object({file_path:y.filePath({description:"Absolute file path to write"}),content:F5.string().describe("Content to write"),encoding:y.encoding(),create_directories:F5.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($,Z){let{file_path:J,content:W,encoding:X,create_directories:Y}=$,{updateOutput:V,sessionId:B,messageId:K}=Z,Q=Z.signal??new AbortController().signal;try{V?.("开始写入文件...");let U=j0(),q=y$();if(Y){let j=_7(J);try{await U.mkdir(j,{recursive:!0,mode:493})}catch(b){if(b.code!=="EEXIST")throw b}}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let H=!1,G=null;try{if(H=await U.exists(J),H&&X==="utf8")try{G=await U.readTextFile(J)}catch(j){console.warn("[WriteTool] 读取旧文件内容失败:",j)}}catch{}if(H&&B){let j=x$.getInstance();if(!j.hasFileBeenRead(J,B))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 b=await j.checkExternalModification(J);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 writing.
583
583
 
584
- Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}let O=!1;if(H&&B&&K)try{let j=new P0({sessionId:B});await j.initialize(),await j.createSnapshot(J,K),O=!0}catch(j){console.warn("[WriteTool] 创建快照失败:",j)}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(X==="utf8"){if(q)V?.("通过 IDE 写入文件...");await U.writeTextFile(J,W)}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 j;if(X==="base64")j=Buffer.from(W,"base64");else if(X==="binary")j=Buffer.from(W,"binary");else j=Buffer.from(W,"utf8");await L7.writeFile(J,j)}if(B)await y$.getInstance().recordFileEdit(J,B,"write");if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let F=await U.stat(J),z=X==="utf8"?W.split(`
585
- `).length:0,w=E7(J),L=null;if(G&&X==="utf8"&&G!==W){if(G.length<1048576&&W.length<1048576)L=z4(G,W,4)}let E={file_path:J,content_size:W.length,file_size:F?.size,encoding:X,created_directories:Y,snapshot_created:O,session_id:B,message_id:K,last_modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0,has_diff:!!L,summary:X==="utf8"?`写入 ${z} 行到 ${w}`:`写入 ${F?.size?R7(F.size):"unknown"} 到 ${w}`,kind:"edit",oldContent:G||"",newContent:X==="utf8"?W:void 0};return{success:!0,llmContent:G?`Wrote ${J} (${W.length} chars, updated existing file)`:`Created ${J} (${W.length} chars, new file)`,metadata:E}}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 Z=A7($.file_path);return Z?`**/*${Z}`:"**/*"}});function R7($){let Z=["B","KB","MB","GB"],J=$,W=0;while(J>=1024&&W<Z.length-1)J/=1024,W++;return`${J.toFixed(1)}${Z[W]}`}import{z as y0}from"zod";var k4=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),k7=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),b7=y0.object({operation:y0.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:y0.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:y0.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:y0.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function A4($){let Z={...$};if(Array.isArray(Z.models))Z.models=Z.models.map((J)=>{let W={...J};if(typeof W.apiKey==="string"&&W.apiKey){let X=W.apiKey;W.apiKey=X.length>8?`${X.slice(0,4)}...${X.slice(-4)}`:"****"}return W});return Z}function R4($,Z){let J=Z.split("."),W=$;for(let X of J){if(W===null||W===void 0||typeof W!=="object")return;W=W[X]}return W}function T7($){let Z=["可配置项列表(白名单):",""];for(let J of k4){let W=$[J],X=W===void 0?"(未设置)":JSON.stringify(W,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
586
- `)}var z5=D({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:b7,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($,Z){let{operation:J,key:W,value:X,scope:Y}=$,V=t();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(J){case"get":{if(!W)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(W==="*"){let U=A4(V);return{success:!0,llmContent:JSON.stringify(U,null,2),metadata:{summary:"获取全部配置"}}}let B=V;if(W.split(".")[0]==="models"){let U=A4(B),q=R4(U,W);return{success:!0,llmContent:JSON.stringify(q,null,2),metadata:{summary:`获取配置: ${W}`}}}let Q=R4(B,W);if(Q===void 0)return{success:!0,llmContent:`Config key "${W}" is not set or does not exist.`,metadata:{summary:`配置项 ${W} 不存在`}};return{success:!0,llmContent:JSON.stringify(Q,null,2),metadata:{summary:`获取配置: ${W}`}}}case"set":{if(!W)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(X===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let B=W.split(".")[0];if(B==="models"||B==="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(k7.has(B))return{success:!1,llmContent:`Refused: "${B}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${B}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${B}`}};if(!k4.has(B))return{success:!1,llmContent:`Key "${B}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${B}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${B}`}};let K;if(W.includes(".")){let Q=W.split(".");if(K={[Q[0]]:X},Q.length===2){let U=V[Q[0]];if(typeof U==="object"&&U!==null)K={[Q[0]]:{...U,[Q[1]]:X}};else K={[Q[0]]:{[Q[1]]:X}}}}else K={[W]:X};try{await x$().updateConfig(K,Y?{scope:Y}:{});let Q=JSON.stringify(X).length>200?`${JSON.stringify(X).slice(0,197)}...`:JSON.stringify(X);return{success:!0,llmContent:`Config updated: ${W} = ${Q}`+(Y?` (scope: ${Y})`:""),metadata:{summary:`配置已更新: ${W}`}}}catch(Q){let U=Q instanceof Error?Q.message:String(Q);return{success:!1,llmContent:`Failed to update config: ${U}`,error:{message:U,type:"execution_error"},metadata:{summary:`配置更新失败: ${W}`}}}}case"list":return{success:!0,llmContent:T7(V),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${J}`,error:{message:`Unknown operation: ${J}`,type:"validation_error"},metadata:{summary:`未知操作: ${J}`}}}}});import{z as b4}from"zod";var w5=D({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:b4.object({topic:b4.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($,Z){let{topic:J}=$,W=Z.workspaceRoot||N(),X=new T$(W);if(J==="_list"){let V=await X.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:
584
+ Details: ${b.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:b.message}}}}let O=!1;if(H&&B&&K)try{let j=new y0({sessionId:B});await j.initialize(),await j.createSnapshot(J,K),O=!0}catch(j){console.warn("[WriteTool] 创建快照失败:",j)}if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();if(X==="utf8"){if(q)V?.("通过 IDE 写入文件...");await U.writeTextFile(J,W)}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 j;if(X==="base64")j=Buffer.from(W,"base64");else if(X==="binary")j=Buffer.from(W,"binary");else j=Buffer.from(W,"utf8");await L7.writeFile(J,j)}if(B)await x$.getInstance().recordFileEdit(J,B,"write");if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let F=await U.stat(J),z=X==="utf8"?W.split(`
585
+ `).length:0,w=E7(J),L=null;if(G&&X==="utf8"&&G!==W){if(G.length<1048576&&W.length<1048576)L=z4(G,W,4)}let E={file_path:J,content_size:W.length,file_size:F?.size,encoding:X,created_directories:Y,snapshot_created:O,session_id:B,message_id:K,last_modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0,has_diff:!!L,summary:X==="utf8"?`写入 ${z} 行到 ${w}`:`写入 ${F?.size?R7(F.size):"unknown"} 到 ${w}`,kind:"edit",oldContent:G||"",newContent:X==="utf8"?W:void 0};return{success:!0,llmContent:G?`Wrote ${J} (${W.length} chars, updated existing file)`:`Created ${J} (${W.length} chars, new file)`,metadata:E}}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 Z=A7($.file_path);return Z?`**/*${Z}`:"**/*"}});function R7($){let Z=["B","KB","MB","GB"],J=$,W=0;while(J>=1024&&W<Z.length-1)J/=1024,W++;return`${J.toFixed(1)}${Z[W]}`}import{z as x0}from"zod";var k4=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),k7=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),b7=x0.object({operation:x0.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:x0.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:x0.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:x0.enum(["local","project","global"]).optional().describe("持久化范围: local(.blade/settings.local.json)"+"/ project(.blade/settings.json)"+"/ global(~/.blade/)")});function A4($){let Z={...$};if(Array.isArray(Z.models))Z.models=Z.models.map((J)=>{let W={...J};if(typeof W.apiKey==="string"&&W.apiKey){let X=W.apiKey;W.apiKey=X.length>8?`${X.slice(0,4)}...${X.slice(-4)}`:"****"}return W});return Z}function R4($,Z){let J=Z.split("."),W=$;for(let X of J){if(W===null||W===void 0||typeof W!=="object")return;W=W[X]}return W}function T7($){let Z=["可配置项列表(白名单):",""];for(let J of k4){let W=$[J],X=W===void 0?"(未设置)":JSON.stringify(W,null,2),Y=X.length>200?`${X.slice(0,197)}...`:X;Z.push(`- ${J}: ${Y}`)}return Z.join(`
586
+ `)}var z5=D({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:b7,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($,Z){let{operation:J,key:W,value:X,scope:Y}=$,V=t();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(J){case"get":{if(!W)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(W==="*"){let U=A4(V);return{success:!0,llmContent:JSON.stringify(U,null,2),metadata:{summary:"获取全部配置"}}}let B=V;if(W.split(".")[0]==="models"){let U=A4(B),q=R4(U,W);return{success:!0,llmContent:JSON.stringify(q,null,2),metadata:{summary:`获取配置: ${W}`}}}let Q=R4(B,W);if(Q===void 0)return{success:!0,llmContent:`Config key "${W}" is not set or does not exist.`,metadata:{summary:`配置项 ${W} 不存在`}};return{success:!0,llmContent:JSON.stringify(Q,null,2),metadata:{summary:`获取配置: ${W}`}}}case"set":{if(!W)return{success:!1,llmContent:'Missing "key" parameter for set operation.',error:{message:"Missing key",type:"validation_error"},metadata:{summary:"缺少 key 参数"}};if(X===void 0)return{success:!1,llmContent:'Missing "value" parameter for set operation.',error:{message:"Missing value",type:"validation_error"},metadata:{summary:"缺少 value 参数"}};let B=W.split(".")[0];if(B==="models"||B==="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(k7.has(B))return{success:!1,llmContent:`Refused: "${B}" is a runtime-only field and cannot be persisted via ConfigTool.`,error:{message:`Forbidden runtime key: ${B}`,type:"permission_denied"},metadata:{summary:`拒绝修改运行时字段: ${B}`}};if(!k4.has(B))return{success:!1,llmContent:`Key "${B}" is not in the settable whitelist. Use operation="list" to see all allowed keys.`,error:{message:`Key not settable: ${B}`,type:"validation_error"},metadata:{summary:`不可设置的 key: ${B}`}};let K;if(W.includes(".")){let Q=W.split(".");if(K={[Q[0]]:X},Q.length===2){let U=V[Q[0]];if(typeof U==="object"&&U!==null)K={[Q[0]]:{...U,[Q[1]]:X}};else K={[Q[0]]:{[Q[1]]:X}}}}else K={[W]:X};try{await f$().updateConfig(K,Y?{scope:Y}:{});let Q=JSON.stringify(X).length>200?`${JSON.stringify(X).slice(0,197)}...`:JSON.stringify(X);return{success:!0,llmContent:`Config updated: ${W} = ${Q}`+(Y?` (scope: ${Y})`:""),metadata:{summary:`配置已更新: ${W}`}}}catch(Q){let U=Q instanceof Error?Q.message:String(Q);return{success:!1,llmContent:`Failed to update config: ${U}`,error:{message:U,type:"execution_error"},metadata:{summary:`配置更新失败: ${W}`}}}}case"list":return{success:!0,llmContent:T7(V),metadata:{summary:"列举可配置项"}};default:return{success:!1,llmContent:`Unknown operation: ${J}`,error:{message:`Unknown operation: ${J}`,type:"validation_error"},metadata:{summary:`未知操作: ${J}`}}}}});import{z as b4}from"zod";var w5=D({name:"MemoryRead",displayName:"Memory Read",kind:"readonly",isConcurrencySafe:!0,schema:b4.object({topic:b4.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($,Z){let{topic:J}=$,W=Z.workspaceRoot||N(),X=new M$(W);if(J==="_list"){let V=await X.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:
587
587
  ${V.map((Q)=>`- ${Q.name}.md (${Q.size} bytes, updated ${Q.lastModified.toISOString()})`).join(`
588
- `)}`,metadata:{summary:`列出 ${V.length} 个记忆文件`}}}let Y=await X.readTopic(J);if(Y===null)return{success:!0,llmContent:`Memory topic "${J}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${J}`}};return{success:!0,llmContent:Y,metadata:{summary:`读取记忆: ${J}`}}}});import{z as F1}from"zod";var M7=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],j5=D({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($,Z){let{topic:J,content:W,mode:X}=$,Y=Z.workspaceRoot||N();for(let Q of M7)if(Q.test(W)){let U=`Refused: content appears to contain sensitive data (matched ${Q}). 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 T$(Y);if(J==="MEMORY")await V.updateIndex(W,X);else await V.writeTopic(J,W,X);return{success:!0,llmContent:`${X==="overwrite"?"Written":"Appended"} to memory/${J}.md (${W.length} chars)`,metadata:{summary:`写入记忆: ${J}`}}}});import*as O1 from"fs/promises";import{z as j0}from"zod";var N5=D({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:j0.object({notebook_path:j0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:j0.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:j0.string().describe("The new source for the cell"),cell_type:j0.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:j0.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($,Z){let{notebook_path:J,cell_id:W,new_source:X,cell_type:Y,edit_mode:V="replace"}=$;try{let B=await O1.readFile(J,"utf-8"),K=JSON.parse(B);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 Q=-1;if(W){if(Q=K.cells.findIndex((q)=>q.id===W),Q===-1&&V!=="insert")return{success:!1,llmContent:`Cell with ID "${W}" not found`,error:{type:"validation_error",message:`Cell ID "${W}" not found`},metadata:{summary:`Cell 未找到: ${W}`}}}switch(V){case"replace":{if(Q===-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[Q];if(q.source=X.split(`
588
+ `)}`,metadata:{summary:`列出 ${V.length} 个记忆文件`}}}let Y=await X.readTopic(J);if(Y===null)return{success:!0,llmContent:`Memory topic "${J}" not found. Use topic="_list" to see available topics.`,metadata:{summary:`记忆主题未找到: ${J}`}};return{success:!0,llmContent:Y,metadata:{summary:`读取记忆: ${J}`}}}});import{z as F1}from"zod";var M7=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],j5=D({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($,Z){let{topic:J,content:W,mode:X}=$,Y=Z.workspaceRoot||N();for(let Q of M7)if(Q.test(W)){let U=`Refused: content appears to contain sensitive data (matched ${Q}). 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 M$(Y);if(J==="MEMORY")await V.updateIndex(W,X);else await V.writeTopic(J,W,X);return{success:!0,llmContent:`${X==="overwrite"?"Written":"Appended"} to memory/${J}.md (${W.length} chars)`,metadata:{summary:`写入记忆: ${J}`}}}});import*as O1 from"fs/promises";import{z as N0}from"zod";var N5=D({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:N0.object({notebook_path:N0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:N0.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:N0.string().describe("The new source for the cell"),cell_type:N0.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:N0.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($,Z){let{notebook_path:J,cell_id:W,new_source:X,cell_type:Y,edit_mode:V="replace"}=$;try{let B=await O1.readFile(J,"utf-8"),K=JSON.parse(B);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 Q=-1;if(W){if(Q=K.cells.findIndex((q)=>q.id===W),Q===-1&&V!=="insert")return{success:!1,llmContent:`Cell with ID "${W}" not found`,error:{type:"validation_error",message:`Cell ID "${W}" not found`},metadata:{summary:`Cell 未找到: ${W}`}}}switch(V){case"replace":{if(Q===-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[Q];if(q.source=X.split(`
589
589
  `).map((H,G,O)=>G<O.length-1?H+`
590
590
  `:H),Y)q.cell_type=Y;break}case"insert":{if(!Y)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:Y,source:X.split(`
591
591
  `).map((G,O,F)=>O<F.length-1?G+`
@@ -714,16 +714,16 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
714
714
  `+(W.feedback||"No specific feedback provided.")+`
715
715
 
716
716
  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:W.feedback,awaitingUserInput:!0,summary:"方案被拒绝,等待用户反馈"}}}catch(W){return{success:!1,llmContent:`Confirmation flow error: ${W instanceof Error?W.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.
717
- Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import u7 from"fast-glob";import{stat as g7}from"node:fs/promises";import{join as m7,resolve as c7}from"path";import{z as w1}from"zod";import{existsSync as I7,readFileSync as S7}from"node:fs";import{readFile as P7}from"node:fs/promises";import{dirname as y7,join as C4}from"node:path";import x7 from"fast-glob";import{LRUCache as f7}from"lru-cache";import x0 from"picomatch";var W0=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],h7=["*.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 p7($){if(!I7($))return{patterns:[],negatePatterns:[]};try{let Z=S7($,"utf-8"),J=[],W=[];for(let X of Z.split(`
718
- `)){let Y=X.trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("!"))W.push(Y.slice(1));else J.push(Y)}return{patterns:J,negatePatterns:W}}catch(Z){return console.warn(`Failed to read .gitignore: ${Z}`),{patterns:[],negatePatterns:[]}}}var v4=new f7({max:100,ttl:30000,updateAgeOnGet:!0});async function d7($,Z){let J=[...W0.map((K)=>`${K}/**`),...Z?.scanIgnore??[]],W=`${$}|${J.join(",")}`,X=v4.get(W);if(X)return X;let Y=await x7("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:J});Y.sort((K,Q)=>I0(K).length-I0(Q).length);let V=[];for(let K of Y){let Q=y7(K).replace(/\\/g,"/"),U=Q==="."?"":Q,H=(await P7(C4($,K),"utf-8")).split(`
719
- `);for(let G of H){let O=G.trim();if(!O||O.startsWith("#"))continue;let F=O.startsWith("!"),w=(F?O.slice(1):O).trim();if(!w)continue;let L="";if(w.startsWith("/")){let E=w.slice(1).replace(/\\/g,"/");if(L=(U?U+"/":"")+E,V.push({type:F?"negate":"ignore",pattern:L}),w.endsWith("/")){let j=L+"**";V.push({type:F?"negate":"ignore",pattern:j});let b=L.replace(/\/$/,"");if(b!==L)V.push({type:F?"negate":"ignore",pattern:b})}}else{let E=w.replace(/\\/g,"/");if(E.includes("/")){if(L=(U?U+"/":"")+E,V.push({type:F?"negate":"ignore",pattern:L}),E.endsWith("/")){let j=L+"**";V.push({type:F?"negate":"ignore",pattern:j});let b=L.replace(/\/$/,"");if(b!==L)V.push({type:F?"negate":"ignore",pattern:b})}}else L=(U?U+"/**/":"**/")+E,V.push({type:F?"negate":"ignore",pattern:L})}}}let B=Z?.cacheTTL??30000;return v4.set(W,V,{ttl:B}),V}class z1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new z1({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:W=!0,gitignoreScanMode:X="root",customScanIgnore:Y=[],cacheTTL:V}=$;if(W&&X==="recursive"){let B=await d7(J,{scanIgnore:Y,cacheTTL:V});for(let K of B)if(Z.orderedRules.push({type:K.type,matcher:x0(K.pattern,{dot:!0})}),K.type==="ignore")Z.ignorePatterns.push(K.pattern);else Z.negatePatterns.push(K.pattern)}return Z}initialize($){let{cwd:Z=N(),useGitignore:J=!0,useDefaults:W=!0,customPatterns:X=[]}=$,Y=[],V=[];if(W){let B=[...W0.map((K)=>`${K}/**`),...W0,...h7];Y.push(...B);for(let K of B)this.orderedRules.push({type:"ignore",matcher:x0(K,{dot:!0})})}if(J){let B=C4(Z,".gitignore"),{patterns:K,negatePatterns:Q}=p7(B);for(let U of K)this.orderedRules.push({type:"ignore",matcher:x0(U,{dot:!0})}),Y.push(U);for(let U of Q)this.orderedRules.push({type:"negate",matcher:x0(U,{dot:!0})}),V.push(U)}Y.push(...X);for(let B of X)this.orderedRules.push({type:"ignore",matcher:x0(B,{dot:!0})});this.ignorePatterns=Y,this.negatePatterns=V}shouldIgnore($){let Z=$.replace(/\\/g,"/"),J=void 0;for(let W of this.orderedRules)if(W.matcher(Z))J=W.type==="ignore";return J===!0}shouldIgnoreDirectory($){let Z=$.replace(/\\/g,"/");return this.shouldIgnore(Z)||this.shouldIgnore(`${Z}/`)}filter($){return $.filter((Z)=>!this.shouldIgnore(Z))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function _5($){let Z=Error($);return Z.name="AbortError",Z}var A5=D({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:w1.object({pattern:y.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:w1.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:y.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:w1.boolean().default(!1).describe("Include directories in results"),case_sensitive:w1.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($,Z){let{pattern:J,path:W=N(),max_results:X,include_directories:Y,case_sensitive:V}=$,{updateOutput:B}=Z,K=Z.signal??new AbortController().signal;try{B?.(`Searching in ${W} for pattern "${J}"...`);let Q=c7(W);try{if(!(await g7(Q)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${Q}`,metadata:{summary:"搜索失败: 搜索路径必须是目录"},error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(z){if(z.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${Q}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw z}K.throwIfAborted();let U=await z1.create({cwd:Q,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:q,wasTruncated:H}=await l7(Q,J,{maxResults:X,includeDirectories:Y,caseSensitive:V,signal:K},U),G=i7(q),O={search_path:Q,pattern:J,total_matches:q.length,returned_matches:q.length,max_results:X,include_directories:Y,case_sensitive:V,truncated:H},F;if(G.length>0)F=`${H?`Found at least ${G.length} file(s) matching "${J}" (truncated)`:`Found ${G.length} file(s) matching "${J}"`}:
717
+ Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import u7 from"fast-glob";import{stat as g7}from"node:fs/promises";import{join as m7,resolve as c7}from"path";import{z as w1}from"zod";import{existsSync as I7,readFileSync as S7}from"node:fs";import{readFile as P7}from"node:fs/promises";import{dirname as y7,join as C4}from"node:path";import x7 from"fast-glob";import{LRUCache as f7}from"lru-cache";import f0 from"picomatch";var X0=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],h7=["*.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 p7($){if(!I7($))return{patterns:[],negatePatterns:[]};try{let Z=S7($,"utf-8"),J=[],W=[];for(let X of Z.split(`
718
+ `)){let Y=X.trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("!"))W.push(Y.slice(1));else J.push(Y)}return{patterns:J,negatePatterns:W}}catch(Z){return console.warn(`Failed to read .gitignore: ${Z}`),{patterns:[],negatePatterns:[]}}}var v4=new f7({max:100,ttl:30000,updateAgeOnGet:!0});async function d7($,Z){let J=[...X0.map((K)=>`${K}/**`),...Z?.scanIgnore??[]],W=`${$}|${J.join(",")}`,X=v4.get(W);if(X)return X;let Y=await x7("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:J});Y.sort((K,Q)=>S0(K).length-S0(Q).length);let V=[];for(let K of Y){let Q=y7(K).replace(/\\/g,"/"),U=Q==="."?"":Q,H=(await P7(C4($,K),"utf-8")).split(`
719
+ `);for(let G of H){let O=G.trim();if(!O||O.startsWith("#"))continue;let F=O.startsWith("!"),w=(F?O.slice(1):O).trim();if(!w)continue;let L="";if(w.startsWith("/")){let E=w.slice(1).replace(/\\/g,"/");if(L=(U?U+"/":"")+E,V.push({type:F?"negate":"ignore",pattern:L}),w.endsWith("/")){let j=L+"**";V.push({type:F?"negate":"ignore",pattern:j});let b=L.replace(/\/$/,"");if(b!==L)V.push({type:F?"negate":"ignore",pattern:b})}}else{let E=w.replace(/\\/g,"/");if(E.includes("/")){if(L=(U?U+"/":"")+E,V.push({type:F?"negate":"ignore",pattern:L}),E.endsWith("/")){let j=L+"**";V.push({type:F?"negate":"ignore",pattern:j});let b=L.replace(/\/$/,"");if(b!==L)V.push({type:F?"negate":"ignore",pattern:b})}}else L=(U?U+"/**/":"**/")+E,V.push({type:F?"negate":"ignore",pattern:L})}}}let B=Z?.cacheTTL??30000;return v4.set(W,V,{ttl:B}),V}class z1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new z1({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:W=!0,gitignoreScanMode:X="root",customScanIgnore:Y=[],cacheTTL:V}=$;if(W&&X==="recursive"){let B=await d7(J,{scanIgnore:Y,cacheTTL:V});for(let K of B)if(Z.orderedRules.push({type:K.type,matcher:f0(K.pattern,{dot:!0})}),K.type==="ignore")Z.ignorePatterns.push(K.pattern);else Z.negatePatterns.push(K.pattern)}return Z}initialize($){let{cwd:Z=N(),useGitignore:J=!0,useDefaults:W=!0,customPatterns:X=[]}=$,Y=[],V=[];if(W){let B=[...X0.map((K)=>`${K}/**`),...X0,...h7];Y.push(...B);for(let K of B)this.orderedRules.push({type:"ignore",matcher:f0(K,{dot:!0})})}if(J){let B=C4(Z,".gitignore"),{patterns:K,negatePatterns:Q}=p7(B);for(let U of K)this.orderedRules.push({type:"ignore",matcher:f0(U,{dot:!0})}),Y.push(U);for(let U of Q)this.orderedRules.push({type:"negate",matcher:f0(U,{dot:!0})}),V.push(U)}Y.push(...X);for(let B of X)this.orderedRules.push({type:"ignore",matcher:f0(B,{dot:!0})});this.ignorePatterns=Y,this.negatePatterns=V}shouldIgnore($){let Z=$.replace(/\\/g,"/"),J=void 0;for(let W of this.orderedRules)if(W.matcher(Z))J=W.type==="ignore";return J===!0}shouldIgnoreDirectory($){let Z=$.replace(/\\/g,"/");return this.shouldIgnore(Z)||this.shouldIgnore(`${Z}/`)}filter($){return $.filter((Z)=>!this.shouldIgnore(Z))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function _5($){let Z=Error($);return Z.name="AbortError",Z}var A5=D({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:w1.object({pattern:y.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:w1.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:y.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:w1.boolean().default(!1).describe("Include directories in results"),case_sensitive:w1.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($,Z){let{pattern:J,path:W=N(),max_results:X,include_directories:Y,case_sensitive:V}=$,{updateOutput:B}=Z,K=Z.signal??new AbortController().signal;try{B?.(`Searching in ${W} for pattern "${J}"...`);let Q=c7(W);try{if(!(await g7(Q)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${Q}`,metadata:{summary:"搜索失败: 搜索路径必须是目录"},error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(z){if(z.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${Q}`,metadata:{summary:"搜索失败: 搜索路径不存在"},error:{type:"execution_error",message:"搜索路径不存在"}};throw z}K.throwIfAborted();let U=await z1.create({cwd:Q,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:q,wasTruncated:H}=await l7(Q,J,{maxResults:X,includeDirectories:Y,caseSensitive:V,signal:K},U),G=i7(q),O={search_path:Q,pattern:J,total_matches:q.length,returned_matches:q.length,max_results:X,include_directories:Y,case_sensitive:V,truncated:H},F;if(G.length>0)F=`${H?`Found at least ${G.length} file(s) matching "${J}" (truncated)`:`Found ${G.length} file(s) matching "${J}"`}:
720
720
 
721
721
  `+G.map((w)=>`- ${w.relative_path}`).join(`
722
722
  `)+`
723
723
 
724
- Use the relative_path values above for Read/Edit operations.`;else F=`No files found matching "${J}"`;return{success:!0,llmContent:F,metadata:{...O,matches:G,summary:`找到 ${q.length} 个匹配 "${J}" 的文件`}}}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 l7($,Z,J,W){let X=W.getIgnorePatterns(),Y=[],V=!1;return await new Promise((B,K)=>{if(J.signal.aborted){K(_5("文件搜索被用户中止"));return}let Q=u7.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:J.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!J.includeDirectories,ignore:X}),U=!1,q=null,H=()=>{if(q){if(J.signal.removeEventListener)J.signal.removeEventListener("abort",q);else if("onabort"in J.signal)J.signal.onabort=null;q=null}},G=()=>{if(!U)U=!0,V=!0,Q.destroy(),H(),B({matches:Y,wasTruncated:V})},O=(F)=>{if(J.signal.aborted){if(!U)U=!0,Q.destroy(_5("文件搜索被用户中止"));return}if(Y.length>=J.maxResults){G();return}let z=F.path.replace(/\\/g,"/"),w=m7($,z);if(W.shouldIgnore(z))return;let L=F.stats?F.stats.isDirectory():!1;if(L&&W.shouldIgnoreDirectory(z))return;let E=F.stats&&F.stats.isFile()?F.stats.size:void 0,j=F.stats?F.stats.mtime.toISOString():void 0;if(Y.push({path:w,relative_path:z,is_directory:L,size:E,modified:j}),Y.length>=J.maxResults)G()};if(Q.on("data",O),q=()=>{if(!U)U=!0,H(),Q.destroy(_5("文件搜索被用户中止"))},J.signal.addEventListener)J.signal.addEventListener("abort",q);else if("onabort"in J.signal)J.signal.onabort=q;Q.once("error",(F)=>{if(!U)U=!0,H(),K(F)}),Q.once("end",()=>{if(!U)U=!0,H(),B({matches:Y,wasTruncated:V})})})}function i7($){return $.sort((Z,J)=>{if(Z.is_directory!==J.is_directory)return Z.is_directory?1:-1;if(Z.modified&&J.modified)return new Date(J.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(J.relative_path)})}import{execSync as k5,spawn as b5}from"child_process";import{existsSync as R5}from"fs";import{readdir as a7,readFile as n7}from"fs/promises";import{join as r7,relative as s7}from"path";import o7 from"picomatch";import{z as f$}from"zod";function t7(){let{platform:$,arch:Z}=process,J={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},W=`${$}-${Z}`,X=J[W];if(!X)return null;try{let Y=new URL("../../../../vendor/ripgrep/"+X,import.meta.url).pathname;if(R5(Y))return Y}catch{}return null}function I4(){try{let Z=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",J=k5(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(J)return J}catch{}let $=t7();if($&&R5($))return $;try{let Z=s$("@vscode/ripgrep");if(Z?.rgPath&&R5(Z.rgPath))return Z.rgPath}catch{}return null}async function e7($){try{return k5("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function $6(){try{return k5("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function Z6($,Z,J,W){let X=I4();if(!X)throw Error("ripgrep not available");return new Promise((Y,V)=>{let B=b5(X,$,{stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};J.addEventListener("abort",U),B.on("close",()=>{J.removeEventListener("abort",U)})})}async function J6($,Z,J,W){let X=["grep","-n"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);if(X.push("-e",$),J.glob)X.push("--",J.glob);return new Promise((Y,V)=>{let B=b5("git",X,{cwd:Z,stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};W.addEventListener("abort",U),B.on("close",()=>{W.removeEventListener("abort",U)})})}async function W6($,Z,J,W){let X=["-rn"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);for(let Y of W0)X.push("--exclude-dir="+Y.replace(/^\./,""));return X.push("-e",$,Z),new Promise((Y,V)=>{let B=b5("grep",X,{stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};W.addEventListener("abort",U),B.on("close",()=>{W.removeEventListener("abort",U)})})}async function X6($,Z,J,W){let X=[],Y=new RegExp($,J.caseInsensitive?"gi":"g"),V=await Y6(Z,W),B=0;for(let K of V){if(W.throwIfAborted(),S4(K))continue;if(J.glob&&!V6(K,J.glob))continue;try{(await n7(K,"utf-8")).split(`
725
- `).forEach((q,H)=>{if(Y.test(q))X.push({file_path:s7(Z,K),line_number:H+1,content:q})}),B++}catch(Q){continue}}return{matches:X,totalFiles:B}}async function Y6($,Z){let J=[];async function W(X){Z.throwIfAborted();try{let Y=await a7(X,{withFileTypes:!0});for(let V of Y){Z.throwIfAborted();let B=r7(X,V.name);if(V.isDirectory()){if(!S4(B))await W(B)}else if(V.isFile())J.push(B)}}catch(Y){}}return await W($),J}function S4($){for(let Z of W0)if($.includes(Z))return!0;return!1}function V6($,Z){return o7(Z)($)}function B6($){let Z=[];if($.case_insensitive)Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Z.push("-l");break;case"count":Z.push("-c");break;case"content":if($.line_numbers)Z.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Z.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Z.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Z.push("-A",$.context_after.toString())}if($.type)Z.push("--type",$.type);for(let J of W0)Z.push("--glob",`!${J}/**`);if($.glob)Z.push("--glob",$.glob);if($.head_limit!==void 0){let J=($.offset??0)+$.head_limit;Z.push("-m",J.toString())}return Z.push($.pattern),Z.push($.path),Z}function K6($,Z){if(!$.trim())return[];let J=$.trim().split(`
726
- `),W=[];switch(Z){case"files_with_matches":return J.map((X)=>({file_path:X.trim()}));case"count":return J.map((X)=>{let[Y,V]=X.split(":");return{file_path:Y,count:parseInt(V,10)}});case"content":for(let X of J){let Y=Q6(X);if(Y)W.push(Y)}return W;default:return[]}}function Q6($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),W=$.substring(Z+1),X=W.indexOf(":");if(X!==-1&&/^\d+$/.test(W.substring(0,X))){let Y=parseInt(W.substring(0,X),10),V=W.substring(X+1);return{file_path:J,line_number:Y,content:V}}else return{file_path:J,content:W}}var T5=D({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:f$.object({pattern:y.pattern({description:"The regular expression pattern to search for in file contents"}),path:f$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:f$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:f$.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:f$.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":f$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":f$.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":y.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":y.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":y.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:y.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:y.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:f$.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($,Z){let{pattern:J,path:W=N(),glob:X,type:Y,output_mode:V,"-i":B,"-n":K=!0,"-B":Q,"-A":U,"-C":q,head_limit:H,offset:G,multiline:O}=$,{updateOutput:F}=Z,z=Z.signal??new AbortController().signal;try{F?.(`使用智能搜索策略查找模式 "${J}"...`);let w=null,L="ripgrep",E=[],j=I4();if(j)try{F?.(`使用 ripgrep (${j})`);let v=B6({pattern:J,path:W,glob:X,type:Y,output_mode:V,case_insensitive:B??!1,line_numbers:K,context_before:Q,context_after:U,context:q,head_limit:H,offset:G,multiline:O??!1});w=await Z6(v,V,z,F),L="ripgrep"}catch{F?.("[WARN] ripgrep 失败,尝试降级策略..."),w=null}if(!w&&await e7(W))try{F?.("使用 git grep"),w=await J6(J,W,{caseInsensitive:B??!1,glob:X,contextLines:q},z),L="git-grep"}catch{F?.("[WARN] git grep 失败,继续尝试其他策略..."),w=null}if(!w&&$6())try{F?.("使用系统 grep"),w=await W6(J,W,{caseInsensitive:B??!1,contextLines:q},z),L="system-grep"}catch{F?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),w=null}if(!w)F?.("使用纯 JavaScript 搜索实现"),E=(await X6(J,W,{caseInsensitive:B??!1,glob:X,multiline:O??!1},z)).matches,L="fallback",w={stdout:"",stderr:"",exitCode:0};else E=K6(w.stdout,V);let b=E.length;if(G!==void 0&&G>0)E=E.slice(G);if(H!==void 0&&E.length>H)E=E.slice(0,H);let a={search_pattern:J,search_path:W,output_mode:V,case_insensitive:B??!1,total_matches:E.length,original_total:b,offset:G,head_limit:H,strategy:L,exit_code:w?.exitCode};if(w&&w.exitCode!==0&&w.stderr)return{success:!1,llmContent:`Search execution failed: ${w.stderr}`,metadata:{...a,summary:`搜索失败: ${w.stderr}`},error:{type:"execution_error",message:w.stderr}};return{success:!0,llmContent:E,metadata:{...a,summary:E.length>0?`搜索 "${J}" 找到 ${E.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(w){let L=w;if(L.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${L.message}`,metadata:{summary:`搜索失败: ${L.message}`},error:{type:"execution_error",message:L.message,details:L}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{spawn as O6}from"child_process";import{randomUUID as z6}from"crypto";import{z as M5}from"zod";var U6=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"]),q6=/^(LD_.+|DYLD_.+|PATH)$/,P4=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function X0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],X=J[2],Y=W.match(P4);if(!Y)break;let V=Y[1];if(!U6.has(V))break;Z=X}return Z}function y4($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],X=J[2],Y=W.match(P4);if(!Y)break;let V=Y[1];if(q6.test(V))break;Z=X}return Z}var H6=[/^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 h$($){let Z=$,J=!0;while(J){J=!1;for(let W of H6){let X=Z.match(W);if(X){Z=Z.slice(X[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function x4($){let Z=[],J="",W=!1,X=!1,Y=!1;for(let V=0;V<$.length;V++){let B=$[V];if(Y){J+=B,Y=!1;continue}if(B==="\\"&&!W){J+=B,Y=!0;continue}if(B==="'"&&!X){W=!W,J+=B;continue}if(B==='"'&&!W){X=!X,J+=B;continue}if(W||X){J+=B;continue}if(B==="|"){if(V+1<$.length&&$[V+1]==="|"){if(J.trim())Z.push(J.trim());J="",V++;continue}return null}if(B===">"||B==="<")return null;if(B==="&"&&V+1<$.length&&$[V+1]==="&"){if(J.trim())Z.push(J.trim());J="",V++;continue}if(B==="&")return null;if(B===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=B}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function f4($){let Z=[],J="",W=!1,X=!1,Y=!1;for(let V=0;V<$.length;V++){let B=$[V];if(Y){J+=B,Y=!1;continue}if(B==="\\"&&!W){if(Y=!0,X){let K=$[V+1];if(K&&'$`"\\'.includes(K))continue;J+=B,Y=!1}continue}if(B==="'"&&!X){W=!W;continue}if(B==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(B)){if(J)Z.push(J),J="";continue}J+=B}if(J)Z.push(J);return Z}var j1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},Y0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},h4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},G6={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},F6=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:j1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:j1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:Y0,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:h4},{pattern:/^git\s+(status|branch|remote)/i,config:Y0},{pattern:/^git\s+(log|diff|show)/i,config:h4},{pattern:/^(ls|dir|tree)\s+/i,config:Y0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:Y0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:Y0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:j1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:j1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:Y0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:Y0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class f0{static getConfigForCommand($){for(let{pattern:Z,config:J,summaryTemplate:W}of F6)if(Z.test($))return{config:J,summaryTemplate:W};return{config:G6}}static truncate($,Z){let{config:J,summaryTemplate:W}=this.getConfigForCommand(Z);return this.truncateWithConfig($,J,W)}static truncateWithConfig($,Z,J){let W=$.length,X=$.split(`
724
+ Use the relative_path values above for Read/Edit operations.`;else F=`No files found matching "${J}"`;return{success:!0,llmContent:F,metadata:{...O,matches:G,summary:`找到 ${q.length} 个匹配 "${J}" 的文件`}}}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 l7($,Z,J,W){let X=W.getIgnorePatterns(),Y=[],V=!1;return await new Promise((B,K)=>{if(J.signal.aborted){K(_5("文件搜索被用户中止"));return}let Q=u7.stream(Z,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:J.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!J.includeDirectories,ignore:X}),U=!1,q=null,H=()=>{if(q){if(J.signal.removeEventListener)J.signal.removeEventListener("abort",q);else if("onabort"in J.signal)J.signal.onabort=null;q=null}},G=()=>{if(!U)U=!0,V=!0,Q.destroy(),H(),B({matches:Y,wasTruncated:V})},O=(F)=>{if(J.signal.aborted){if(!U)U=!0,Q.destroy(_5("文件搜索被用户中止"));return}if(Y.length>=J.maxResults){G();return}let z=F.path.replace(/\\/g,"/"),w=m7($,z);if(W.shouldIgnore(z))return;let L=F.stats?F.stats.isDirectory():!1;if(L&&W.shouldIgnoreDirectory(z))return;let E=F.stats&&F.stats.isFile()?F.stats.size:void 0,j=F.stats?F.stats.mtime.toISOString():void 0;if(Y.push({path:w,relative_path:z,is_directory:L,size:E,modified:j}),Y.length>=J.maxResults)G()};if(Q.on("data",O),q=()=>{if(!U)U=!0,H(),Q.destroy(_5("文件搜索被用户中止"))},J.signal.addEventListener)J.signal.addEventListener("abort",q);else if("onabort"in J.signal)J.signal.onabort=q;Q.once("error",(F)=>{if(!U)U=!0,H(),K(F)}),Q.once("end",()=>{if(!U)U=!0,H(),B({matches:Y,wasTruncated:V})})})}function i7($){return $.sort((Z,J)=>{if(Z.is_directory!==J.is_directory)return Z.is_directory?1:-1;if(Z.modified&&J.modified)return new Date(J.modified).getTime()-new Date(Z.modified).getTime();return Z.relative_path.localeCompare(J.relative_path)})}import{execSync as k5,spawn as b5}from"child_process";import{existsSync as R5}from"fs";import{readdir as a7,readFile as n7}from"fs/promises";import{join as r7,relative as s7}from"path";import o7 from"picomatch";import{z as h$}from"zod";function t7(){let{platform:$,arch:Z}=process,J={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},W=`${$}-${Z}`,X=J[W];if(!X)return null;try{let Y=new URL("../../../../vendor/ripgrep/"+X,import.meta.url).pathname;if(R5(Y))return Y}catch{}return null}function I4(){try{let Z=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",J=k5(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(J)return J}catch{}let $=t7();if($&&R5($))return $;try{let Z=o$("@vscode/ripgrep");if(Z?.rgPath&&R5(Z.rgPath))return Z.rgPath}catch{}return null}async function e7($){try{return k5("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function $6(){try{return k5("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function Z6($,Z,J,W){let X=I4();if(!X)throw Error("ripgrep not available");return new Promise((Y,V)=>{let B=b5(X,$,{stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};J.addEventListener("abort",U),B.on("close",()=>{J.removeEventListener("abort",U)})})}async function J6($,Z,J,W){let X=["grep","-n"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);if(X.push("-e",$),J.glob)X.push("--",J.glob);return new Promise((Y,V)=>{let B=b5("git",X,{cwd:Z,stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};W.addEventListener("abort",U),B.on("close",()=>{W.removeEventListener("abort",U)})})}async function W6($,Z,J,W){let X=["-rn"];if(J.caseInsensitive)X.push("-i");if(J.contextLines!==void 0)X.push(`-C${J.contextLines}`);for(let Y of X0)X.push("--exclude-dir="+Y.replace(/^\./,""));return X.push("-e",$,Z),new Promise((Y,V)=>{let B=b5("grep",X,{stdio:["pipe","pipe","pipe"]}),K="",Q="";B.stdout.on("data",(q)=>{K+=q.toString()}),B.stderr.on("data",(q)=>{Q+=q.toString()}),B.on("close",(q)=>{Y({stdout:K,stderr:Q,exitCode:q||0})}),B.on("error",(q)=>{V(q)});let U=()=>{B.kill("SIGTERM"),V(Error("搜索被用户中止"))};W.addEventListener("abort",U),B.on("close",()=>{W.removeEventListener("abort",U)})})}async function X6($,Z,J,W){let X=[],Y=new RegExp($,J.caseInsensitive?"gi":"g"),V=await Y6(Z,W),B=0;for(let K of V){if(W.throwIfAborted(),S4(K))continue;if(J.glob&&!V6(K,J.glob))continue;try{(await n7(K,"utf-8")).split(`
725
+ `).forEach((q,H)=>{if(Y.test(q))X.push({file_path:s7(Z,K),line_number:H+1,content:q})}),B++}catch(Q){continue}}return{matches:X,totalFiles:B}}async function Y6($,Z){let J=[];async function W(X){Z.throwIfAborted();try{let Y=await a7(X,{withFileTypes:!0});for(let V of Y){Z.throwIfAborted();let B=r7(X,V.name);if(V.isDirectory()){if(!S4(B))await W(B)}else if(V.isFile())J.push(B)}}catch(Y){}}return await W($),J}function S4($){for(let Z of X0)if($.includes(Z))return!0;return!1}function V6($,Z){return o7(Z)($)}function B6($){let Z=[];if($.case_insensitive)Z.push("-i");if($.multiline)Z.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Z.push("-l");break;case"count":Z.push("-c");break;case"content":if($.line_numbers)Z.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Z.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Z.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Z.push("-A",$.context_after.toString())}if($.type)Z.push("--type",$.type);for(let J of X0)Z.push("--glob",`!${J}/**`);if($.glob)Z.push("--glob",$.glob);if($.head_limit!==void 0){let J=($.offset??0)+$.head_limit;Z.push("-m",J.toString())}return Z.push($.pattern),Z.push($.path),Z}function K6($,Z){if(!$.trim())return[];let J=$.trim().split(`
726
+ `),W=[];switch(Z){case"files_with_matches":return J.map((X)=>({file_path:X.trim()}));case"count":return J.map((X)=>{let[Y,V]=X.split(":");return{file_path:Y,count:parseInt(V,10)}});case"content":for(let X of J){let Y=Q6(X);if(Y)W.push(Y)}return W;default:return[]}}function Q6($){let Z=$.indexOf(":");if(Z===-1)return null;let J=$.substring(0,Z),W=$.substring(Z+1),X=W.indexOf(":");if(X!==-1&&/^\d+$/.test(W.substring(0,X))){let Y=parseInt(W.substring(0,X),10),V=W.substring(X+1);return{file_path:J,line_number:Y,content:V}}else return{file_path:J,content:W}}var T5=D({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:h$.object({pattern:y.pattern({description:"The regular expression pattern to search for in file contents"}),path:h$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:h$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:h$.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:h$.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":h$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":h$.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":y.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":y.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":y.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:y.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:y.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:h$.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($,Z){let{pattern:J,path:W=N(),glob:X,type:Y,output_mode:V,"-i":B,"-n":K=!0,"-B":Q,"-A":U,"-C":q,head_limit:H,offset:G,multiline:O}=$,{updateOutput:F}=Z,z=Z.signal??new AbortController().signal;try{F?.(`使用智能搜索策略查找模式 "${J}"...`);let w=null,L="ripgrep",E=[],j=I4();if(j)try{F?.(`使用 ripgrep (${j})`);let v=B6({pattern:J,path:W,glob:X,type:Y,output_mode:V,case_insensitive:B??!1,line_numbers:K,context_before:Q,context_after:U,context:q,head_limit:H,offset:G,multiline:O??!1});w=await Z6(v,V,z,F),L="ripgrep"}catch{F?.("[WARN] ripgrep 失败,尝试降级策略..."),w=null}if(!w&&await e7(W))try{F?.("使用 git grep"),w=await J6(J,W,{caseInsensitive:B??!1,glob:X,contextLines:q},z),L="git-grep"}catch{F?.("[WARN] git grep 失败,继续尝试其他策略..."),w=null}if(!w&&$6())try{F?.("使用系统 grep"),w=await W6(J,W,{caseInsensitive:B??!1,contextLines:q},z),L="system-grep"}catch{F?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),w=null}if(!w)F?.("使用纯 JavaScript 搜索实现"),E=(await X6(J,W,{caseInsensitive:B??!1,glob:X,multiline:O??!1},z)).matches,L="fallback",w={stdout:"",stderr:"",exitCode:0};else E=K6(w.stdout,V);let b=E.length;if(G!==void 0&&G>0)E=E.slice(G);if(H!==void 0&&E.length>H)E=E.slice(0,H);let a={search_pattern:J,search_path:W,output_mode:V,case_insensitive:B??!1,total_matches:E.length,original_total:b,offset:G,head_limit:H,strategy:L,exit_code:w?.exitCode};if(w&&w.exitCode!==0&&w.stderr)return{success:!1,llmContent:`Search execution failed: ${w.stderr}`,metadata:{...a,summary:`搜索失败: ${w.stderr}`},error:{type:"execution_error",message:w.stderr}};return{success:!0,llmContent:E,metadata:{...a,summary:E.length>0?`搜索 "${J}" 找到 ${E.length} 个文件`:`搜索 "${J}" 未找到匹配`}}}catch(w){let L=w;if(L.name==="AbortError")return{success:!1,llmContent:"Search aborted",metadata:{summary:"搜索失败: 操作被中止"},error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${L.message}`,metadata:{summary:`搜索失败: ${L.message}`},error:{type:"execution_error",message:L.message,details:L}}}},version:"3.0.0",category:"搜索工具",tags:["search","grep","ripgrep","regex","text","fallback"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});import{spawn as O6}from"child_process";import{randomUUID as z6}from"crypto";import{z as M5}from"zod";var U6=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"]),q6=/^(LD_.+|DYLD_.+|PATH)$/,P4=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Y0($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],X=J[2],Y=W.match(P4);if(!Y)break;let V=Y[1];if(!U6.has(V))break;Z=X}return Z}function y4($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],X=J[2],Y=W.match(P4);if(!Y)break;let V=Y[1];if(q6.test(V))break;Z=X}return Z}var H6=[/^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 p$($){let Z=$,J=!0;while(J){J=!1;for(let W of H6){let X=Z.match(W);if(X){Z=Z.slice(X[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function x4($){let Z=[],J="",W=!1,X=!1,Y=!1;for(let V=0;V<$.length;V++){let B=$[V];if(Y){J+=B,Y=!1;continue}if(B==="\\"&&!W){J+=B,Y=!0;continue}if(B==="'"&&!X){W=!W,J+=B;continue}if(B==='"'&&!W){X=!X,J+=B;continue}if(W||X){J+=B;continue}if(B==="|"){if(V+1<$.length&&$[V+1]==="|"){if(J.trim())Z.push(J.trim());J="",V++;continue}return null}if(B===">"||B==="<")return null;if(B==="&"&&V+1<$.length&&$[V+1]==="&"){if(J.trim())Z.push(J.trim());J="",V++;continue}if(B==="&")return null;if(B===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=B}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function f4($){let Z=[],J="",W=!1,X=!1,Y=!1;for(let V=0;V<$.length;V++){let B=$[V];if(Y){J+=B,Y=!1;continue}if(B==="\\"&&!W){if(Y=!0,X){let K=$[V+1];if(K&&'$`"\\'.includes(K))continue;J+=B,Y=!1}continue}if(B==="'"&&!X){W=!W;continue}if(B==='"'&&!W){X=!X;continue}if(!W&&!X&&/[ \t]/.test(B)){if(J)Z.push(J),J="";continue}J+=B}if(J)Z.push(J);return Z}var j1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},V0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},h4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},G6={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},F6=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:j1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:j1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:V0,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:h4},{pattern:/^git\s+(status|branch|remote)/i,config:V0},{pattern:/^git\s+(log|diff|show)/i,config:h4},{pattern:/^(ls|dir|tree)\s+/i,config:V0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:V0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:V0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:j1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:j1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:V0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:V0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class h0{static getConfigForCommand($){for(let{pattern:Z,config:J,summaryTemplate:W}of F6)if(Z.test($))return{config:J,summaryTemplate:W};return{config:G6}}static truncate($,Z){let{config:J,summaryTemplate:W}=this.getConfigForCommand(Z);return this.truncateWithConfig($,J,W)}static truncateWithConfig($,Z,J){let W=$.length,X=$.split(`
727
727
  `),Y=X.length;if(Y<=Z.maxLines&&W<=Z.maxChars)return{content:$,truncated:!1,originalLines:Y,originalChars:W};let V=X.slice(0,Z.keepHead),B=X.slice(-Z.keepTail),K=Y-Z.keepHead-Z.keepTail,Q=V.join(`
728
728
  `);if(Q+=`
729
729
 
@@ -756,13 +756,13 @@ Before executing commands:
756
756
  * cd "/Users/name/My Documents" (correct)
757
757
  * cd /Users/name/My Documents (incorrect - will fail)
758
758
  * python "/path/with spaces/script.py" (correct)
759
- * 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($,Z){let{command:J,timeout:W=30000,cwd:X,env:Y,run_in_background:V=!1}=$,{updateOutput:B}=Z,K=Z.signal??new AbortController().signal;try{if(B?.(`Executing Bash command: ${J}`),V)return w6(J,X,Y);if(P$())return B?.("通过 IDE 终端执行命令..."),j6(J,X,Y,W,K,B);else return N6(J,X,Y,W,K,B)}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`Command execution failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let J=X0(h$($.command.trim())).split(/\s+/);if(J.length===1)return J[0];if(["run","exec","test","start","build","dev"].includes(J[1])){if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}});function w6($,Z,J){let X=n.getInstance().startBackgroundProcess({command:$,sessionId:z6(),cwd:Z||N(),env:J}),V=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,B={command:$,background:!0,pid:X.pid??0,bash_id:X.id,shell_id:X.id,message:"命令已在后台启动",summary:V};return{success:!0,llmContent:{command:$,background:!0,pid:X.pid,bash_id:X.id,shell_id:X.id},metadata:B}}async function j6($,Z,J,W,X,Y){let V=Date.now();try{let K=await F4().execute($,{cwd:Z||N(),env:J,timeout:W,signal:X,onOutput:(O)=>{Y?.(O)}}),Q=Date.now()-V;if(X.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:Q}};if(K.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${W}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K.stdout,stderr:K.stderr,execution_time:Q}};let U=$.length>30?`${$.substring(0,30)}...`:$,q=K.exitCode===0?`执行命令成功 (${Q}ms): ${U}`:`执行命令完成 (退出码 ${K.exitCode}, ${Q}ms): ${U}`,H={command:$,execution_time:Q,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},G=f0.truncateForLLM(K.stdout.trim(),K.stderr.trim(),$);return{success:K.success,llmContent:{stdout:G.stdout,stderr:G.stderr,execution_time:Q,exit_code:K.exitCode,...G.truncationInfo&&{truncation_info:G.truncationInfo}},metadata:H}}catch(B){let K=B,Q=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:Q,error:K.message}}}}async function N6($,Z,J,W,X,Y){return new Promise((V)=>{let B=Date.now(),K="",Q="",U=!1,q=O6("bash",["-c",$],{cwd:Z||N(),env:{...process.env,...J,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]});q.stdout.on("data",(O)=>{K+=O.toString()}),q.stderr.on("data",(O)=>{Q+=O.toString()});let H=setTimeout(()=>{U=!0,q.kill("SIGTERM"),setTimeout(()=>{if(!q.killed)q.kill("SIGKILL")},1000)},W),G=()=>{q.kill("SIGTERM"),clearTimeout(H)};if(X.addEventListener)X.addEventListener("abort",G);else if("onabort"in X)X.onabort=G;q.on("close",(O,F)=>{if(clearTimeout(H),X.removeEventListener)X.removeEventListener("abort",G);else if("onabort"in X)X.onabort=null;let z=Date.now()-B;if(U){V({success:!1,llmContent:`Command execution timed out (${W}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K,stderr:Q,execution_time:z}});return}if(X.aborted){V({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:K,stderr:Q,execution_time:z}});return}let w=$.length>30?`${$.substring(0,30)}...`:$,L=O===0?`执行命令成功 (${z}ms): ${w}`:`执行命令完成 (退出码 ${O}, ${z}ms): ${w}`,E={command:$,execution_time:z,exit_code:O,signal:F,stdout_length:K.length,stderr_length:Q.length,has_stderr:Q.length>0,summary:L},j=f0.truncateForLLM(K.trim(),Q.trim(),$);V({success:!0,llmContent:{stdout:j.stdout,stderr:j.stderr,execution_time:z,exit_code:O,signal:F,...j.truncationInfo&&{truncation_info:j.truncationInfo}},metadata:E})}),q.on("error",(O)=>{if(clearTimeout(H),X.removeEventListener)X.removeEventListener("abort",G);else if("onabort"in X)X.onabort=null;V({success:!1,llmContent:`Command execution failed: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}})})})}import{z as p4}from"zod";var C5=D({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:p4.object({shell_id:p4.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
759
+ * 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($,Z){let{command:J,timeout:W=30000,cwd:X,env:Y,run_in_background:V=!1}=$,{updateOutput:B}=Z,K=Z.signal??new AbortController().signal;try{if(B?.(`Executing Bash command: ${J}`),V)return w6(J,X,Y);if(y$())return B?.("通过 IDE 终端执行命令..."),j6(J,X,Y,W,K,B);else return N6(J,X,Y,W,K,B)}catch(Q){let U=Q;if(U.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`Command execution failed: ${U.message}`,error:{type:"execution_error",message:U.message,details:U}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let J=Y0(p$($.command.trim())).split(/\s+/);if(J.length===1)return J[0];if(["run","exec","test","start","build","dev"].includes(J[1])){if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}if(J.length===2)return`${J[0]} ${J[1]}`;return`${J[0]} ${J[1]} *`}});function w6($,Z,J){let X=n.getInstance().startBackgroundProcess({command:$,sessionId:z6(),cwd:Z||N(),env:J}),V=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,B={command:$,background:!0,pid:X.pid??0,bash_id:X.id,shell_id:X.id,message:"命令已在后台启动",summary:V};return{success:!0,llmContent:{command:$,background:!0,pid:X.pid,bash_id:X.id,shell_id:X.id},metadata:B}}async function j6($,Z,J,W,X,Y){let V=Date.now();try{let K=await F4().execute($,{cwd:Z||N(),env:J,timeout:W,signal:X,onOutput:(O)=>{Y?.(O)}}),Q=Date.now()-V;if(X.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:Q}};if(K.error==="Command timed out")return{success:!1,llmContent:`Command execution timed out (${W}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K.stdout,stderr:K.stderr,execution_time:Q}};let U=$.length>30?`${$.substring(0,30)}...`:$,q=K.exitCode===0?`执行命令成功 (${Q}ms): ${U}`:`执行命令完成 (退出码 ${K.exitCode}, ${Q}ms): ${U}`,H={command:$,execution_time:Q,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},G=h0.truncateForLLM(K.stdout.trim(),K.stderr.trim(),$);return{success:K.success,llmContent:{stdout:G.stdout,stderr:G.stderr,execution_time:Q,exit_code:K.exitCode,...G.truncationInfo&&{truncation_info:G.truncationInfo}},metadata:H}}catch(B){let K=B,Q=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:Q,error:K.message}}}}async function N6($,Z,J,W,X,Y){return new Promise((V)=>{let B=Date.now(),K="",Q="",U=!1,q=O6("bash",["-c",$],{cwd:Z||N(),env:{...process.env,...J,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]});q.stdout.on("data",(O)=>{K+=O.toString()}),q.stderr.on("data",(O)=>{Q+=O.toString()});let H=setTimeout(()=>{U=!0,q.kill("SIGTERM"),setTimeout(()=>{if(!q.killed)q.kill("SIGKILL")},1000)},W),G=()=>{q.kill("SIGTERM"),clearTimeout(H)};if(X.addEventListener)X.addEventListener("abort",G);else if("onabort"in X)X.onabort=G;q.on("close",(O,F)=>{if(clearTimeout(H),X.removeEventListener)X.removeEventListener("abort",G);else if("onabort"in X)X.onabort=null;let z=Date.now()-B;if(U){V({success:!1,llmContent:`Command execution timed out (${W}ms)`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K,stderr:Q,execution_time:z}});return}if(X.aborted){V({success:!1,llmContent:"Command execution aborted by user",error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:K,stderr:Q,execution_time:z}});return}let w=$.length>30?`${$.substring(0,30)}...`:$,L=O===0?`执行命令成功 (${z}ms): ${w}`:`执行命令完成 (退出码 ${O}, ${z}ms): ${w}`,E={command:$,execution_time:z,exit_code:O,signal:F,stdout_length:K.length,stderr_length:Q.length,has_stderr:Q.length>0,summary:L},j=h0.truncateForLLM(K.trim(),Q.trim(),$);V({success:!0,llmContent:{stdout:j.stdout,stderr:j.stderr,execution_time:z,exit_code:O,signal:F,...j.truncationInfo&&{truncation_info:j.truncationInfo}},metadata:E})}),q.on("error",(O)=>{if(clearTimeout(H),X.removeEventListener)X.removeEventListener("abort",G);else if("onabort"in X)X.onabort=null;V({success:!1,llmContent:`Command execution failed: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}})})})}import{z as p4}from"zod";var C5=D({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",isConcurrencySafe:!1,schema:p4.object({shell_id:p4.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
760
760
  - Kills a running background bash shell by its ID
761
761
  - Takes a shell_id parameter identifying the shell to kill
762
762
  - Returns a success or failure status
763
763
  - Use this tool when you need to terminate a long-running shell
764
764
  - Shell IDs can be found using the /tasks command
765
- `},async execute($,Z){let W=n.getInstance().kill($.shell_id);if(!W)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!W.success&&!W.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...W,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:W.status,already_exited:W.alreadyExited,pid:W.pid,exit_code:W.exitCode,signal:W.signal},metadata:{...W,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as p$}from"zod";var d4=D({name:"AddTask",displayName:"Add Task",kind:"write",isConcurrencySafe:!1,schema:p$.object({title:p$.string().min(1).describe("Brief title of the task"),description:p$.string().min(1).describe("Detailed description of what needs to be done"),complexity:p$.enum(["low","medium","high"]).optional().default("medium").describe("Estimated complexity of the task"),affectedFiles:p$.array(p$.string()).optional().default([]).describe("List of files that will be modified by this task"),dependencies:p$.array(p$.string()).optional().default([]).describe("IDs of tasks that must be completed before this one")}),description:{short:"Add a task to the current Spec project",long:`Use this tool to add tasks to the current Spec-Driven Development project.
765
+ `},async execute($,Z){let W=n.getInstance().kill($.shell_id);if(!W)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"},metadata:{summary:`未找到 Shell: ${$.shell_id}`}};if(!W.success&&!W.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:{...W,summary:`终止 Shell 失败: ${$.shell_id}`}};return{success:!0,llmContent:{shell_id:$.shell_id,status:W.status,already_exited:W.alreadyExited,pid:W.pid,exit_code:W.exitCode,signal:W.signal},metadata:{...W,summary:`终止 Shell: ${$.shell_id}`}}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as d$}from"zod";var d4=D({name:"AddTask",displayName:"Add Task",kind:"write",isConcurrencySafe:!1,schema:d$.object({title:d$.string().min(1).describe("Brief title of the task"),description:d$.string().min(1).describe("Detailed description of what needs to be done"),complexity:d$.enum(["low","medium","high"]).optional().default("medium").describe("Estimated complexity of the task"),affectedFiles:d$.array(d$.string()).optional().default([]).describe("List of files that will be modified by this task"),dependencies:d$.array(d$.string()).optional().default([]).describe("IDs of tasks that must be completed before this one")}),description:{short:"Add a task to the current Spec project",long:`Use this tool to add tasks to the current Spec-Driven Development project.
766
766
 
767
767
  ## Task Structure
768
768
 
@@ -1182,7 +1182,7 @@ Progress: ${Q.completed}/${Q.total} tasks (${Q.percentage}%)`+q,metadata:{taskId
1182
1182
  - Before marking spec as done
1183
1183
  - To get improvement suggestions
1184
1184
  `},async execute($,Z){let J=m.getInstance(),W=J.getCurrentSpec();if(!W)return{success:!1,llmContent:"No active spec. Use EnterSpecMode or /spec load <name> first.",error:{type:"validation_error",message:"No active spec project"},metadata:{summary:"无活跃 Spec"}};try{let X=await J.validateCurrentSpec(),Y=[];Y.push(`# Spec Validation: ${W.name}`),Y.push(""),Y.push(`**Phase**: ${s[X.phase]}`),Y.push(`**Status**: ${X.valid?"[OK] Valid":"[WARN] Has Issues"}`),Y.push(""),Y.push("## File Completeness"),Y.push("");let V=[["proposal.md",X.completeness.proposal],["spec.md",X.completeness.spec],["requirements.md",X.completeness.requirements],["design.md",X.completeness.design],["tasks.md",X.completeness.tasks]];for(let[Q,U]of V)Y.push(`- ${U?"[OK] ":"[FAIL] "} ${Q}`);if(Y.push(""),X.issues.length>0){Y.push("## [WARN] Issues"),Y.push("");for(let Q of X.issues){let U={error:"[ERROR]",warning:"[WARN]",info:"[INFO]"}[Q.severity];Y.push(`- ${U} **${Q.file}**: ${Q.message}`)}Y.push("")}if(X.suggestions.length>0){Y.push("## Suggestions"),Y.push("");for(let Q of X.suggestions)Y.push(`- ${Q}`);Y.push("")}let B=J.getTaskProgress();if(B.total>0){Y.push("## Task Progress"),Y.push(""),Y.push(`- Total: ${B.total}`),Y.push(`- Completed: ${B.completed}`),Y.push(`- Remaining: ${B.total-B.completed}`),Y.push(`- Progress: ${B.percentage}%`),Y.push("");let Q=Math.round(B.percentage/5),U=20-Q;Y.push(`[${"█".repeat(Q)}${"░".repeat(U)}]`)}if(Y.push(""),Y.push("## Next Steps"),Y.push(""),!X.valid)Y.push("1. Address the issues listed above"),Y.push("2. Re-run ValidateSpec to verify fixes");else{let Q=J.getAllowedTransitions();if(Q.length>0)Y.push(`1. Ready to transition to: ${Q.map((U)=>s[U]).join(", ")}`),Y.push("2. Use TransitionSpecPhase to proceed");else Y.push("1. All phases complete!"),Y.push("2. Use ExitSpecMode to finish and archive")}return{success:!0,llmContent:Y.join(`
1185
- `),metadata:{valid:X.valid,phase:X.phase,completeness:X.completeness,issueCount:X.issues.length,taskProgress:B,summary:X.valid?`Spec 验证通过: ${W.name}`:`Spec 有 ${X.issues.length} 个问题`}}}catch(X){return{success:!1,llmContent:`Validation failed: ${X instanceof Error?X.message:"Unknown error"}`,error:{type:"execution_error",message:X instanceof Error?X.message:"Validation error"},metadata:{summary:"验证失败"}}}}});var o4=[u4,a4,m4,i4,d4,r4,s4,g4];import{z as A$}from"zod";var _6=A$.object({label:A$.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:A$.string().describe("Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.")}),A6=A$.object({question:A$.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:A$.string().max(12).describe('Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'),multiSelect:A$.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:A$.array(_6).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.')}),R6=A$.object({questions:A$.array(A6).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),y5=D({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:R6,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:
1185
+ `),metadata:{valid:X.valid,phase:X.phase,completeness:X.completeness,issueCount:X.issues.length,taskProgress:B,summary:X.valid?`Spec 验证通过: ${W.name}`:`Spec 有 ${X.issues.length} 个问题`}}}catch(X){return{success:!1,llmContent:`Validation failed: ${X instanceof Error?X.message:"Unknown error"}`,error:{type:"execution_error",message:X instanceof Error?X.message:"Validation error"},metadata:{summary:"验证失败"}}}}});var o4=[u4,a4,m4,i4,d4,r4,s4,g4];import{z as R$}from"zod";var _6=R$.object({label:R$.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:R$.string().describe("Explanation of what this option means or what will happen if chosen. Useful for providing context about trade-offs or implications.")}),A6=R$.object({question:R$.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:R$.string().max(12).describe('Very short label displayed as a chip/tag (max 12 chars). Examples: "Auth method", "Library", "Approach".'),multiSelect:R$.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:R$.array(_6).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.')}),R6=R$.object({questions:R$.array(A6).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),y5=D({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:R6,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:
1186
1186
  1. Gather user preferences or requirements
1187
1187
  2. Clarify ambiguous instructions
1188
1188
  3. Get decisions on implementation choices as you work
@@ -1227,7 +1227,7 @@ ${Z}
1227
1227
 
1228
1228
  Remember: Follow the above instructions carefully to complete the user's request.`}import{z as g5}from"zod";import{execSync as b6}from"node:child_process";import t4 from"node:fs";import e4 from"node:path";class h5{async execute($,Z){let J=$.content;if(Z.signal?.aborted)throw Error("Command execution aborted");return J=this.interpolateArgs(J,Z.args),J=await this.executeBashEmbeds(J,Z),J=await this.resolveFileReferences(J,Z.workspaceRoot),J}interpolateArgs($,Z){$=$.replace(/\$ARGUMENTS/g,Z.join(" "));for(let J=9;J>=1;J--){let W=`$${J}`,X=Z[J-1]??"";$=$.split(W).join(X)}return $}async executeBashEmbeds($,Z){let J=/!`([^`]+)`/g,W=[];for(let Y of $.matchAll(J))W.push({match:Y[0],command:Y[1]});let X=$;for(let{match:Y,command:V}of W){if(Z.signal?.aborted){X=X.replace(Y,"[Execution aborted]");continue}try{let B=b6(V,{cwd:Z.workspaceRoot,encoding:"utf-8",timeout:30000,maxBuffer:1048576,stdio:["pipe","pipe","pipe"]}).trim();X=X.replace(Y,B)}catch(B){let K=B instanceof Error?B.message:String(B);X=X.replace(Y,`[Error executing '${V}': ${K}]`)}}return X}async resolveFileReferences($,Z){let J=/@([\w./-]+(?:\/[\w./-]+|\.[\w]+))/g,W=[];for(let Y of $.matchAll(J))W.push({match:Y[0],relativePath:Y[1]});let X=$;for(let{match:Y,relativePath:V}of W){let B=e4.resolve(Z,V);try{if(t4.statSync(B).isFile()){let Q=t4.readFileSync(B,"utf-8"),q=`\`\`\`${e4.extname(V).slice(1)||"text"}
1229
1229
  ${Q}
1230
- \`\`\``;X=X.replace(Y,q)}}catch{}}return X}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import d5 from"node:fs";import Z9 from"node:os";import M$ from"node:path";import T6 from"node:fs";import $9 from"node:path";import M6 from"gray-matter";class p5{parse($,Z,J,W){try{let X=T6.readFileSync($,"utf-8"),{data:Y,content:V}=M6(X),{name:B,namespace:K}=this.extractNameAndNamespace($,Z);if(!B)return null;return{name:B,namespace:K,config:this.normalizeConfig(Y),content:V.trim(),path:$,source:J,sourceDir:W}}catch(X){return console.error(`Failed to parse command file: ${$}`,X),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((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}extractNameAndNamespace($,Z){let W=$9.relative(Z,$).split($9.sep),X=W.pop();if(!X)return{name:""};let Y=X.replace(/\.md$/i,""),V=W.length>0?W.join("/"):void 0;return{name:Y,namespace:V}}validateConfig($){let Z=[];if($.model&&!this.isValidModelId($.model))Z.push(`Invalid model ID: ${$.model}`);return Z}isValidModelId($){return $.length>0&&$.length<200}}class u5{parser=new p5;async discover($){let Z=[],J=[],W=[],X=this.getSearchDirs($);for(let Y of X){if(!d5.existsSync(Y.path))continue;J.push(Y.path);try{let V=await this.scanDirectory(Y.path);for(let B of V)try{let K=this.parser.parse(B,Y.path,Y.source,Y.sourceDir);if(K)Z.push(K)}catch(K){W.push({path:B,error:K instanceof Error?K.message:String(K)})}}catch(V){W.push({path:Y.path,error:V instanceof Error?V.message:String(V)})}}return{commands:Z,scannedDirs:J,errors:W}}getSearchDirs($){let Z=Z9.homedir();return[{path:M$.join(Z,".blade","commands"),source:"user",sourceDir:"blade"},{path:M$.join(Z,".claude","commands"),source:"user",sourceDir:"claude"},{path:M$.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:M$.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let Z=[],J=async(W)=>{let X=await d5.promises.readdir(W,{withFileTypes:!0});for(let Y of X){let V=M$.join(W,Y.name);if(Y.isDirectory())await J(V);else if(Y.isFile()&&Y.name.endsWith(".md"))Z.push(V)}};return await J($),Z}async hasCommands($){let Z=this.getSearchDirs($);for(let J of Z){if(!d5.existsSync(J.path))continue;if((await this.scanDirectory(J.path)).length>0)return!0}return!1}getCommandDirs($){let Z=Z9.homedir();return{projectBlade:M$.join($,".blade","commands"),projectClaude:M$.join($,".claude","commands"),userBlade:M$.join(Z,".blade","commands"),userClaude:M$.join(Z,".claude","commands")}}}class d{static instance;commands=new Map;pluginCommands=new Map;loader=new u5;executor=new h5;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!d.instance)d.instance=new d;return d.instance}static resetInstance(){d.instance=new d}constructor(){}async initialize($){this.workspaceRoot=$;let Z=await this.loader.discover($);this.lastDiscoveryResult=Z,this.commands.clear();for(let J of Z.commands)this.commands.set(J.name,J);return this.initialized=!0,Z}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($,Z){let J=this.getCommand($);if(!J)return null;return this.executor.execute(J,Z)}getCommandLabel($){let Z=$.source==="project"?"project":"user";if($.namespace)return`(${Z}:${$.namespace})`;return`(${Z})`}getCommandDisplayName($){let Z=[`/${$.name}`];if($.config.argumentHint)Z.push($.config.argumentHint);if($.config.description)Z.push("-",$.config.description);return Z.push(this.getCommandLabel($)),Z.join(" ")}getCommandsBySource(){let $=[],Z=[];for(let J of this.commands.values())if(J.source==="project")$.push(J);else Z.push(J);return{project:$,user:Z}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let Z=this.getModelInvocableCommands(),J=Z.length;if(J===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let W=`Available custom commands:
1230
+ \`\`\``;X=X.replace(Y,q)}}catch{}}return X}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import d5 from"node:fs";import Z9 from"node:os";import v$ from"node:path";import T6 from"node:fs";import $9 from"node:path";import M6 from"gray-matter";class p5{parse($,Z,J,W){try{let X=T6.readFileSync($,"utf-8"),{data:Y,content:V}=M6(X),{name:B,namespace:K}=this.extractNameAndNamespace($,Z);if(!B)return null;return{name:B,namespace:K,config:this.normalizeConfig(Y),content:V.trim(),path:$,source:J,sourceDir:W}}catch(X){return console.error(`Failed to parse command file: ${$}`,X),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((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}extractNameAndNamespace($,Z){let W=$9.relative(Z,$).split($9.sep),X=W.pop();if(!X)return{name:""};let Y=X.replace(/\.md$/i,""),V=W.length>0?W.join("/"):void 0;return{name:Y,namespace:V}}validateConfig($){let Z=[];if($.model&&!this.isValidModelId($.model))Z.push(`Invalid model ID: ${$.model}`);return Z}isValidModelId($){return $.length>0&&$.length<200}}class u5{parser=new p5;async discover($){let Z=[],J=[],W=[],X=this.getSearchDirs($);for(let Y of X){if(!d5.existsSync(Y.path))continue;J.push(Y.path);try{let V=await this.scanDirectory(Y.path);for(let B of V)try{let K=this.parser.parse(B,Y.path,Y.source,Y.sourceDir);if(K)Z.push(K)}catch(K){W.push({path:B,error:K instanceof Error?K.message:String(K)})}}catch(V){W.push({path:Y.path,error:V instanceof Error?V.message:String(V)})}}return{commands:Z,scannedDirs:J,errors:W}}getSearchDirs($){let Z=Z9.homedir();return[{path:v$.join(Z,".blade","commands"),source:"user",sourceDir:"blade"},{path:v$.join(Z,".claude","commands"),source:"user",sourceDir:"claude"},{path:v$.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:v$.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let Z=[],J=async(W)=>{let X=await d5.promises.readdir(W,{withFileTypes:!0});for(let Y of X){let V=v$.join(W,Y.name);if(Y.isDirectory())await J(V);else if(Y.isFile()&&Y.name.endsWith(".md"))Z.push(V)}};return await J($),Z}async hasCommands($){let Z=this.getSearchDirs($);for(let J of Z){if(!d5.existsSync(J.path))continue;if((await this.scanDirectory(J.path)).length>0)return!0}return!1}getCommandDirs($){let Z=Z9.homedir();return{projectBlade:v$.join($,".blade","commands"),projectClaude:v$.join($,".claude","commands"),userBlade:v$.join(Z,".blade","commands"),userClaude:v$.join(Z,".claude","commands")}}}class d{static instance;commands=new Map;pluginCommands=new Map;loader=new u5;executor=new h5;initialized=!1;workspaceRoot="";lastDiscoveryResult=null;static getInstance(){if(!d.instance)d.instance=new d;return d.instance}static resetInstance(){d.instance=new d}constructor(){}async initialize($){this.workspaceRoot=$;let Z=await this.loader.discover($);this.lastDiscoveryResult=Z,this.commands.clear();for(let J of Z.commands)this.commands.set(J.name,J);return this.initialized=!0,Z}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($,Z){let J=this.getCommand($);if(!J)return null;return this.executor.execute(J,Z)}getCommandLabel($){let Z=$.source==="project"?"project":"user";if($.namespace)return`(${Z}:${$.namespace})`;return`(${Z})`}getCommandDisplayName($){let Z=[`/${$.name}`];if($.config.argumentHint)Z.push($.config.argumentHint);if($.config.description)Z.push("-",$.config.description);return Z.push(this.getCommandLabel($)),Z.join(" ")}getCommandsBySource(){let $=[],Z=[];for(let J of this.commands.values())if(J.source==="project")$.push(J);else Z.push(J);return{project:$,user:Z}}getLastDiscoveryResult(){return this.lastDiscoveryResult}getCommandDirs(){if(!this.workspaceRoot)return null;return this.loader.getCommandDirs(this.workspaceRoot)}generateCommandListDescription($=15000){let Z=this.getModelInvocableCommands(),J=Z.length;if(J===0)return{text:"No custom commands available.",includedCount:0,totalCount:0};let W=`Available custom commands:
1231
1231
 
1232
1232
  `,X=W.length,Y=0;for(let V of Z){let B=this.getCommandLabel(V),K=V.config.argumentHint?` ${V.config.argumentHint}`:"",Q=`- /${V.name}${K}: ${V.config.description} ${B}
1233
1233
  `;if(X+Q.length>$)break;W+=Q,X+=Q.length,Y++}if(Y<J)W+=`
@@ -1278,11 +1278,11 @@ ${Z}
1278
1278
  Remember: Follow the above instructions carefully to complete the user's request.`,W}import{z as c5}from"zod";var l5=D({name:"ToolSearch",displayName:"Tool Search",kind:"readonly",isConcurrencySafe:!0,schema:c5.object({query:c5.string().describe('Search query. Use "select:Read,Edit,Grep" for exact selection, or keywords for fuzzy search.'),max_results:c5.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($,Z){let{query:J,max_results:W}=$,X=Z.toolRegistry;if(!X)return{success:!1,llmContent:"Tool registry not available in execution context."};let Y=[];if(J.startsWith("select:")){let B=J.slice(7).split(",").map((K)=>K.trim());for(let K of B){let Q=X.get(K);if(Q)Y.push({name:Q.name,declaration:Q.getFunctionDeclaration()})}}else Y=X.search(J).slice(0,W).map((K)=>({name:K.name,declaration:K.getFunctionDeclaration()}));if(Y.length===0)return{success:!0,llmContent:`No tools found matching "${J}".`};if(Z.deferredToolManager)for(let{name:B}of Y)Z.deferredToolManager.markLoaded(B);return{success:!0,llmContent:`<functions>
1279
1279
  ${Y.map(({declaration:B})=>`<function>${JSON.stringify(B)}</function>`).join(`
1280
1280
  `)}
1281
- </functions>`,metadata:{summary:`加载了 ${Y.length} 个工具 schema`}}}});import{nanoid as w9}from"nanoid";import{z as q0}from"zod";import{nanoid as AZ}from"nanoid";import*as U9 from"os";import*as q9 from"path";import{EventEmitter as OZ}from"events";import{nanoid as S6}from"nanoid";class i5{name="hook";hookManager;constructor(){this.hookManager=X$.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;if($._internal.ruleDecision?.behavior==="deny")return;try{let J=$.context.messageId||`tool_${S6()}`;$._internal.hookToolUseId=J;let W=$.context.workspaceRoot||N(),X=await this.hookManager.executePreToolHooks(Z.name,J,$.params,{projectDir:W,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(X.modifiedInput&&X.decision!=="deny"){let Y={...$.params,...X.modifiedInput};try{Z.build(Y),$.params=Y}catch(V){$.abort(`Hook modified parameters are invalid: ${V instanceof Error?V.message:String(V)}`);return}}if($._internal.hookDecision=P6(X.decision,{reason:X.reason}),X.warning)console.warn(`[Hook Warning] ${X.warning}`)}catch(J){console.error("[HookStage] Error executing hooks:",J)}}}function P6($,Z){return{behavior:$,source:"hook",reason:Z.reason}}import{nanoid as y6}from"nanoid";function x6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class a5{name="post-hook";hookManager;constructor(){this.hookManager=X$.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;let J=$.getResult();if(!J)return;try{let W=$._internal.hookToolUseId||$.context.messageId||`tool_${y6()}`,X=$.context.workspaceRoot||N(),Y=await this.hookManager.executePostToolHooks(Z.name,W,$.params,J,{projectDir:X,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(Y.additionalContext){let V=typeof J.llmContent==="string"?J.llmContent:J.llmContent?JSON.stringify(J.llmContent):"";J.llmContent=`${V}
1281
+ </functions>`,metadata:{summary:`加载了 ${Y.length} 个工具 schema`}}}});import{nanoid as w9}from"nanoid";import{z as H0}from"zod";import{nanoid as kZ}from"nanoid";import*as U9 from"os";import*as q9 from"path";import{EventEmitter as wZ}from"events";import{nanoid as S6}from"nanoid";class i5{name="hook";hookManager;constructor(){this.hookManager=X$.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;if($._internal.ruleDecision?.behavior==="deny")return;try{let J=$.context.messageId||`tool_${S6()}`;$._internal.hookToolUseId=J;let W=$.context.workspaceRoot||N(),X=await this.hookManager.executePreToolHooks(Z.name,J,$.params,{projectDir:W,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(X.modifiedInput&&X.decision!=="deny"){let Y={...$.params,...X.modifiedInput};try{Z.build(Y),$.params=Y}catch(V){$.abort(`Hook modified parameters are invalid: ${V instanceof Error?V.message:String(V)}`);return}}if($._internal.hookDecision=P6(X.decision,{reason:X.reason}),X.warning)console.warn(`[Hook Warning] ${X.warning}`)}catch(J){console.error("[HookStage] Error executing hooks:",J)}}}function P6($,Z){return{behavior:$,source:"hook",reason:Z.reason}}import{nanoid as y6}from"nanoid";function x6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class a5{name="post-hook";hookManager;constructor(){this.hookManager=X$.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Z=$._internal.tool;if(!Z)return;let J=$.getResult();if(!J)return;try{let W=$._internal.hookToolUseId||$.context.messageId||`tool_${y6()}`,X=$.context.workspaceRoot||N(),Y=await this.hookManager.executePostToolHooks(Z.name,W,$.params,J,{projectDir:X,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode??"default",abortSignal:$.context.signal});if(Y.additionalContext){let V=typeof J.llmContent==="string"?J.llmContent:J.llmContent?JSON.stringify(J.llmContent):"";J.llmContent=`${V}
1282
1282
 
1283
1283
  ---
1284
1284
  **Hook Context:**
1285
- ${Y.additionalContext}`}if(Y.modifiedOutput!==void 0){let V=Y.modifiedOutput;if(x6(V))Object.assign(J,V)}if(Y.warning)console.warn(`[PostToolUseHook Warning] ${Y.warning}`)}catch(W){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",W)}}}var n5=M("Execution");class d${static instance=null;locks=new Map;constructor(){}static getInstance(){if(!d$.instance)d$.instance=new d$;return d$.instance}async acquireLock($,Z){let J=this.locks.get($);if(J)try{await J}catch{}let W=this.executeWithLock($,Z);return this.locks.set($,W.then(()=>{return})),W}async executeWithLock($,Z){n5.debug(`获取文件锁: ${$}`);try{let J=await Z();return n5.debug(`释放文件锁: ${$}`),J}catch(J){throw n5.debug(`操作失败,释放文件锁: ${$}`),J}}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(){d$.instance=null}}var f6={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class v${static instance=null;buckets;constructor($={}){let Z={...f6,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:Z.readonly,queue:[]},write:{inFlight:0,maxConcurrent:Z.write,queue:[]},execute:{inFlight:0,maxConcurrent:Z.execute,queue:[]}}}static getInstance(){if(!v$.instance)v$.instance=new v$;return v$.instance}static resetInstance(){v$.instance=null}schedule($,Z){let J=this.buckets[$];if(!J)return Z();if(J.inFlight<J.maxConcurrent)return this.runImmediately(J,Z);return new Promise((W,X)=>{J.queue.push({fn:Z,resolve:W,reject:X})})}async runImmediately($,Z){$.inFlight++;try{return await Z()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let Z=$.queue.shift();$.inFlight++,Z.fn().then(Z.resolve,Z.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}}}}class h0{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import p0 from"picomatch";class V0{config;constructor($){this.config=$}check($){let Z=V0.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",W=J?String($.params.command).trim():"",X=null;if(J){let Q=X0(h$(W));if(Q!==W)X=`Bash(${Q})`}let Y=null;if(J){let Q=y4(h$(W));if(Q!==W)Y=`Bash(${Q})`}let V=[Z];if(Y)V.push(Y);for(let Q of V){let U=this.matchRules(Q,this.config.deny);if(U)return{result:"deny",matchedRule:U.rule,matchType:U.type,reason:`工具调用被拒绝规则阻止: ${U.rule}`}}let B=[Z];if(X)B.push(X);for(let Q of B){let U=this.matchRules(Q,this.config.allow);if(U)return{result:"allow",matchedRule:U.rule,matchType:U.type,reason:`工具调用符合允许规则: ${U.rule}`}}let K=[Z];if(Y)K.push(Y);for(let Q of K){let U=this.matchRules(Q,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:Z,params:J,tool:W}=$;try{if(W?.extractSignatureContent){let X=W.extractSignatureContent(J);return X?`${Z}(${X})`:Z}return Z}catch(X){return console.warn(`Failed to build signature for ${Z}:`,X instanceof Error?X.message:X),Z}}static abstractPattern($){let{toolName:Z,params:J,tool:W}=$;try{if(W?.abstractPermissionRule){let X=W.abstractPermissionRule(J);if(X==="")return"";return X?`${Z}(${X})`:Z}return Z}catch(X){return console.warn(`Failed to abstract pattern for ${Z}:`,X instanceof Error?X.message:X),Z}}matchRules($,Z){for(let J of Z){let W=this.matchRule($,J);if(W)return{rule:J,type:W}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let J=this.extractToolName($),W=this.extractToolName(Z);if(!J||!W)return null;if(W.includes("*")){if(!p0.isMatch(J,W,{dot:!0,bash:!0}))return null}else if(J!==W)return null;if(Z===W)return"prefix";if(Z.includes("*")){let X=this.extractParams($),Y=this.extractParams(Z);if(Y==="*"||Y==="**")return"wildcard";if(this.matchParams(X,Y))return Y.includes("**")?"glob":"wildcard";if(p0.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let J=this.parseParamPairs($),W=this.parseParamPairs(Z),X=Object.keys(W).length>0,Y=Object.keys(J).length>0;if(X!==Y)return!1;if(!X&&!Y){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return p0.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[V,B]of Object.entries(W)){let K=J[V];if(K===void 0)return!1;if(B.includes("*")||B.includes("{")||B.includes("?")){if(B==="*"||B==="**")continue;if(!p0.isMatch(K,B,{dot:!0,bash:!0}))return!1}else if(K!==B)return!1}return!0}parseParamPairs($){let Z={},J=this.smartSplit($,",");for(let W of J){let X=this.findTopLevelDelimiter(W,":");if(X>0){let Y=W.slice(0,X).trim(),V=W.slice(X+1).trim();Z[Y]=V}}return Z}smartSplit($,Z){let J=[],W="",X=0,Y=0,V=0,B=!1,K="",Q=!1;for(let U=0;U<$.length;U++){let q=$[U];if(Q){W+=q,Q=!1;continue}if(q==="\\"){W+=q,Q=!0;continue}if(!B&&q==="{")X++;else if(!B&&q==="}")X--;else if(!B&&q==="(")Y++;else if(!B&&q===")")Y--;else if(!B&&q==="[")V++;else if(!B&&q==="]")V--;if((q==='"'||q==="'")&&!B){B=!0,K=q,W+=q;continue}else if(B&&q===K){B=!1,K="",W+=q;continue}if(q===Z&&X===0&&Y===0&&V===0&&!B)J.push(W.trim()),W="";else W+=q}if(W)J.push(W.trim());return J}findTopLevelDelimiter($,Z){let J=0,W=0,X=0,Y=!1,V="",B=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(B){B=!1;continue}if(Q==="\\"){B=!0;continue}if(!Y&&Q==="{")J++;else if(!Y&&Q==="}")J--;else if(!Y&&Q==="(")W++;else if(!Y&&Q===")")W--;else if(!Y&&Q==="[")X++;else if(!Y&&Q==="]")X--;if((Q==='"'||Q==="'")&&!Y){Y=!0,V=Q;continue}else if(Y&&Q===V){Y=!1,V="";continue}if(Q===Z&&J===0&&W===0&&X===0&&!Y)return K}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[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 Y$=M("Execution");class r5{registry;name="discovery";constructor($){this.registry=$}async process($){let Z=this.registry.get($.toolName);if(!Z){$.abort(`Tool "${$.toolName}" not found`);return}$._internal.tool=Z}}class s5{sessionApprovals;name="confirmation";permissionChecker;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async process($){let{tool:Z,invocation:J,effectiveDecision:W}=$._internal;if(!Z||!J){$.abort("Pre-confirmation stage failed; cannot request user approval");return}if(W?.behavior!=="ask")return;let X=W.reason;try{let Y=Z.extractSignatureContent?Z.extractSignatureContent($.params):Z.name,V=X$.getInstance();if(V.isEnabled()){let Q=await V.executePermissionRequestHooks(Z.name,$.context.sessionId||"unknown",$.params,{projectDir:N(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});switch(Q.decision){case"approve":Y$.debug(`PermissionRequest hook 自动批准: ${Z.name}`);return;case"deny":$.abort(Q.reason||`PermissionRequest hook denied: ${Z.name}`,{shouldExitLoop:!0});return;case"ask":default:break}}let B={title:Y,message:X||"此操作需要用户确认",kind:Z.kind,details:this.generatePreviewForTool(Z.name,$.params),risks:this.extractRisksFromPermissionCheck(Z,$.params),affectedFiles:J.getAffectedPaths()||[]};if(Y$.warn(`工具 "${Z.name}" 需要用户确认: ${B.title}`),Y$.warn(`详情: ${B.message}`),B.risks&&B.risks.length>0)Y$.warn(`风险: ${B.risks.join(", ")}`);let K=$.context.confirmationHandler;if(K){Y$.info(`[ConfirmationStage] Requesting confirmation for ${Z.name}`);let Q=await K.requestConfirmation(B);if(Y$.info(`[ConfirmationStage] Confirmation response: approved=${Q.approved}`),$.context.signal?.aborted){Y$.info("[ConfirmationStage] Signal aborted, setting abort result"),$.abort("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});return}if(!Q.approved){$.abort(Q.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"});return}if(Y$.info("[ConfirmationStage] User approved, continuing to execution stage"),(Q.scope||"once")==="session"&&$._internal.permissionSignature){let q=$._internal.permissionSignature;this.sessionApprovals.add(q);let H={toolName:Z.name,params:$.params,affectedPaths:J.getAffectedPaths()||[],tool:Z};await this.persistSessionApproval(q,H)}}else{let Q=$.context.permissionMode||"default";if(Q==="yolo")Y$.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode (non-interactive environment)");else{Y$.warn(`[WARN] No ConfirmationHandler in "${Q}" mode; denying tool "${Z.name}" (non-interactive environment). Use --permission-mode yolo to auto-approve.`),$.abort(`Non-interactive mode with "${Q}" permission: tool "${Z.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{shouldExitLoop:!1,llmContent:`工具 "${Z.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${Q}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"});return}}}catch(Y){$.abort(`User confirmation failed: ${Y.message}`)}}async persistSessionApproval($,Z){try{let J=V0.abstractPattern(Z);Y$.debug(`保存权限规则: "${J}"`),await x$().appendLocalPermissionAllowRule(J,{immediate:!0});let W=t();if(W?.permissions)Y$.debug("同步权限配置到 PermissionChecker:",W.permissions),this.permissionChecker.replaceConfig(W.permissions)}catch(J){Y$.warn(`Failed to persist permission rule "${$}": ${J instanceof Error?J.message:"Unknown error"}`)}}generatePreviewForTool($,Z){switch($){case"Edit":{let{old_string:J,new_string:W}=Z;if(!J&&!W)return;let X=20,Y=(V)=>{let B=V.split(`
1285
+ ${Y.additionalContext}`}if(Y.modifiedOutput!==void 0){let V=Y.modifiedOutput;if(x6(V))Object.assign(J,V)}if(Y.warning)console.warn(`[PostToolUseHook Warning] ${Y.warning}`)}catch(W){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",W)}}}var n5=M("Execution");class u${static instance=null;locks=new Map;constructor(){}static getInstance(){if(!u$.instance)u$.instance=new u$;return u$.instance}async acquireLock($,Z){let J=this.locks.get($);if(J)try{await J}catch{}let W=this.executeWithLock($,Z);return this.locks.set($,W.then(()=>{return})),W}async executeWithLock($,Z){n5.debug(`获取文件锁: ${$}`);try{let J=await Z();return n5.debug(`释放文件锁: ${$}`),J}catch(J){throw n5.debug(`操作失败,释放文件锁: ${$}`),J}}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(){u$.instance=null}}var f6={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class C${static instance=null;buckets;constructor($={}){let Z={...f6,...$};this.buckets={readonly:{inFlight:0,maxConcurrent:Z.readonly,queue:[]},write:{inFlight:0,maxConcurrent:Z.write,queue:[]},execute:{inFlight:0,maxConcurrent:Z.execute,queue:[]}}}static getInstance(){if(!C$.instance)C$.instance=new C$;return C$.instance}static resetInstance(){C$.instance=null}schedule($,Z){let J=this.buckets[$];if(!J)return Z();if(J.inFlight<J.maxConcurrent)return this.runImmediately(J,Z);return new Promise((W,X)=>{J.queue.push({fn:Z,resolve:W,reject:X})})}async runImmediately($,Z){$.inFlight++;try{return await Z()}finally{$.inFlight--,this.drain($)}}drain($){while($.inFlight<$.maxConcurrent&&$.queue.length>0){let Z=$.queue.shift();$.inFlight++,Z.fn().then(Z.resolve,Z.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}}}}class p0{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import d0 from"picomatch";class B0{config;constructor($){this.config=$}check($){let Z=B0.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",W=J?String($.params.command).trim():"",X=null;if(J){let Q=Y0(p$(W));if(Q!==W)X=`Bash(${Q})`}let Y=null;if(J){let Q=y4(p$(W));if(Q!==W)Y=`Bash(${Q})`}let V=[Z];if(Y)V.push(Y);for(let Q of V){let U=this.matchRules(Q,this.config.deny);if(U)return{result:"deny",matchedRule:U.rule,matchType:U.type,reason:`工具调用被拒绝规则阻止: ${U.rule}`}}let B=[Z];if(X)B.push(X);for(let Q of B){let U=this.matchRules(Q,this.config.allow);if(U)return{result:"allow",matchedRule:U.rule,matchType:U.type,reason:`工具调用符合允许规则: ${U.rule}`}}let K=[Z];if(Y)K.push(Y);for(let Q of K){let U=this.matchRules(Q,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:Z,params:J,tool:W}=$;try{if(W?.extractSignatureContent){let X=W.extractSignatureContent(J);return X?`${Z}(${X})`:Z}return Z}catch(X){return console.warn(`Failed to build signature for ${Z}:`,X instanceof Error?X.message:X),Z}}static abstractPattern($){let{toolName:Z,params:J,tool:W}=$;try{if(W?.abstractPermissionRule){let X=W.abstractPermissionRule(J);if(X==="")return"";return X?`${Z}(${X})`:Z}return Z}catch(X){return console.warn(`Failed to abstract pattern for ${Z}:`,X instanceof Error?X.message:X),Z}}matchRules($,Z){for(let J of Z){let W=this.matchRule($,J);if(W)return{rule:J,type:W}}return null}matchRule($,Z){if($===Z)return"exact";if(Z==="*"||Z==="**")return"wildcard";let J=this.extractToolName($),W=this.extractToolName(Z);if(!J||!W)return null;if(W.includes("*")){if(!d0.isMatch(J,W,{dot:!0,bash:!0}))return null}else if(J!==W)return null;if(Z===W)return"prefix";if(Z.includes("*")){let X=this.extractParams($),Y=this.extractParams(Z);if(Y==="*"||Y==="**")return"wildcard";if(this.matchParams(X,Y))return Y.includes("**")?"glob":"wildcard";if(d0.isMatch($,Z,{dot:!0,bash:!0}))return Z.includes("**")?"glob":"wildcard"}return null}extractParams($){let Z=$.match(/\(([\s\S]*)\)$/);return Z?Z[1]:""}matchParams($,Z){if(!$||!Z)return!1;let J=this.parseParamPairs($),W=this.parseParamPairs(Z),X=Object.keys(W).length>0,Y=Object.keys(J).length>0;if(X!==Y)return!1;if(!X&&!Y){if(Z==="*"||Z==="**")return!0;if(Z.includes("*")||Z.includes("{")||Z.includes("?"))return d0.isMatch($,Z,{dot:!0,bash:!0});return $===Z}for(let[V,B]of Object.entries(W)){let K=J[V];if(K===void 0)return!1;if(B.includes("*")||B.includes("{")||B.includes("?")){if(B==="*"||B==="**")continue;if(!d0.isMatch(K,B,{dot:!0,bash:!0}))return!1}else if(K!==B)return!1}return!0}parseParamPairs($){let Z={},J=this.smartSplit($,",");for(let W of J){let X=this.findTopLevelDelimiter(W,":");if(X>0){let Y=W.slice(0,X).trim(),V=W.slice(X+1).trim();Z[Y]=V}}return Z}smartSplit($,Z){let J=[],W="",X=0,Y=0,V=0,B=!1,K="",Q=!1;for(let U=0;U<$.length;U++){let q=$[U];if(Q){W+=q,Q=!1;continue}if(q==="\\"){W+=q,Q=!0;continue}if(!B&&q==="{")X++;else if(!B&&q==="}")X--;else if(!B&&q==="(")Y++;else if(!B&&q===")")Y--;else if(!B&&q==="[")V++;else if(!B&&q==="]")V--;if((q==='"'||q==="'")&&!B){B=!0,K=q,W+=q;continue}else if(B&&q===K){B=!1,K="",W+=q;continue}if(q===Z&&X===0&&Y===0&&V===0&&!B)J.push(W.trim()),W="";else W+=q}if(W)J.push(W.trim());return J}findTopLevelDelimiter($,Z){let J=0,W=0,X=0,Y=!1,V="",B=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(B){B=!1;continue}if(Q==="\\"){B=!0;continue}if(!Y&&Q==="{")J++;else if(!Y&&Q==="}")J--;else if(!Y&&Q==="(")W++;else if(!Y&&Q===")")W--;else if(!Y&&Q==="[")X++;else if(!Y&&Q==="]")X--;if((Q==='"'||Q==="'")&&!Y){Y=!0,V=Q;continue}else if(Y&&Q===V){Y=!1,V="";continue}if(Q===Z&&J===0&&W===0&&X===0&&!Y)return K}return-1}extractToolName($){let Z=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Z?Z[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 Y$=M("Execution");class r5{registry;name="discovery";constructor($){this.registry=$}async process($){let Z=this.registry.get($.toolName);if(!Z){$.abort(`Tool "${$.toolName}" not found`);return}$._internal.tool=Z}}class s5{sessionApprovals;name="confirmation";permissionChecker;constructor($,Z){this.sessionApprovals=$;this.permissionChecker=Z}async process($){let{tool:Z,invocation:J,effectiveDecision:W}=$._internal;if(!Z||!J){$.abort("Pre-confirmation stage failed; cannot request user approval");return}if(W?.behavior!=="ask")return;let X=W.reason;try{let Y=Z.extractSignatureContent?Z.extractSignatureContent($.params):Z.name,V=X$.getInstance();if(V.isEnabled()){let Q=await V.executePermissionRequestHooks(Z.name,$.context.sessionId||"unknown",$.params,{projectDir:N(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});switch(Q.decision){case"approve":Y$.debug(`PermissionRequest hook 自动批准: ${Z.name}`);return;case"deny":$.abort(Q.reason||`PermissionRequest hook denied: ${Z.name}`,{shouldExitLoop:!0});return;case"ask":default:break}}let B={title:Y,message:X||"此操作需要用户确认",kind:Z.kind,details:this.generatePreviewForTool(Z.name,$.params),risks:this.extractRisksFromPermissionCheck(Z,$.params),affectedFiles:J.getAffectedPaths()||[]};if(Y$.warn(`工具 "${Z.name}" 需要用户确认: ${B.title}`),Y$.warn(`详情: ${B.message}`),B.risks&&B.risks.length>0)Y$.warn(`风险: ${B.risks.join(", ")}`);let K=$.context.confirmationHandler;if(K){Y$.info(`[ConfirmationStage] Requesting confirmation for ${Z.name}`);let Q=await K.requestConfirmation(B);if(Y$.info(`[ConfirmationStage] Confirmation response: approved=${Q.approved}`),$.context.signal?.aborted){Y$.info("[ConfirmationStage] Signal aborted, setting abort result"),$.abort("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});return}if(!Q.approved){$.abort(Q.reason||"用户拒绝授权",{shouldExitLoop:!0,llmContent:"已取消工具执行",summary:"已取消工具执行",errorType:"permission_denied"});return}if(Y$.info("[ConfirmationStage] User approved, continuing to execution stage"),(Q.scope||"once")==="session"&&$._internal.permissionSignature){let q=$._internal.permissionSignature;this.sessionApprovals.add(q);let H={toolName:Z.name,params:$.params,affectedPaths:J.getAffectedPaths()||[],tool:Z};await this.persistSessionApproval(q,H)}}else{let Q=$.context.permissionMode||"default";if(Q==="yolo")Y$.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode (non-interactive environment)");else{Y$.warn(`[WARN] No ConfirmationHandler in "${Q}" mode; denying tool "${Z.name}" (non-interactive environment). Use --permission-mode yolo to auto-approve.`),$.abort(`Non-interactive mode with "${Q}" permission: tool "${Z.name}" requires user confirmation but no interactive handler is available. Use --permission-mode yolo to allow all operations.`,{shouldExitLoop:!1,llmContent:`工具 "${Z.name}" 需要用户确认,但当前为非交互模式且权限模式为 "${Q}"。请使用 --permission-mode yolo 来允许所有操作。`,summary:"非交互模式下拒绝需要确认的操作",errorType:"permission_denied"});return}}}catch(Y){$.abort(`User confirmation failed: ${Y.message}`)}}async persistSessionApproval($,Z){try{let J=B0.abstractPattern(Z);Y$.debug(`保存权限规则: "${J}"`),await f$().appendLocalPermissionAllowRule(J,{immediate:!0});let W=t();if(W?.permissions)Y$.debug("同步权限配置到 PermissionChecker:",W.permissions),this.permissionChecker.replaceConfig(W.permissions)}catch(J){Y$.warn(`Failed to persist permission rule "${$}": ${J instanceof Error?J.message:"Unknown error"}`)}}generatePreviewForTool($,Z){switch($){case"Edit":{let{old_string:J,new_string:W}=Z;if(!J&&!W)return;let X=20,Y=(V)=>{let B=V.split(`
1286
1286
  `);if(B.length<=X)return V;return`${B.slice(0,X).join(`
1287
1287
  `)}
1288
1288
  ... (还有 ${B.length-X} 行)`};return`**变更前:**
@@ -1303,23 +1303,23 @@ ${J}
1303
1303
  ${V}
1304
1304
  \`\`\`
1305
1305
 
1306
- ... (还有 ${Y.length-X} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Z){let J=[];if($.name==="Bash"){let W=Z.command||"";if(W.includes("rm"))J.push("[WARN] 此命令可能删除文件");if(W.includes("sudo"))J.push("[WARN] 此命令需要管理员权限");if(W.includes("git push"))J.push("[WARN] 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")J.push("此操作将修改文件内容");else if($.name==="Delete")J.push("此操作将永久删除文件");return J}}class u${name="execution";static TRANSIENT_ERRORS=["EBUSY","EAGAIN","EMFILE","ENFILE"];static MAX_TRANSIENT_RETRIES=2;static RETRY_DELAY_MS=200;async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}let J=Date.now(),W;for(let X=0;X<=u$.MAX_TRANSIENT_RETRIES;X++)try{let Y=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);if(!Y.metadata)Y.metadata={};if(Y.metadata.duration=Date.now()-J,X>0)Y.metadata.retriedAttempts=X;$.setResult(Y);return}catch(Y){if(W=Y,X<u$.MAX_TRANSIENT_RETRIES&&this.isTransientError(W)){Y$.debug(`[ExecutionStage] Transient error (${W.message}), retry ${X+1}/${u$.MAX_TRANSIENT_RETRIES}`),await new Promise((V)=>setTimeout(V,u$.RETRY_DELAY_MS*(X+1)));continue}break}$.abort(`Tool execution failed: ${W.message}`)}isTransientError($){let Z=$.message;return u$.TRANSIENT_ERRORS.some((J)=>Z.includes(J))}}class o5{name="formatting";async process($){try{let Z=$.getResult();if(!Z.llmContent)Z.llmContent="Execution completed";if(!Z.metadata)Z.metadata={};Z.metadata.executionId=$.context.sessionId,Z.metadata.toolName=$.toolName,Z.metadata.timestamp=Date.now(),$.setResult(Z)}catch(Z){$.abort(`Result formatting failed: ${Z.message}`)}}}import{execFile as c6}from"node:child_process";import d0 from"node:path";import{promisify as l6}from"node:util";import{execFile as h6}from"node:child_process";import{existsSync as e5}from"node:fs";import g$ from"node:path";import{promisify as p6}from"node:util";var d6=p6(h6),t5=M("Execution");class m${static instance=null;cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??m6}static getInstance(){if(!m$.instance)m$.instance=new m$;return m$.instance}static resetInstance(){m$.instance=null}async verify($,Z){let J=u6($,Z);if(!J)return null;let W=Date.now(),X=this.cache.get(J);if(X&&W-X.at<this.cacheMs)return t5.debug(`[VerifyQueue] cache hit: ${J}`),X.result;let Y=this.running.get(J);if(!Y)Y=this.runTypeCheck(J).finally(()=>{this.running.delete(J)}),this.running.set(J,Y);else t5.debug(`[VerifyQueue] coalescing into running check: ${J}`);let V=await Y;return this.cache.set(J,{result:V,at:Date.now()}),V}clearCache(){this.cache.clear()}async runTypeCheck($){let{cmd:Z,args:J}=g6($);t5.debug(`[VerifyQueue] running: ${Z} ${J.join(" ")} in ${$}`);let{stdout:W,stderr:X,exitCode:Y,timedOut:V}=await this.runCommand(Z,J,$,this.timeoutMs),B=`${W}
1307
- ${X}`.trim();return{hasErrors:Y!==0&&!V,rawOutput:B,timedOut:V,workspaceRoot:$}}}function u6($,Z){let J=g$.isAbsolute($)?$:g$.resolve(Z,$),W=g$.dirname(J),X=g$.parse(W).root;while(W!==X){if(e5(g$.join(W,"tsconfig.json")))return W;W=g$.dirname(W)}if(e5(g$.join(Z,"tsconfig.json")))return Z;return null}function g6($){let Z=g$.join($,"package.json");if(e5(Z))try{if(s$(Z)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function m6($,Z,J,W){try{let{stdout:X,stderr:Y}=await d6($,Z,{cwd:J,timeout:W,encoding:"utf-8",maxBuffer:4194304});return{stdout:X,stderr:Y,exitCode:0,timedOut:!1}}catch(X){let Y=X,V=Y.killed===!0||Y.signal==="SIGTERM",B=typeof Y.code==="number"?Y.code:1;return{stdout:Y.stdout??"",stderr:Y.stderr??"",exitCode:B,timedOut:V}}}var i6=l6(c6),J9=M("Execution"),a6=new Set(["Edit","Write"]),$8=15,n6=5000;function r6($,Z){let J=$.split(`
1308
- `),W=d0.basename(Z),X=d0.isAbsolute(Z)?Z:d0.resolve(Z);return J.filter((Y)=>Y.includes(W)||Y.includes(X))}async function s6($,Z){try{return await i6("npx",["biome","lint","--max-diagnostics=5",$],{cwd:Z,timeout:n6,encoding:"utf-8"}),null}catch(J){let W=J;if(W.killed)return null;let X=(W.stdout||"")+(W.stderr||"");if(X.includes("error"))return X.trim();return null}}class Z8{queue;name="auto-verify";constructor($=m$.getInstance()){this.queue=$}async process($){if(!a6.has($.toolName))return;let Z=$.getResult();if(!Z||!Z.success)return;let J=$.params.file_path||$.params.path;if(!J)return;let W=$.context.workspaceRoot||N(),X=[];try{let B=await this.queue.verify(J,W);if(B&&!B.timedOut&&B.hasErrors){let K=r6(B.rawOutput,J);if(K.length>0){let Q=K.slice(0,$8);X.push(`Type errors:
1309
- ${Q.join(`
1310
- `)}`+(K.length>$8?`
1311
- ... (+${K.length-$8} more)`:""))}}}catch(B){J9.debug(`[AutoVerify] type-check failed: ${B instanceof Error?B.message:String(B)}`)}if(J.endsWith(".ts")||J.endsWith(".tsx")||J.endsWith(".js")){let B=await s6(J,W);if(B){let K=B.split(`
1306
+ ... (还有 ${Y.length-X} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Z){let J=[];if($.name==="Bash"){let W=Z.command||"";if(W.includes("rm"))J.push("[WARN] 此命令可能删除文件");if(W.includes("sudo"))J.push("[WARN] 此命令需要管理员权限");if(W.includes("git push"))J.push("[WARN] 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")J.push("此操作将修改文件内容");else if($.name==="Delete")J.push("此操作将永久删除文件");return J}}class g${name="execution";static TRANSIENT_ERRORS=["EBUSY","EAGAIN","EMFILE","ENFILE"];static MAX_TRANSIENT_RETRIES=2;static RETRY_DELAY_MS=200;async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}let J=Date.now(),W;for(let X=0;X<=g$.MAX_TRANSIENT_RETRIES;X++)try{let Y=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);if(!Y.metadata)Y.metadata={};if(Y.metadata.duration=Date.now()-J,X>0)Y.metadata.retriedAttempts=X;$.setResult(Y);return}catch(Y){if(W=Y,X<g$.MAX_TRANSIENT_RETRIES&&this.isTransientError(W)){Y$.debug(`[ExecutionStage] Transient error (${W.message}), retry ${X+1}/${g$.MAX_TRANSIENT_RETRIES}`),await new Promise((V)=>setTimeout(V,g$.RETRY_DELAY_MS*(X+1)));continue}break}$.abort(`Tool execution failed: ${W.message}`)}isTransientError($){let Z=$.message;return g$.TRANSIENT_ERRORS.some((J)=>Z.includes(J))}}class o5{name="formatting";async process($){try{let Z=$.getResult();if(!Z.llmContent)Z.llmContent="Execution completed";if(!Z.metadata)Z.metadata={};Z.metadata.executionId=$.context.sessionId,Z.metadata.toolName=$.toolName,Z.metadata.timestamp=Date.now(),$.setResult(Z)}catch(Z){$.abort(`Result formatting failed: ${Z.message}`)}}}import{execFile as c6}from"node:child_process";import{existsSync as l6}from"node:fs";import F$ from"node:path";import{promisify as i6}from"node:util";import{execFile as h6}from"node:child_process";import{existsSync as e5}from"node:fs";import m$ from"node:path";import{promisify as p6}from"node:util";var d6=p6(h6),t5=M("Execution");class c${static instance=null;cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??m6}static getInstance(){if(!c$.instance)c$.instance=new c$;return c$.instance}static resetInstance(){c$.instance=null}async verify($,Z){let J=u6($,Z);if(!J)return null;let W=Date.now(),X=this.cache.get(J);if(X&&W-X.at<this.cacheMs)return t5.debug(`[VerifyQueue] cache hit: ${J}`),X.result;let Y=this.running.get(J);if(!Y)Y=this.runTypeCheck(J).finally(()=>{this.running.delete(J)}),this.running.set(J,Y);else t5.debug(`[VerifyQueue] coalescing into running check: ${J}`);let V=await Y;return this.cache.set(J,{result:V,at:Date.now()}),V}clearCache(){this.cache.clear()}async runTypeCheck($){let{cmd:Z,args:J}=g6($);t5.debug(`[VerifyQueue] running: ${Z} ${J.join(" ")} in ${$}`);let{stdout:W,stderr:X,exitCode:Y,timedOut:V}=await this.runCommand(Z,J,$,this.timeoutMs),B=`${W}
1307
+ ${X}`.trim();return{hasErrors:Y!==0&&!V,rawOutput:B,timedOut:V,workspaceRoot:$}}}function u6($,Z){let J=m$.isAbsolute($)?$:m$.resolve(Z,$),W=m$.dirname(J),X=m$.parse(W).root;while(W!==X){if(e5(m$.join(W,"tsconfig.json")))return W;W=m$.dirname(W)}if(e5(m$.join(Z,"tsconfig.json")))return Z;return null}function g6($){let Z=m$.join($,"package.json");if(e5(Z))try{if(o$(Z)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function m6($,Z,J,W){try{let{stdout:X,stderr:Y}=await d6($,Z,{cwd:J,timeout:W,encoding:"utf-8",maxBuffer:4194304});return{stdout:X,stderr:Y,exitCode:0,timedOut:!1}}catch(X){let Y=X,V=Y.killed===!0||Y.signal==="SIGTERM",B=typeof Y.code==="number"?Y.code:1;return{stdout:Y.stdout??"",stderr:Y.stderr??"",exitCode:B,timedOut:V}}}var a6=i6(c6),J9=M("Execution"),n6=new Set(["Edit","Write"]),$8=15,r6=5000;function s6($,Z){let J=$.split(`
1308
+ `),W=F$.basename(Z),X=F$.isAbsolute(Z)?Z:F$.resolve(Z);return J.filter((Y)=>Y.includes(W)||Y.includes(X))}async function o6($,Z){try{return await a6("npx",["biome","lint","--max-diagnostics=5",$],{cwd:Z,timeout:r6,encoding:"utf-8"}),null}catch(J){let W=J;if(W.killed)return null;let X=(W.stdout||"")+(W.stderr||"");if(X.includes("error"))return X.trim();return null}}function t6($){if($.includes(".test.")||$.includes(".spec.")||$.includes("__tests__"))return null;let Z=F$.dirname($),J=F$.extname($),W=F$.basename($,J),X=[F$.join(Z,`${W}.test${J}`),F$.join(Z,`${W}.spec${J}`),F$.join(Z,"__tests__",`${W}.test${J}`),F$.join(Z,"..","tests",`${W}.test${J}`)];for(let Y of X)if(l6(Y))return Y;return null}class Z8{queue;name="auto-verify";constructor($=c$.getInstance()){this.queue=$}async process($){if(!n6.has($.toolName))return;let Z=$.getResult();if(!Z||!Z.success)return;let J=$.params.file_path||$.params.path;if(!J)return;let W=$.context.workspaceRoot||N(),X=[];try{let K=await this.queue.verify(J,W);if(K&&!K.timedOut&&K.hasErrors){let Q=s6(K.rawOutput,J);if(Q.length>0){let U=Q.slice(0,$8);X.push(`Type errors:
1309
+ ${U.join(`
1310
+ `)}`+(Q.length>$8?`
1311
+ ... (+${Q.length-$8} more)`:""))}}}catch(K){J9.debug(`[AutoVerify] type-check failed: ${K instanceof Error?K.message:String(K)}`)}if(J.endsWith(".ts")||J.endsWith(".tsx")||J.endsWith(".js")){let K=await o6(J,W);if(K){let Q=K.split(`
1312
1312
  `).slice(0,5);X.push(`Lint errors:
1313
- ${K.join(`
1314
- `)}`)}}if(X.length===0)return;let Y=`
1313
+ ${Q.join(`
1314
+ `)}`)}}let Y=t6(J);if(Y)X.push(`Related test: ${Y}`);if(X.length===0)return;let V=`
1315
1315
 
1316
1316
  ---
1317
- **Auto-Verify: issues in ${d0.basename(J)}:**
1317
+ **Auto-Verify: issues in ${F$.basename(J)}:**
1318
1318
  \`\`\`
1319
1319
  `+X.join(`
1320
1320
 
1321
- `)+"\n```",V=typeof Z.llmContent==="string"?Z.llmContent:Z.llmContent?JSON.stringify(Z.llmContent):"";Z.llmContent=`${V}${Y}`,J9.info(`[AutoVerify] injected ${X.length} diagnostic(s) (${d0.basename(J)})`)}}class J8{name="validation";toolWhitelist;toolBlacklist;constructor($,Z){this.toolWhitelist=$?.length?new Set($):null,this.toolBlacklist=Z?.length?new Set(Z):null}async process($){let Z=$._internal.tool;if(!Z){$.abort("Discovery stage failed; cannot perform validation");return}if(this.toolBlacklist?.has(Z.name)){$.abort(`Tool "${Z.name}" is blocked by --disallowed-tools`);return}if(this.toolWhitelist&&!this.toolWhitelist.has(Z.name)){$.abort(`Tool "${Z.name}" is not in --allowed-tools whitelist`);return}try{let J=Z.build($.params);$._internal.invocation=J}catch(J){$.abort(`Parameter validation failed: ${J.message}`)}}}var W8={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},X8={"--since":"string","--after":"string","--until":"string","--before":"string"},Y8={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},L1={"--max-count":"number","-n":"number"},E1={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},N0={"--color":"none","--no-color":"none"},_1={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},W9={"--author":"string","--committer":"string","--grep":"string"},A1={"--format":"string","--pretty":"string"},o6={"git diff":{safeFlags:{...E1,...N0,..._1,"--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:{...W8,...X8,...Y8,...L1,...E1,...N0,..._1,...W9,...A1,"--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:{...E1,...N0,..._1,...A1,"--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:{...W8,...X8,...L1,...W9,"-s":"none","--summary":"none","-n":"number","--numbered":"none","-e":"none","--email":"none","--group":"string","--format":"string"}},"git reflog":{safeFlags:{...Y8,...L1,...N0,...A1,"--date":"string"},isDangerousCallback:($,Z)=>{let J=new Set(["expire","delete","exists"]);for(let W of Z)if(J.has(W))return!0;return!1}},"git stash list":{safeFlags:{...Y8,...N0,...A1}},"git stash show":{safeFlags:{...E1,...N0,..._1,"-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:($,Z)=>{let J=Z.filter((W)=>!W.startsWith("-"));if(J.length!==1)return!0;return!/^[a-zA-Z0-9_.-]+$/.test(J[0])}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},isDangerousCallback:($,Z)=>{return Z.filter((W)=>!W.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:{...W8,...X8,...L1,"--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:($,Z)=>{if(Z.some((X)=>X==="-l"||X==="--list"))return!1;return Z.filter((X)=>!X.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:($,Z)=>{let J=new Set(["-l","--list","-a","--all","-r","--remotes","--show-current"]);if(Z.some((V)=>J.has(V)))return!1;let X=new Set(["-d","-D","-m","-M","-c","--copy","--delete","--move","--set-upstream-to","--unset-upstream","--edit-description"]);if(Z.some((V)=>X.has(V.split("=")[0])))return!0;return Z.filter((V)=>!V.startsWith("-")).length>0}}};function f($,Z){for(let J of Z){if(J.includes("://")||J.includes("@"))return!0;if((J.match(/\//g)||[]).length>=2)return!0}return!1}var h={"--json":"string","--jq":"string","--template":"string","-q":"none","--limit":"number","-L":"number","--web":"none","-w":"none","--comments":"none"},t6={"gh pr view":{safeFlags:{...h},isDangerousCallback:f},"gh pr list":{safeFlags:{...h,"--state":"string","-s":"string","--author":"string","--label":"string","--base":"string","--head":"string","--search":"string","--assignee":"string","--draft":"none"},isDangerousCallback:f},"gh pr diff":{safeFlags:{...h,"--color":"string","--patch":"none","--name-only":"none"},isDangerousCallback:f},"gh pr checks":{safeFlags:{...h,"--watch":"none","--fail-fast":"none","--required":"none"},isDangerousCallback:f},"gh pr status":{safeFlags:{...h},isDangerousCallback:f},"gh issue view":{safeFlags:{...h},isDangerousCallback:f},"gh issue list":{safeFlags:{...h,"--state":"string","-s":"string","--author":"string","--label":"string","--search":"string","--assignee":"string","--milestone":"string"},isDangerousCallback:f},"gh issue status":{safeFlags:{...h},isDangerousCallback:f},"gh repo view":{safeFlags:{...h},isDangerousCallback:f},"gh run list":{safeFlags:{...h,"--workflow":"string","-w":"string","--branch":"string","-b":"string","--status":"string","-s":"string","--user":"string","-u":"string","--event":"string","-e":"string"},isDangerousCallback:f},"gh run view":{safeFlags:{...h,"--log":"none","--log-failed":"none","--exit-status":"none","--verbose":"none","-v":"none","--job":"string","-j":"string"},isDangerousCallback:f},"gh auth status":{safeFlags:{"--hostname":"string","-h":"string","--active":"none"},isDangerousCallback:($,Z)=>{return Z.some((J)=>J==="--show-token"||J==="-t")}},"gh release list":{safeFlags:{...h,"--exclude-drafts":"none","--exclude-pre-releases":"none"},isDangerousCallback:f},"gh release view":{safeFlags:{...h},isDangerousCallback:f},"gh workflow list":{safeFlags:{...h,"--all":"none","-a":"none"},isDangerousCallback:f},"gh workflow view":{safeFlags:{...h,"--yaml":"none","-y":"none","--ref":"string","-r":"string"},isDangerousCallback:f},"gh label list":{safeFlags:{...h,"--search":"string","--sort":"string","--order":"string"},isDangerousCallback:f},"gh search repos":{safeFlags:{...h,"--language":"string","--topic":"string","--sort":"string","--order":"string","--match":"string","--owner":"string","--visibility":"string"},isDangerousCallback:f},"gh search issues":{safeFlags:{...h,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:f},"gh search prs":{safeFlags:{...h,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:f},"gh search commits":{safeFlags:{...h,"--sort":"string","--order":"string","--author":"string","--committer":"string","--repo":"string"},isDangerousCallback:f},"gh search code":{safeFlags:{...h,"--language":"string","--filename":"string","--extension":"string","--repo":"string","--match":"string"},isDangerousCallback:f}},e6={"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"}}},$Z={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"}}},ZZ={...o6,...t6,...e6,...$Z,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:($,Z)=>{for(let J of Z){if(J==="-i"||J.startsWith("-i")||J==="--in-place")return!0;if(/\bw\s/.test(J)||/\bw$/.test(J))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 JZ($){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${Z}(?:\\s|$)[^<>()$\`|{}&;\\n\\r]*$`)}var WZ=["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"],XZ=[/^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*$/],YZ=[...WZ.map(JZ),...XZ];function R1($,Z){switch(Z){case"none":return!1;case"number":return/^\d+$/.test($);case"string":return!0}}function VZ($,Z,J){let W=Z,X=J.respectsDoubleDash!==!1;while(W<$.length){let Y=$[W];if(Y==="--"&&X)break;if(!Y.startsWith("-")){W++;continue}if(Y.startsWith("--")){let Q=Y.indexOf("="),U=Q!==-1,q=U?Y.substring(0,Q):Y,H=J.safeFlags[q];if(H===void 0)return!1;if(H==="none"){if(U)return!1;W++;continue}if(U){let G=Y.substring(Q+1);if(!R1(G,H))return!1;W++}else{if(W++,W>=$.length)return!1;let G=$[W];if(H==="string"&&G.startsWith("-")){if(q!=="--sort")return!1}if(!R1(G,H))return!1;W++}continue}let V=Y;if(/^-\d+$/.test(V)){W++;continue}let B=J.safeFlags[V];if(B!==void 0){if(B==="none"){W++;continue}if(W++,W>=$.length)return!1;let Q=$[W];if(!R1(Q,B))return!1;W++;continue}let K=V.indexOf("=");if(K!==-1){let Q=V.substring(0,K),U=J.safeFlags[Q];if(U===void 0)return!1;let q=V.substring(K+1);if(U!=="none"&&!R1(q,U))return!1;W++;continue}if(/^-[A-Za-z]\d+$/.test(V)){let Q=V.substring(0,2);if(J.safeFlags[Q]==="number"){W++;continue}}if(/^-[A-Za-z]{2,}$/.test(V)){let Q=!0;for(let U=1;U<V.length;U++){let q=`-${V[U]}`;if(J.safeFlags[q]!=="none"){Q=!1;break}}if(Q){W++;continue}}return!1}return!0}function BZ($){for(let Z=Math.min(3,$.length);Z>=1;Z--){let J=$.slice(0,Z).join(" "),W=ZZ[J];if(W)return[J,W,Z]}return null}function KZ($){let Z=f4($);if(Z.length===0)return!1;let J=BZ(Z);if(!J)return!1;let[W,X,Y]=J,V=Z.slice(Y);for(let B of V)if(B.includes("$"))return!1;for(let B of V)if(B.includes("{")&&(B.includes(",")||B.includes("..")))return!1;if(!VZ(Z,Y,X))return!1;if(X.regex&&!X.regex.test($))return!1;if(X.isDangerousCallback&&X.isDangerousCallback($,V))return!1;if(W==="grep"||W==="rg"){for(let B of V)if(B.includes(`
1322
- `)||B.includes("\r"))return!1}return!0}function QZ($){for(let Z of YZ)if(Z.test($))return!0;return!1}function UZ($){let Z=!1,J=!1,W=!1;for(let X=0;X<$.length;X++){let Y=$[X];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let V=$[X+1];if(V&&/[A-Za-z_@*#?!$0-9({-]/.test(V))return!0}if(Y==="`")return!0}return!1}function qZ($){let Z=$.replace(/\s+2>&1\s*$/,"").trim();if(!Z)return!1;if(UZ(Z))return!1;if(KZ(Z))return!0;if(QZ(Z)){if(/\bgit\b/.test(Z)){if(/\s-c\s/.test(Z)||/--exec-path/.test(Z)||/--config-env/.test(Z))return!1}return!0}return!1}function X9($){let Z=$.trim();if(!Z)return!1;let J=x4(Z);if(J===null)return!1;if(J.length>1){let W=!1,X=!1;for(let Y of J){let V=X0(h$(Y.trim()));if(/^cd\b/.test(V))W=!0;if(/\bgit\b/.test(V))X=!0}if(W&&X)return!1}for(let W of J){let X=W.trim();if(!X)continue;let Y=X0(h$(X));if(!Y)return!1;if(!qZ(Y))return!1}return!0}import HZ from"node:os";import V8 from"node:path";class B8{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 Z=this.normalizePath($),J=V8.basename(Z);for(let W of this.SENSITIVE_PATTERNS)if(this.matchPattern(J,W.pattern))return{isSensitive:!0,level:W.level,matchedPattern:W.pattern instanceof RegExp?W.pattern.source:W.pattern,reason:W.description};for(let W of this.SENSITIVE_PATHS)if(this.matchPattern(Z,W.path))return{isSensitive:!0,level:W.level,matchedPattern:W.path instanceof RegExp?W.path.source:W.path,reason:W.description};return{isSensitive:!1}}static checkMultiple($){let Z=new Map;for(let J of $)Z.set(J,this.check(J));return Z}static filterSensitive($,Z="low"){let J={["high"]:3,["medium"]:2,["low"]:1},W=J[Z];return $.map((X)=>({path:X,result:this.check(X)})).filter(({result:X})=>X.isSensitive&&X.level&&J[X.level]>=W)}static normalizePath($){if($.startsWith("~/")||$==="~")return V8.join(HZ.homedir(),$.slice(1));return V8.resolve($)}static matchPattern($,Z){if(Z instanceof RegExp)return Z.test($);let J=Z.replace(/\*/g,".*");return new RegExp(`^${J}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class Q8{name="rule-permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,Z,J){this.permissionChecker=new V0($),this.sessionApprovals=Z,this.defaultPermissionMode=J}getPermissionChecker(){return this.permissionChecker}async process($){let{tool:Z,invocation:J}=$._internal;if(!Z||!J){$.abort("Validation stage failed; cannot perform permission check");return}try{let W=J.getAffectedPaths(),X={toolName:Z.name,params:$.params,affectedPaths:W,tool:Z},Y=V0.buildSignature(X);$._internal.permissionSignature=Y;let V=this.permissionChecker.check(X);if(V.result==="ask"&&!V.matchedRule&&Z.name==="Bash"&&typeof $.params.command==="string"){if(X9($.params.command))V={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"}}let B=$.context.permissionMode||this.defaultPermissionMode;if(V=this.applyModeOverrides(Z.kind,V,B),V.result==="ask"&&this.sessionApprovals.has(Y))V={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};if(V=this.applySafetyOverrides(W,V,$),$.shouldAbort())return;$._internal.ruleDecision=GZ(V)}catch(W){$.abort(`Permission check failed: ${W.message}`)}}applyModeOverrides($,Z,J){if(J==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(J==="plan"){if(!K8($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"}}if(Z.result==="deny")return Z;if(Z.result==="allow")return Z;if(K8($))return{result:"allow",matchedRule:`mode:${J}:readonly`,reason:"Read-only tools do not require confirmation"};if(J==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}applySafetyOverrides($,Z,J){if(!$||$.length===0)return Z;let W=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],X=$.filter((K)=>{if(K.includes(".."))return!0;return W.some((Q)=>K.includes(Q))});if(X.length>0)return J.abort(`Access to dangerous system paths denied: ${X.join(", ")}`),Z;let Y=B8.filterSensitive($,"medium");if(Y.length===0)return Z;let V=Y.map(({path:K,result:Q})=>`${K} (${Q.level}: ${Q.reason})`);if(Y.filter(({result:K})=>K.level==="high").length>0&&Z.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
1321
+ `)+"\n```",B=typeof Z.llmContent==="string"?Z.llmContent:Z.llmContent?JSON.stringify(Z.llmContent):"";Z.llmContent=`${B}${V}`,J9.info(`[AutoVerify] injected ${X.length} diagnostic(s) (${F$.basename(J)})`)}}class J8{name="validation";toolWhitelist;toolBlacklist;constructor($,Z){this.toolWhitelist=$?.length?new Set($):null,this.toolBlacklist=Z?.length?new Set(Z):null}async process($){let Z=$._internal.tool;if(!Z){$.abort("Discovery stage failed; cannot perform validation");return}if(this.toolBlacklist?.has(Z.name)){$.abort(`Tool "${Z.name}" is blocked by --disallowed-tools`);return}if(this.toolWhitelist&&!this.toolWhitelist.has(Z.name)){$.abort(`Tool "${Z.name}" is not in --allowed-tools whitelist`);return}try{let J=Z.build($.params);$._internal.invocation=J}catch(J){$.abort(`Parameter validation failed: ${J.message}`)}}}var W8={"--all":"none","--branches":"none","--tags":"none","--remotes":"none"},X8={"--since":"string","--after":"string","--until":"string","--before":"string"},Y8={"--oneline":"none","--graph":"none","--decorate":"none","--no-decorate":"none","--date":"string","--relative-date":"none"},L1={"--max-count":"number","-n":"number"},E1={"--stat":"none","--numstat":"none","--shortstat":"none","--name-only":"none","--name-status":"none"},D0={"--color":"none","--no-color":"none"},_1={"--patch":"none","-p":"none","--no-patch":"none","--no-ext-diff":"none","-s":"none"},W9={"--author":"string","--committer":"string","--grep":"string"},A1={"--format":"string","--pretty":"string"},e6={"git diff":{safeFlags:{...E1,...D0,..._1,"--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:{...W8,...X8,...Y8,...L1,...E1,...D0,..._1,...W9,...A1,"--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:{...E1,...D0,..._1,...A1,"--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:{...W8,...X8,...L1,...W9,"-s":"none","--summary":"none","-n":"number","--numbered":"none","-e":"none","--email":"none","--group":"string","--format":"string"}},"git reflog":{safeFlags:{...Y8,...L1,...D0,...A1,"--date":"string"},isDangerousCallback:($,Z)=>{let J=new Set(["expire","delete","exists"]);for(let W of Z)if(J.has(W))return!0;return!1}},"git stash list":{safeFlags:{...Y8,...D0,...A1}},"git stash show":{safeFlags:{...E1,...D0,..._1,"-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:($,Z)=>{let J=Z.filter((W)=>!W.startsWith("-"));if(J.length!==1)return!0;return!/^[a-zA-Z0-9_.-]+$/.test(J[0])}},"git remote":{safeFlags:{"-v":"none","--verbose":"none"},isDangerousCallback:($,Z)=>{return Z.filter((W)=>!W.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:{...W8,...X8,...L1,"--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:($,Z)=>{if(Z.some((X)=>X==="-l"||X==="--list"))return!1;return Z.filter((X)=>!X.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:($,Z)=>{let J=new Set(["-l","--list","-a","--all","-r","--remotes","--show-current"]);if(Z.some((V)=>J.has(V)))return!1;let X=new Set(["-d","-D","-m","-M","-c","--copy","--delete","--move","--set-upstream-to","--unset-upstream","--edit-description"]);if(Z.some((V)=>X.has(V.split("=")[0])))return!0;return Z.filter((V)=>!V.startsWith("-")).length>0}}};function f($,Z){for(let J of Z){if(J.includes("://")||J.includes("@"))return!0;if((J.match(/\//g)||[]).length>=2)return!0}return!1}var h={"--json":"string","--jq":"string","--template":"string","-q":"none","--limit":"number","-L":"number","--web":"none","-w":"none","--comments":"none"},$Z={"gh pr view":{safeFlags:{...h},isDangerousCallback:f},"gh pr list":{safeFlags:{...h,"--state":"string","-s":"string","--author":"string","--label":"string","--base":"string","--head":"string","--search":"string","--assignee":"string","--draft":"none"},isDangerousCallback:f},"gh pr diff":{safeFlags:{...h,"--color":"string","--patch":"none","--name-only":"none"},isDangerousCallback:f},"gh pr checks":{safeFlags:{...h,"--watch":"none","--fail-fast":"none","--required":"none"},isDangerousCallback:f},"gh pr status":{safeFlags:{...h},isDangerousCallback:f},"gh issue view":{safeFlags:{...h},isDangerousCallback:f},"gh issue list":{safeFlags:{...h,"--state":"string","-s":"string","--author":"string","--label":"string","--search":"string","--assignee":"string","--milestone":"string"},isDangerousCallback:f},"gh issue status":{safeFlags:{...h},isDangerousCallback:f},"gh repo view":{safeFlags:{...h},isDangerousCallback:f},"gh run list":{safeFlags:{...h,"--workflow":"string","-w":"string","--branch":"string","-b":"string","--status":"string","-s":"string","--user":"string","-u":"string","--event":"string","-e":"string"},isDangerousCallback:f},"gh run view":{safeFlags:{...h,"--log":"none","--log-failed":"none","--exit-status":"none","--verbose":"none","-v":"none","--job":"string","-j":"string"},isDangerousCallback:f},"gh auth status":{safeFlags:{"--hostname":"string","-h":"string","--active":"none"},isDangerousCallback:($,Z)=>{return Z.some((J)=>J==="--show-token"||J==="-t")}},"gh release list":{safeFlags:{...h,"--exclude-drafts":"none","--exclude-pre-releases":"none"},isDangerousCallback:f},"gh release view":{safeFlags:{...h},isDangerousCallback:f},"gh workflow list":{safeFlags:{...h,"--all":"none","-a":"none"},isDangerousCallback:f},"gh workflow view":{safeFlags:{...h,"--yaml":"none","-y":"none","--ref":"string","-r":"string"},isDangerousCallback:f},"gh label list":{safeFlags:{...h,"--search":"string","--sort":"string","--order":"string"},isDangerousCallback:f},"gh search repos":{safeFlags:{...h,"--language":"string","--topic":"string","--sort":"string","--order":"string","--match":"string","--owner":"string","--visibility":"string"},isDangerousCallback:f},"gh search issues":{safeFlags:{...h,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:f},"gh search prs":{safeFlags:{...h,"--sort":"string","--order":"string","--match":"string","--state":"string","--label":"string","--language":"string","--author":"string","--assignee":"string","--repo":"string"},isDangerousCallback:f},"gh search commits":{safeFlags:{...h,"--sort":"string","--order":"string","--author":"string","--committer":"string","--repo":"string"},isDangerousCallback:f},"gh search code":{safeFlags:{...h,"--language":"string","--filename":"string","--extension":"string","--repo":"string","--match":"string"},isDangerousCallback:f}},ZZ={"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"}}},JZ={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"}}},WZ={...e6,...$Z,...ZZ,...JZ,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:($,Z)=>{for(let J of Z){if(J==="-i"||J.startsWith("-i")||J==="--in-place")return!0;if(/\bw\s/.test(J)||/\bw$/.test(J))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 XZ($){let Z=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${Z}(?:\\s|$)[^<>()$\`|{}&;\\n\\r]*$`)}var YZ=["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"],VZ=[/^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*$/],BZ=[...YZ.map(XZ),...VZ];function R1($,Z){switch(Z){case"none":return!1;case"number":return/^\d+$/.test($);case"string":return!0}}function KZ($,Z,J){let W=Z,X=J.respectsDoubleDash!==!1;while(W<$.length){let Y=$[W];if(Y==="--"&&X)break;if(!Y.startsWith("-")){W++;continue}if(Y.startsWith("--")){let Q=Y.indexOf("="),U=Q!==-1,q=U?Y.substring(0,Q):Y,H=J.safeFlags[q];if(H===void 0)return!1;if(H==="none"){if(U)return!1;W++;continue}if(U){let G=Y.substring(Q+1);if(!R1(G,H))return!1;W++}else{if(W++,W>=$.length)return!1;let G=$[W];if(H==="string"&&G.startsWith("-")){if(q!=="--sort")return!1}if(!R1(G,H))return!1;W++}continue}let V=Y;if(/^-\d+$/.test(V)){W++;continue}let B=J.safeFlags[V];if(B!==void 0){if(B==="none"){W++;continue}if(W++,W>=$.length)return!1;let Q=$[W];if(!R1(Q,B))return!1;W++;continue}let K=V.indexOf("=");if(K!==-1){let Q=V.substring(0,K),U=J.safeFlags[Q];if(U===void 0)return!1;let q=V.substring(K+1);if(U!=="none"&&!R1(q,U))return!1;W++;continue}if(/^-[A-Za-z]\d+$/.test(V)){let Q=V.substring(0,2);if(J.safeFlags[Q]==="number"){W++;continue}}if(/^-[A-Za-z]{2,}$/.test(V)){let Q=!0;for(let U=1;U<V.length;U++){let q=`-${V[U]}`;if(J.safeFlags[q]!=="none"){Q=!1;break}}if(Q){W++;continue}}return!1}return!0}function QZ($){for(let Z=Math.min(3,$.length);Z>=1;Z--){let J=$.slice(0,Z).join(" "),W=WZ[J];if(W)return[J,W,Z]}return null}function UZ($){let Z=f4($);if(Z.length===0)return!1;let J=QZ(Z);if(!J)return!1;let[W,X,Y]=J,V=Z.slice(Y);for(let B of V)if(B.includes("$"))return!1;for(let B of V)if(B.includes("{")&&(B.includes(",")||B.includes("..")))return!1;if(!KZ(Z,Y,X))return!1;if(X.regex&&!X.regex.test($))return!1;if(X.isDangerousCallback&&X.isDangerousCallback($,V))return!1;if(W==="grep"||W==="rg"){for(let B of V)if(B.includes(`
1322
+ `)||B.includes("\r"))return!1}return!0}function qZ($){for(let Z of BZ)if(Z.test($))return!0;return!1}function HZ($){let Z=!1,J=!1,W=!1;for(let X=0;X<$.length;X++){let Y=$[X];if(W){W=!1;continue}if(Y==="\\"&&!Z){W=!0;continue}if(Y==="'"&&!J){Z=!Z;continue}if(Y==='"'&&!Z){J=!J;continue}if(Z)continue;if(Y==="$"){let V=$[X+1];if(V&&/[A-Za-z_@*#?!$0-9({-]/.test(V))return!0}if(Y==="`")return!0}return!1}function GZ($){let Z=$.replace(/\s+2>&1\s*$/,"").trim();if(!Z)return!1;if(HZ(Z))return!1;if(UZ(Z))return!0;if(qZ(Z)){if(/\bgit\b/.test(Z)){if(/\s-c\s/.test(Z)||/--exec-path/.test(Z)||/--config-env/.test(Z))return!1}return!0}return!1}function X9($){let Z=$.trim();if(!Z)return!1;let J=x4(Z);if(J===null)return!1;if(J.length>1){let W=!1,X=!1;for(let Y of J){let V=Y0(p$(Y.trim()));if(/^cd\b/.test(V))W=!0;if(/\bgit\b/.test(V))X=!0}if(W&&X)return!1}for(let W of J){let X=W.trim();if(!X)continue;let Y=Y0(p$(X));if(!Y)return!1;if(!GZ(Y))return!1}return!0}import FZ from"node:os";import V8 from"node:path";class B8{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 Z=this.normalizePath($),J=V8.basename(Z);for(let W of this.SENSITIVE_PATTERNS)if(this.matchPattern(J,W.pattern))return{isSensitive:!0,level:W.level,matchedPattern:W.pattern instanceof RegExp?W.pattern.source:W.pattern,reason:W.description};for(let W of this.SENSITIVE_PATHS)if(this.matchPattern(Z,W.path))return{isSensitive:!0,level:W.level,matchedPattern:W.path instanceof RegExp?W.path.source:W.path,reason:W.description};return{isSensitive:!1}}static checkMultiple($){let Z=new Map;for(let J of $)Z.set(J,this.check(J));return Z}static filterSensitive($,Z="low"){let J={["high"]:3,["medium"]:2,["low"]:1},W=J[Z];return $.map((X)=>({path:X,result:this.check(X)})).filter(({result:X})=>X.isSensitive&&X.level&&J[X.level]>=W)}static normalizePath($){if($.startsWith("~/")||$==="~")return V8.join(FZ.homedir(),$.slice(1));return V8.resolve($)}static matchPattern($,Z){if(Z instanceof RegExp)return Z.test($);let J=Z.replace(/\*/g,".*");return new RegExp(`^${J}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}class Q8{name="rule-permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,Z,J){this.permissionChecker=new B0($),this.sessionApprovals=Z,this.defaultPermissionMode=J}getPermissionChecker(){return this.permissionChecker}async process($){let{tool:Z,invocation:J}=$._internal;if(!Z||!J){$.abort("Validation stage failed; cannot perform permission check");return}try{let W=J.getAffectedPaths(),X={toolName:Z.name,params:$.params,affectedPaths:W,tool:Z},Y=B0.buildSignature(X);$._internal.permissionSignature=Y;let V=this.permissionChecker.check(X);if(V.result==="ask"&&!V.matchedRule&&Z.name==="Bash"&&typeof $.params.command==="string"){if(X9($.params.command))V={result:"allow",matchedRule:"builtin:read-only-command",reason:"Command classified as read-only, auto-approved"}}let B=$.context.permissionMode||this.defaultPermissionMode;if(V=this.applyModeOverrides(Z.kind,V,B),V.result==="ask"&&this.sessionApprovals.has(Y))V={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};if(V=this.applySafetyOverrides(W,V,$),$.shouldAbort())return;$._internal.ruleDecision=OZ(V)}catch(W){$.abort(`Permission check failed: ${W.message}`)}}applyModeOverrides($,Z,J){if(J==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(J==="plan"){if(!K8($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed"}}if(Z.result==="deny")return Z;if(Z.result==="allow")return Z;if(K8($))return{result:"allow",matchedRule:`mode:${J}:readonly`,reason:"Read-only tools do not require confirmation"};if(J==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Z}applySafetyOverrides($,Z,J){if(!$||$.length===0)return Z;let W=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],X=$.filter((K)=>{if(K.includes(".."))return!0;return W.some((Q)=>K.includes(Q))});if(X.length>0)return J.abort(`Access to dangerous system paths denied: ${X.join(", ")}`),Z;let Y=B8.filterSensitive($,"medium");if(Y.length===0)return Z;let V=Y.map(({path:K,result:Q})=>`${K} (${Q.level}: ${Q.reason})`);if(Y.filter(({result:K})=>K.level==="high").length>0&&Z.result!=="allow")return{result:"deny",matchedRule:"safety:high-sensitive-file",reason:`Access to highly sensitive files denied:
1323
1323
  ${V.join(`
1324
1324
  `)}
1325
1325
 
@@ -1327,34 +1327,34 @@ If access is required, add an explicit allow rule in permissions.`};if(Z.result=
1327
1327
  ${V.join(`
1328
1328
  `)}
1329
1329
 
1330
- Confirm to proceed?`};return Z}}function GZ($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}var FZ=M("Execution");class k1{name="resolve-decision";async process($){let{ruleDecision:Z,hookDecision:J}=$._internal,W=k1.resolve(Z,J);if($._internal.effectiveDecision=W,FZ.debug(`[ResolveDecision] rule=${Z?.behavior??"none"} hook=${J?.behavior??"none"} → ${W.behavior} (${W.source})`),W.behavior==="deny")$.abort(W.reason||`Tool invocation denied by ${W.source}${W.matchedRule?` (${W.matchedRule})`:""}`)}static resolve($,Z){if($?.behavior==="deny")return $;if(Z?.behavior==="deny")return Z;if(Z?.behavior==="ask")return Z;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(Z?.behavior==="allow")return Z;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}}class u0 extends OZ{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals;scheduler;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize||1000,this.sessionApprovals=Z.approvalStore||new h0,this.scheduler=Z.scheduler??(Z.concurrencyLimits?new v$(Z.concurrencyLimits):v$.getInstance());let J=Z.permissionConfig||{allow:[],ask:[],deny:[]},W=Z.permissionMode??"default",X=new Q8(J,this.sessionApprovals,W);this.stages=[new r5(this.registry),new J8(Z.toolWhitelist,Z.toolBlacklist),X,new i5,new k1,new s5(this.sessionApprovals,X.getPermissionChecker()),new u$,new a5,new Z8,new o5]}async execute($,Z,J){let W=Date.now(),X=this.generateExecutionId(),Y=new Y9($,Z,{...J,sessionId:J.sessionId||X});this.emit("executionStarted",{executionId:X,toolName:$,params:Z,context:J,timestamp:W});let V=this.registry.get($),B=V&&!V.isConcurrencySafe,K=B&&Z.file_path?String(Z.file_path):null,Q=V?.kind??"readonly",U=()=>this.executeWithPipeline(Y,X,W),q=B&&K?()=>d$.getInstance().acquireLock(K,U):U;return this.scheduler.schedule(Q,q)}async executeWithPipeline($,Z,J){try{for(let Y of this.stages){if($.context.signal?.aborted){$.abort("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});break}if(this.emit("stageStarted",{executionId:Z,stageName:Y.name,timestamp:Date.now()}),await Y.process($),this.emit("stageCompleted",{executionId:Z,stageName:Y.name,timestamp:Date.now()}),$.shouldAbort())break}let W=$.getResult(),X=Date.now();return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:W,startTime:J,endTime:X,context:$.context}),this.emit("executionCompleted",{executionId:Z,toolName:$.toolName,result:W,duration:X-J,timestamp:X}),W}catch(W){let X=Date.now(),Y=W.message?.includes("timeout")||W.name==="TimeoutError",V={success:!1,llmContent:`Tool execution failed: ${W.message}`,error:{type:"execution_error",message:W.message}};try{let K=await X$.getInstance().executePostToolUseFailureHooks($.toolName,`tool_use_${Z}`,$.params,W.message,{projectDir:N(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default",isInterrupt:!1,isTimeout:Y,abortSignal:$.context.signal});if(K.additionalContext)V={...V,llmContent:`${V.llmContent}
1330
+ Confirm to proceed?`};return Z}}function OZ($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}var zZ=M("Execution");class k1{name="resolve-decision";async process($){let{ruleDecision:Z,hookDecision:J}=$._internal,W=k1.resolve(Z,J);if($._internal.effectiveDecision=W,zZ.debug(`[ResolveDecision] rule=${Z?.behavior??"none"} hook=${J?.behavior??"none"} → ${W.behavior} (${W.source})`),W.behavior==="deny")$.abort(W.reason||`Tool invocation denied by ${W.source}${W.matchedRule?` (${W.matchedRule})`:""}`)}static resolve($,Z){if($?.behavior==="deny")return $;if(Z?.behavior==="deny")return Z;if(Z?.behavior==="ask")return Z;if($?.behavior==="ask")return $;if($?.behavior==="allow")return $;if(Z?.behavior==="allow")return Z;return{behavior:"ask",source:"default",reason:"No permission rule or hook decision; defaulting to ask"}}}class u0 extends wZ{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals;scheduler;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize||1000,this.sessionApprovals=Z.approvalStore||new p0,this.scheduler=Z.scheduler??(Z.concurrencyLimits?new C$(Z.concurrencyLimits):C$.getInstance());let J=Z.permissionConfig||{allow:[],ask:[],deny:[]},W=Z.permissionMode??"default",X=new Q8(J,this.sessionApprovals,W);this.stages=[new r5(this.registry),new J8(Z.toolWhitelist,Z.toolBlacklist),X,new i5,new k1,new s5(this.sessionApprovals,X.getPermissionChecker()),new g$,new a5,new Z8,new o5]}async execute($,Z,J){let W=Date.now(),X=this.generateExecutionId(),Y=new Y9($,Z,{...J,sessionId:J.sessionId||X});this.emit("executionStarted",{executionId:X,toolName:$,params:Z,context:J,timestamp:W});let V=this.registry.get($),B=V&&!V.isConcurrencySafe,K=B&&Z.file_path?String(Z.file_path):null,Q=V?.kind??"readonly",U=()=>this.executeWithPipeline(Y,X,W),q=B&&K?()=>u$.getInstance().acquireLock(K,U):U;return this.scheduler.schedule(Q,q)}async executeWithPipeline($,Z,J){try{for(let Y of this.stages){if($.context.signal?.aborted){$.abort("任务已被用户中止",{shouldExitLoop:!0,llmContent:"任务已被用户中止",summary:"任务已被用户中止",abortedBeforeLaunch:!0});break}if(this.emit("stageStarted",{executionId:Z,stageName:Y.name,timestamp:Date.now()}),await Y.process($),this.emit("stageCompleted",{executionId:Z,stageName:Y.name,timestamp:Date.now()}),$.shouldAbort())break}let W=$.getResult(),X=Date.now();return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:W,startTime:J,endTime:X,context:$.context}),this.emit("executionCompleted",{executionId:Z,toolName:$.toolName,result:W,duration:X-J,timestamp:X}),W}catch(W){let X=Date.now(),Y=W.message?.includes("timeout")||W.name==="TimeoutError",V={success:!1,llmContent:`Tool execution failed: ${W.message}`,error:{type:"execution_error",message:W.message}};try{let K=await X$.getInstance().executePostToolUseFailureHooks($.toolName,`tool_use_${Z}`,$.params,W.message,{projectDir:N(),sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default",isInterrupt:!1,isTimeout:Y,abortSignal:$.context.signal});if(K.additionalContext)V={...V,llmContent:`${V.llmContent}
1331
1331
 
1332
- ${K.additionalContext}`};if(K.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${K.warning}`)}catch(B){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",B)}return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:V,startTime:J,endTime:X,context:$.context}),this.emit("executionFailed",{executionId:Z,toolName:$.toolName,error:W,duration:X-J,timestamp:X}),V}}async executeAll($){let Z=$.map((J)=>this.execute(J.toolName,J.params,J.context));return Promise.all(Z)}async executeParallel($,Z=5){let J=Z>0?Z:Number.POSITIVE_INFINITY;if(!Number.isFinite(J)||J>=$.length)return Promise.all($.map((V)=>this.execute(V.toolName,V.params,V.context)));let W=Array($.length),X=0,Y=async()=>{while(!0){let V=X++;if(V>=$.length)return;let B=$[V];W[V]=await this.execute(B.toolName,B.params,B.context)}};return await Promise.all(Array.from({length:Math.min(J,$.length)},()=>Y())),W}getSchedulerStats(){return this.scheduler.getStats()}getExecutionHistory($){let Z=[...this.executionHistory];return $?Z.slice(-$):Z}clearHistory(){this.executionHistory=[],this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let J of this.executionHistory){if(J.result.success)$.successfulExecutions++;else $.failedExecutions++;let W=J.endTime-J.startTime;Z+=W;let X=$.toolUsage.get(J.toolName)||0;$.toolUsage.set(J.toolName,X+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}addStage($,Z=-1){if(Z===-1){let J=this.stages.findIndex((W)=>W.name==="execution");this.stages.splice(J,0,$)}else this.stages.splice(Z,0,$);this.emit("stageAdded",{stageName:$.name,position:Z,timestamp:Date.now()})}removeStage($){let Z=this.stages.findIndex((J)=>J.name===$);if(Z===-1)return!1;return this.stages.splice(Z,1),this.emit("stageRemoved",{stageName:$,timestamp:Date.now()}),!0}getStages(){return[...this.stages]}getRegistry(){return this.registry}generateExecutionId(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory=this.executionHistory.slice(-this.maxHistorySize)}}import{EventEmitter as zZ}from"events";var U8=new Set(["Read","Edit","Write","Glob","Grep","Bash","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode"]);class q8{loadedTools=new Set(U8);deferredTools=new Set;register($){if(U8.has($))this.loadedTools.add($);else this.deferredTools.add($)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,Z){return $.filter((J)=>this.isLoaded(J.name)).map((J)=>J.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
1333
- `)}reset(){this.loadedTools=new Set(U8),this.deferredTools.clear()}}class c$ extends zZ{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new q8;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 Z=[];for(let J of $)try{this.register(J)}catch(W){Z.push(`${J.name}: ${W.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($);if(!Z)return!1;return this.tools.delete($),this.removeFromIndexes(Z),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 Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((J)=>{let W=typeof J.description==="string"?J.description:J.description.short;return J.name.toLowerCase().includes(Z)||W.toLowerCase().includes(Z)||J.displayName.toLowerCase().includes(Z)||J.category&&J.category.toLowerCase().includes(Z)||J.tags.some((X)=>X.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();if($==="spec")return this.getSpecModeFunctionDeclarations();return this._deferredManager.filterDeclarations(this.getAll(),$)}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return c$.SPEC_TOOLS.includes($)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new c$;for(let Z of this.tools.values())$.register(Z);for(let Z of this.mcpTools.values())$.registerMcpTool(Z);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 Z=0,J=`mcp__${$}__`;for(let[W,X]of this.mcpTools.entries())if(W.startsWith(J))this.mcpTools.delete(W),this.removeFromIndexes(X),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:W,serverName:$,timestamp:Date.now()});return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let J=this.tags.get(Z);if(J){if(J.delete($.name),J.size===0)this.tags.delete(Z)}}}}var wZ=[/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 jZ($){return wZ.some((Z)=>Z.test($))}function NZ($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:jZ($.model),thinkingBudget:void 0}}function b1($){return NZ($).supportsThinking}import*as K9 from"crypto";import{nanoid as B9}from"nanoid";class H8{assemble($){if($.length===0)return null;let Z=this.assembleSession($),J=this.assembleConversation($),W=this.assembleToolCalls($);return{session:Z,conversation:J,toolCalls:W}}assembleContextData($,Z,J){let W=this.assemble($);if(!W)return null;return{layers:{system:Z,session:W.session,conversation:W.conversation,tool:{recentCalls:W.toolCalls,toolStates:{},dependencies:{}},workspace:J},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let Z=$.find((V)=>V.type==="session_created"),J=Z?.sessionId??$[0].sessionId,W=new Date(Z?.timestamp??$[0].timestamp).getTime(),X=$.filter((V)=>V.type==="session_updated"),Y=X.length>0?X[X.length-1]:null;return{sessionId:J,userId:void 0,preferences:{},configuration:Y?.data??{},startTime:W}}assembleConversation($){let Z=new Map,J;for(let V of $){if(V.type==="message_created")Z.set(V.data.messageId,{id:V.data.messageId,role:V.data.role,content:"",timestamp:new Date(V.timestamp).getTime(),metadata:V.data.model?{model:V.data.model}:void 0});if(V.type==="part_created"){let{partType:B,messageId:K,payload:Q}=V.data,U=Z.get(K);if(B==="text"&&U){let q=Q;U.content=q.text??""}if(B==="image"&&U)U.content=U.content?`${U.content}
1334
- [Image]`:"[Image]";if(B==="summary"){let q=Q;if(q.text)J=q.text}}if(V.type==="part_updated"){let{partType:B,messageId:K,payload:Q}=V.data,U=Z.get(K);if(B==="text"&&U){let q=Q;U.content=q.text??""}}}let W=Array.from(Z.values()),X=$[$.length-1],Y=new Date(X.timestamp).getTime();return{messages:W,summary:J,topics:[],lastActivity:Y}}assembleToolCalls($){let Z=new Map;for(let J of $){if(J.type!=="part_created")continue;let{partType:W,partId:X,payload:Y}=J.data;if(W==="tool_call"){let V=Y,B=V.toolCallId??X;Z.set(B,{id:B,name:V.toolName??"unknown",input:V.input??null,timestamp:new Date(J.timestamp).getTime(),status:"pending"})}if(W==="tool_result"){let V=Y,B=V.toolCallId??X,K=Z.get(B);if(K)K.output=V.output??void 0,K.status=V.error?"error":"success",K.error=V.error??void 0;else Z.set(B,{id:B,name:V.toolName??"unknown",input:null,output:V.output??void 0,timestamp:new Date(J.timestamp).getTime(),status:V.error?"error":"success",error:V.error??void 0})}}return Array.from(Z.values())}}class G8{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,J=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=J}async compress($){let Z=$.layers.conversation.messages,J=$.layers.tool.recentCalls,W=Z.filter((q)=>q.role==="system"),X=Z.filter((q)=>q.role!=="system"),Y=this.getRecentMessages(X),V=X.slice(0,-this.recentMessagesLimit),B=await this.generateSummary(V),K=this.extractKeyPoints(V,J),Q=this.generateToolSummary(J),U=this.estimateTokenCount(B,K,Y,Q);return{summary:B,keyPoints:K,recentMessages:[...W,...Y],toolSummary:Q,tokenCount:U}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,J=new Set,W=new Set;for(let Y of $){let V=Y.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,50);if(q)Z.add(q)}}),["创建","删除","修改","更新","实现","开发"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,30);if(q)J.add(q)}}),["决定","选择","确定","采用","使用"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,40);if(q)W.add(q)}})}let X=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)X+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(J.size>0)X+=` 执行操作:${Array.from(J).slice(0,3).join("、")}。`;if(W.size>0)X+=` 关键决策:${Array.from(W).slice(0,2).join("、")}。`;return X.length>this.maxSummaryLength?X.substring(0,this.maxSummaryLength)+"...":X}extractKeyPoints($,Z){let J=new Set;for(let X of $)if(X.role==="user")this.extractQuestions(X.content).forEach((B)=>J.add(`用户问题:${B}`)),this.extractRequests(X.content).forEach((B)=>J.add(`用户请求:${B}`));else if(X.role==="assistant")this.extractSolutions(X.content).forEach((V)=>J.add(`解决方案:${V}`));return this.summarizeToolUsage(Z).forEach((X)=>J.add(`工具使用:${X}`)),Array.from(J).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,J=Date.now()-600000;for(let X of $){let Y=Z.get(X.name)||{count:0,success:0,recent:0};if(Y.count++,X.status==="success")Y.success++;if(X.timestamp>J)Y.recent++;Z.set(X.name,Y)}let W=[];for(let[X,Y]of Array.from(Z.entries())){let V=Math.round(Y.success/Y.count*100);W.push(`${X}(${Y.count}次,成功率${V}%)`)}return`工具调用:${W.join("、")}`}estimateTokenCount($,Z,J,W){let X=$.length+Z.join(" ").length;if(W)X+=W.length;for(let Y of J)X+=Y.content.length;return Math.ceil(X/4)}extractContext($,Z,J){let W=$.indexOf(Z);if(W===-1)return null;let X=Math.max(0,W-J/2),Y=Math.min($.length,W+J/2);return $.substring(X,Y).trim()}extractQuestions($){let Z=[],J=["?","?","如何","怎么","什么","为什么"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractRequests($){let Z=[],J=["请","帮我","需要","想要","希望","能否"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractSolutions($){let Z=[],J=["可以","建议","推荐","应该","最好","解决方案"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>10&&Y.length<150)Z.push(Y)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],J=$.filter((W)=>Date.now()-W.timestamp<1800000);if(J.length>0){let W=new Map;J.forEach((X)=>{let Y=W.get(X.name)||[];Y.push(X),W.set(X.name,Y)});for(let[X,Y]of Array.from(W.entries())){let V=Y.filter((B)=>B.status==="success").length;Z.push(`${X}(${Y.length}次,${V}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let J=$.layers.conversation.messages.reduce((W,X)=>W+X.content.length,0);return Math.ceil(J/4)}}class B0{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let J={...this.defaultOptions,...Z},W={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,J),tool:J.includeTools?this.filterTools($.layers.tool,J):{recentCalls:[],toolStates:{},dependencies:{}},workspace:J.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return W.metadata.totalTokens=this.estimateTokens(W),W}filterConversation($,Z){let J=[...$.messages];if(Z.timeWindow>0){let W=Date.now()-Z.timeWindow;J=J.filter((X)=>X.timestamp>=W||X.role==="system")}if(Z.priority>1)J=this.filterByPriority(J,Z.priority);if(Z.maxMessages>0)J=this.limitMessages(J,Z.maxMessages);if(Z.maxTokens>0)J=this.limitByTokens(J,Z.maxTokens);return{messages:J,summary:$.summary,topics:this.updateTopics(J,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let J=[...$.recentCalls];if(Z.timeWindow>0){let K=Date.now()-Z.timeWindow;J=J.filter((Q)=>Q.timestamp>=K)}let W=J.filter((K)=>K.status==="success"),X=J.filter((K)=>K.status==="error"),Y=Math.min(20,W.length),V=Math.min(10,X.length);return{recentCalls:[...W.slice(-Y),...X.slice(-V)].sort((K,Q)=>K.timestamp-Q.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((J)=>{if(J.role==="system")return!0;return this.calculateMessagePriority(J)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let J=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Y)=>J.includes(Y)))Z+=2;if(J.includes("```")||J.includes("function")||J.includes("class"))Z+=1;let X=(Date.now()-$.timestamp)/3600000;if(X<1)Z+=2;else if(X<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let J=$.filter((V)=>V.role==="system"),W=$.filter((V)=>V.role!=="system"),X=Z-J.length,Y=X>0?W.slice(-X):[];return[...J,...Y].sort((V,B)=>V.timestamp-B.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let J=0,W=[];for(let X=$.length-1;X>=0;X--){let Y=$[X],V=this.estimateMessageTokens(Y);if(Y.role==="system")if(J+V<=Z)W.unshift(Y),J+=V;else{let B=this.compressMessage(Y,Z-J);W.unshift(B),J+=this.estimateMessageTokens(B)}else if(J+V<=Z)W.unshift(Y),J+=V;else break}return W.sort((X,Y)=>X.timestamp-Y.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let J=Z*4;if($.content.length<=J)return $;let W=$.content.substring(0,J-3)+"...";return{...$,content:W,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let J=new Set(Z);for(let W of $)this.extractTopicsFromMessage(W).forEach((Y)=>J.add(Y));return Array.from(J).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),J=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((X)=>{if(Z.includes(X))J.push(X)}),J}estimateTokens($){let Z=0;for(let W of $.layers.conversation.messages)Z+=this.estimateMessageTokens(W);let J=JSON.stringify($.layers.system);if(Z+=Math.ceil(J.length/4),$.layers.tool.recentCalls.length>0){let W=JSON.stringify($.layers.tool);Z+=Math.ceil(W.length/8)}return Z}static createPresets(){return{lightweight:new B0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new B0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new B0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new B0({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class F8{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,J){let W=Date.now(),X={data:Z,timestamp:W,accessCount:0,lastAccess:W,ttl:J||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,X)}get($){let Z=this.cache.get($);if(!Z)return null;let J=Date.now();if(J-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=J,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,J){let W=`summary:${$}:${Z.length}`;this.set(W,{summary:J,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let J=`summary:${$}:${Z}`;return this.get(J)}cacheToolResult($,Z,J){let W=this.hashInput(Z),X=`tool:${$}:${W}`;this.set(X,J,1800000)}getToolResult($,Z){let J=this.hashInput(Z),W=`tool:${$}:${J}`;return this.get(W)}cacheCompressedContext($,Z){let J=`compressed:${$}`;this.set(J,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,J=[];for(let[W,X]of Array.from(this.cache.entries()))$+=X.accessCount,Z+=this.estimateItemSize(X),J.push({key:W,accessCount:X.accessCount,lastAccess:X.lastAccess});return J.sort((W,X)=>X.accessCount-W.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:J.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[J,W]of Array.from(this.cache.entries()))if($-W.timestamp>W.ttl)Z.push(J);Z.forEach((J)=>this.cache.delete(J))}evictLeastUsed(){let $=null,Z=1/0,J=Date.now();for(let[W,X]of Array.from(this.cache.entries())){let Y=1/(J-X.lastAccess+1),V=X.accessCount,B=Y*V;if(B<Z)Z=B,$=W}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),J=0;for(let W=0;W<Z.length;W++){let X=Z.charCodeAt(W);J=(J<<5)-J+X,J=J&J}return Math.abs(J).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let J=this.cache.get($);if(J)return J.ttl=Z,J.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let J=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,J)}warmup($){$.forEach(({key:Z,value:J,ttl:W})=>{this.set(Z,J,W)})}}class O8{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as w$}from"nanoid";import*as C$ from"node:fs/promises";import*as V9 from"node:path";import*as T1 from"node:fs";import{createReadStream as DZ}from"node:fs";import*as e from"node:fs/promises";import*as z8 from"node:path";import{createInterface as LZ}from"node:readline";class q${filePath;constructor($){this.filePath=$}async append($){try{await e.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=JSON.stringify($)+`
1332
+ ${K.additionalContext}`};if(K.warning)console.warn(`[ExecutionPipeline] PostToolUseFailure hook warning: ${K.warning}`)}catch(B){console.warn("[ExecutionPipeline] PostToolUseFailure hook execution failed:",B)}return this.addToHistory({executionId:Z,toolName:$.toolName,params:$.params,result:V,startTime:J,endTime:X,context:$.context}),this.emit("executionFailed",{executionId:Z,toolName:$.toolName,error:W,duration:X-J,timestamp:X}),V}}async executeAll($){let Z=$.map((J)=>this.execute(J.toolName,J.params,J.context));return Promise.all(Z)}async executeParallel($,Z=5){let J=Z>0?Z:Number.POSITIVE_INFINITY;if(!Number.isFinite(J)||J>=$.length)return Promise.all($.map((V)=>this.execute(V.toolName,V.params,V.context)));let W=Array($.length),X=0,Y=async()=>{while(!0){let V=X++;if(V>=$.length)return;let B=$[V];W[V]=await this.execute(B.toolName,B.params,B.context)}};return await Promise.all(Array.from({length:Math.min(J,$.length)},()=>Y())),W}getSchedulerStats(){return this.scheduler.getStats()}getExecutionHistory($){let Z=[...this.executionHistory];return $?Z.slice(-$):Z}clearHistory(){this.executionHistory=[],this.emit("historyClear",{timestamp:Date.now()})}getStats(){let $={totalExecutions:this.executionHistory.length,successfulExecutions:0,failedExecutions:0,averageDuration:0,toolUsage:new Map,recentExecutions:this.executionHistory.slice(-10)},Z=0;for(let J of this.executionHistory){if(J.result.success)$.successfulExecutions++;else $.failedExecutions++;let W=J.endTime-J.startTime;Z+=W;let X=$.toolUsage.get(J.toolName)||0;$.toolUsage.set(J.toolName,X+1)}return $.averageDuration=$.totalExecutions>0?Z/$.totalExecutions:0,$}addStage($,Z=-1){if(Z===-1){let J=this.stages.findIndex((W)=>W.name==="execution");this.stages.splice(J,0,$)}else this.stages.splice(Z,0,$);this.emit("stageAdded",{stageName:$.name,position:Z,timestamp:Date.now()})}removeStage($){let Z=this.stages.findIndex((J)=>J.name===$);if(Z===-1)return!1;return this.stages.splice(Z,1),this.emit("stageRemoved",{stageName:$,timestamp:Date.now()}),!0}getStages(){return[...this.stages]}getRegistry(){return this.registry}generateExecutionId(){return`exec_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}addToHistory($){if(this.executionHistory.push($),this.executionHistory.length>this.maxHistorySize)this.executionHistory=this.executionHistory.slice(-this.maxHistorySize)}}import{EventEmitter as jZ}from"events";var U8=new Set(["Read","Edit","Write","Glob","Grep","Bash","Task","TaskOutput","TaskCreate","TaskGet","TaskUpdate","TaskList","TeamCreate","TeamStatus","TeamDelete","AskUserQuestion","Skill","SlashCommand","ToolSearch","EnterPlanMode","ExitPlanMode"]);class q8{loadedTools=new Set(U8);deferredTools=new Set;register($){if(U8.has($))this.loadedTools.add($);else this.deferredTools.add($)}markLoaded($){this.loadedTools.add($),this.deferredTools.delete($)}isLoaded($){return this.loadedTools.has($)}filterDeclarations($,Z){return $.filter((J)=>this.isLoaded(J.name)).map((J)=>J.getFunctionDeclaration())}getDeferredToolNames(){return Array.from(this.deferredTools)}getDeferredToolsListing(){let $=this.getDeferredToolNames();if($.length===0)return"";return["<available-deferred-tools>",...$,"</available-deferred-tools>"].join(`
1333
+ `)}reset(){this.loadedTools=new Set(U8),this.deferredTools.clear()}}class l$ extends jZ{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;_deferredManager=new q8;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 Z=[];for(let J of $)try{this.register(J)}catch(W){Z.push(`${J.name}: ${W.message}`)}if(Z.length>0)throw Error(`批量注册失败: ${Z.join(", ")}`)}unregister($){let Z=this.tools.get($);if(!Z)return!1;return this.tools.delete($),this.removeFromIndexes(Z),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 Z=this.categories.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}getByTag($){let Z=this.tags.get($);if(!Z)return[];return Array.from(Z).map((J)=>this.get(J)).filter((J)=>J!==void 0)}search($){let Z=$.toLowerCase();return this.getAll().filter((J)=>{let W=typeof J.description==="string"?J.description:J.description.short;return J.name.toLowerCase().includes(Z)||W.toLowerCase().includes(Z)||J.displayName.toLowerCase().includes(Z)||J.category&&J.category.toLowerCase().includes(Z)||J.tags.some((X)=>X.toLowerCase().includes(Z))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();if($==="spec")return this.getSpecModeFunctionDeclarations();return this._deferredManager.filterDeclarations(this.getAll(),$)}static SPEC_TOOLS=["EnterSpecMode","UpdateSpec","GetSpecContext","TransitionSpecPhase","AddTask","UpdateTaskStatus","ValidateSpec","ExitSpecMode"];getSpecModeFunctionDeclarations(){return this.getFunctionDeclarations()}isSpecTool($){return l$.SPEC_TOOLS.includes($)}getReadOnlyTools(){return this.getAll().filter(($)=>$.isReadOnly)}getCategories(){return Array.from(this.categories.keys())}getTags(){return Array.from(this.tags.keys())}getStats(){return{totalTools:this.tools.size+this.mcpTools.size,builtinTools:this.tools.size,mcpTools:this.mcpTools.size,categories:this.categories.size,tags:this.tags.size,toolsByCategory:Object.fromEntries(Array.from(this.categories.entries()).map(([$,Z])=>[$,Z.size]))}}getDeferredToolsListing(){return this._deferredManager.getDeferredToolsListing()}clone(){let $=new l$;for(let Z of this.tools.values())$.register(Z);for(let Z of this.mcpTools.values())$.registerMcpTool(Z);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 Z=0,J=`mcp__${$}__`;for(let[W,X]of this.mcpTools.entries())if(W.startsWith(J))this.mcpTools.delete(W),this.removeFromIndexes(X),Z++,this.emit("toolUnregistered",{type:"mcp",toolName:W,serverName:$,timestamp:Date.now()});return Z}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Z of $.tags){if(!this.tags.has(Z))this.tags.set(Z,new Set);this.tags.get(Z).add($.name)}}removeFromIndexes($){if($.category){let Z=this.categories.get($.category);if(Z){if(Z.delete($.name),Z.size===0)this.categories.delete($.category)}}for(let Z of $.tags){let J=this.tags.get(Z);if(J){if(J.delete($.name),J.size===0)this.tags.delete(Z)}}}}var NZ=[/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 DZ($){return NZ.some((Z)=>Z.test($))}function LZ($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:DZ($.model),thinkingBudget:void 0}}function b1($){return LZ($).supportsThinking}import*as K9 from"crypto";import{nanoid as B9}from"nanoid";class H8{assemble($){if($.length===0)return null;let Z=this.assembleSession($),J=this.assembleConversation($),W=this.assembleToolCalls($);return{session:Z,conversation:J,toolCalls:W}}assembleContextData($,Z,J){let W=this.assemble($);if(!W)return null;return{layers:{system:Z,session:W.session,conversation:W.conversation,tool:{recentCalls:W.toolCalls,toolStates:{},dependencies:{}},workspace:J},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}}}assembleSession($){let Z=$.find((V)=>V.type==="session_created"),J=Z?.sessionId??$[0].sessionId,W=new Date(Z?.timestamp??$[0].timestamp).getTime(),X=$.filter((V)=>V.type==="session_updated"),Y=X.length>0?X[X.length-1]:null;return{sessionId:J,userId:void 0,preferences:{},configuration:Y?.data??{},startTime:W}}assembleConversation($){let Z=new Map,J;for(let V of $){if(V.type==="message_created")Z.set(V.data.messageId,{id:V.data.messageId,role:V.data.role,content:"",timestamp:new Date(V.timestamp).getTime(),metadata:V.data.model?{model:V.data.model}:void 0});if(V.type==="part_created"){let{partType:B,messageId:K,payload:Q}=V.data,U=Z.get(K);if(B==="text"&&U){let q=Q;U.content=q.text??""}if(B==="image"&&U)U.content=U.content?`${U.content}
1334
+ [Image]`:"[Image]";if(B==="summary"){let q=Q;if(q.text)J=q.text}}if(V.type==="part_updated"){let{partType:B,messageId:K,payload:Q}=V.data,U=Z.get(K);if(B==="text"&&U){let q=Q;U.content=q.text??""}}}let W=Array.from(Z.values()),X=$[$.length-1],Y=new Date(X.timestamp).getTime();return{messages:W,summary:J,topics:[],lastActivity:Y}}assembleToolCalls($){let Z=new Map;for(let J of $){if(J.type!=="part_created")continue;let{partType:W,partId:X,payload:Y}=J.data;if(W==="tool_call"){let V=Y,B=V.toolCallId??X;Z.set(B,{id:B,name:V.toolName??"unknown",input:V.input??null,timestamp:new Date(J.timestamp).getTime(),status:"pending"})}if(W==="tool_result"){let V=Y,B=V.toolCallId??X,K=Z.get(B);if(K)K.output=V.output??void 0,K.status=V.error?"error":"success",K.error=V.error??void 0;else Z.set(B,{id:B,name:V.toolName??"unknown",input:null,output:V.output??void 0,timestamp:new Date(J.timestamp).getTime(),status:V.error?"error":"success",error:V.error??void 0})}}return Array.from(Z.values())}}class G8{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Z=10,J=20){this.maxSummaryLength=$,this.keyPointsLimit=Z,this.recentMessagesLimit=J}async compress($){let Z=$.layers.conversation.messages,J=$.layers.tool.recentCalls,W=Z.filter((q)=>q.role==="system"),X=Z.filter((q)=>q.role!=="system"),Y=this.getRecentMessages(X),V=X.slice(0,-this.recentMessagesLimit),B=await this.generateSummary(V),K=this.extractKeyPoints(V,J),Q=this.generateToolSummary(J),U=this.estimateTokenCount(B,K,Y,Q);return{summary:B,keyPoints:K,recentMessages:[...W,...Y],toolSummary:Q,tokenCount:U}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Z=new Set,J=new Set,W=new Set;for(let Y of $){let V=Y.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,50);if(q)Z.add(q)}}),["创建","删除","修改","更新","实现","开发"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,30);if(q)J.add(q)}}),["决定","选择","确定","采用","使用"].forEach((U)=>{if(V.includes(U)){let q=this.extractContext(V,U,40);if(q)W.add(q)}})}let X=`对话涉及 ${$.length} 条消息。`;if(Z.size>0)X+=` 主要讨论:${Array.from(Z).slice(0,3).join("、")}。`;if(J.size>0)X+=` 执行操作:${Array.from(J).slice(0,3).join("、")}。`;if(W.size>0)X+=` 关键决策:${Array.from(W).slice(0,2).join("、")}。`;return X.length>this.maxSummaryLength?X.substring(0,this.maxSummaryLength)+"...":X}extractKeyPoints($,Z){let J=new Set;for(let X of $)if(X.role==="user")this.extractQuestions(X.content).forEach((B)=>J.add(`用户问题:${B}`)),this.extractRequests(X.content).forEach((B)=>J.add(`用户请求:${B}`));else if(X.role==="assistant")this.extractSolutions(X.content).forEach((V)=>J.add(`解决方案:${V}`));return this.summarizeToolUsage(Z).forEach((X)=>J.add(`工具使用:${X}`)),Array.from(J).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Z=new Map,J=Date.now()-600000;for(let X of $){let Y=Z.get(X.name)||{count:0,success:0,recent:0};if(Y.count++,X.status==="success")Y.success++;if(X.timestamp>J)Y.recent++;Z.set(X.name,Y)}let W=[];for(let[X,Y]of Array.from(Z.entries())){let V=Math.round(Y.success/Y.count*100);W.push(`${X}(${Y.count}次,成功率${V}%)`)}return`工具调用:${W.join("、")}`}estimateTokenCount($,Z,J,W){let X=$.length+Z.join(" ").length;if(W)X+=W.length;for(let Y of J)X+=Y.content.length;return Math.ceil(X/4)}extractContext($,Z,J){let W=$.indexOf(Z);if(W===-1)return null;let X=Math.max(0,W-J/2),Y=Math.min($.length,W+J/2);return $.substring(X,Y).trim()}extractQuestions($){let Z=[],J=["?","?","如何","怎么","什么","为什么"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractRequests($){let Z=[],J=["请","帮我","需要","想要","希望","能否"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>5&&Y.length<100)Z.push(Y)}return Z.slice(0,3)}extractSolutions($){let Z=[],J=["可以","建议","推荐","应该","最好","解决方案"],W=$.split(/[。!.!]/);for(let X of W)if(J.some((Y)=>X.includes(Y))){let Y=X.trim();if(Y.length>10&&Y.length<150)Z.push(Y)}return Z.slice(0,3)}summarizeToolUsage($){let Z=[],J=$.filter((W)=>Date.now()-W.timestamp<1800000);if(J.length>0){let W=new Map;J.forEach((X)=>{let Y=W.get(X.name)||[];Y.push(X),W.set(X.name,Y)});for(let[X,Y]of Array.from(W.entries())){let V=Y.filter((B)=>B.status==="success").length;Z.push(`${X}(${Y.length}次,${V}成功)`)}}return Z.slice(0,5)}shouldCompress($,Z){return this.estimateCurrentTokens($)>Z*0.8}estimateCurrentTokens($){let J=$.layers.conversation.messages.reduce((W,X)=>W+X.content.length,0);return Math.ceil(J/4)}}class K0{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Z){let J={...this.defaultOptions,...Z},W={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,J),tool:J.includeTools?this.filterTools($.layers.tool,J):{recentCalls:[],toolStates:{},dependencies:{}},workspace:J.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return W.metadata.totalTokens=this.estimateTokens(W),W}filterConversation($,Z){let J=[...$.messages];if(Z.timeWindow>0){let W=Date.now()-Z.timeWindow;J=J.filter((X)=>X.timestamp>=W||X.role==="system")}if(Z.priority>1)J=this.filterByPriority(J,Z.priority);if(Z.maxMessages>0)J=this.limitMessages(J,Z.maxMessages);if(Z.maxTokens>0)J=this.limitByTokens(J,Z.maxTokens);return{messages:J,summary:$.summary,topics:this.updateTopics(J,$.topics),lastActivity:$.lastActivity}}filterTools($,Z){let J=[...$.recentCalls];if(Z.timeWindow>0){let K=Date.now()-Z.timeWindow;J=J.filter((Q)=>Q.timestamp>=K)}let W=J.filter((K)=>K.status==="success"),X=J.filter((K)=>K.status==="error"),Y=Math.min(20,W.length),V=Math.min(10,X.length);return{recentCalls:[...W.slice(-Y),...X.slice(-V)].sort((K,Q)=>K.timestamp-Q.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Z){return $.filter((J)=>{if(J.role==="system")return!0;return this.calculateMessagePriority(J)>=Z})}calculateMessagePriority($){let Z=1;if($.role==="system")Z+=3;else if($.role==="assistant")Z+=1;let J=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((Y)=>J.includes(Y)))Z+=2;if(J.includes("```")||J.includes("function")||J.includes("class"))Z+=1;let X=(Date.now()-$.timestamp)/3600000;if(X<1)Z+=2;else if(X<6)Z+=1;return Z}limitMessages($,Z){if($.length<=Z)return $;let J=$.filter((V)=>V.role==="system"),W=$.filter((V)=>V.role!=="system"),X=Z-J.length,Y=X>0?W.slice(-X):[];return[...J,...Y].sort((V,B)=>V.timestamp-B.timestamp)}limitByTokens($,Z){if(Z<=0)return $;let J=0,W=[];for(let X=$.length-1;X>=0;X--){let Y=$[X],V=this.estimateMessageTokens(Y);if(Y.role==="system")if(J+V<=Z)W.unshift(Y),J+=V;else{let B=this.compressMessage(Y,Z-J);W.unshift(B),J+=this.estimateMessageTokens(B)}else if(J+V<=Z)W.unshift(Y),J+=V;else break}return W.sort((X,Y)=>X.timestamp-Y.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Z){let J=Z*4;if($.content.length<=J)return $;let W=$.content.substring(0,J-3)+"...";return{...$,content:W,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Z){let J=new Set(Z);for(let W of $)this.extractTopicsFromMessage(W).forEach((Y)=>J.add(Y));return Array.from(J).slice(0,10)}extractTopicsFromMessage($){let Z=$.content.toLowerCase(),J=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((X)=>{if(Z.includes(X))J.push(X)}),J}estimateTokens($){let Z=0;for(let W of $.layers.conversation.messages)Z+=this.estimateMessageTokens(W);let J=JSON.stringify($.layers.system);if(Z+=Math.ceil(J.length/4),$.layers.tool.recentCalls.length>0){let W=JSON.stringify($.layers.tool);Z+=Math.ceil(W.length/8)}return Z}static createPresets(){return{lightweight:new K0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new K0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new K0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new K0({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class F8{cache=new Map;maxSize;defaultTTL;constructor($=100,Z=300000){this.maxSize=$,this.defaultTTL=Z}set($,Z,J){let W=Date.now(),X={data:Z,timestamp:W,accessCount:0,lastAccess:W,ttl:J||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,X)}get($){let Z=this.cache.get($);if(!Z)return null;let J=Date.now();if(J-Z.timestamp>Z.ttl)return this.cache.delete($),null;return Z.accessCount++,Z.lastAccess=J,Z.data}has($){let Z=this.cache.get($);if(!Z)return!1;if(Date.now()-Z.timestamp>Z.ttl)return this.cache.delete($),!1;return!0}delete($){return this.cache.delete($)}clear(){this.cache.clear()}size(){return this.cleanExpired(),this.cache.size}cacheMessageSummary($,Z,J){let W=`summary:${$}:${Z.length}`;this.set(W,{summary:J,messageCount:Z.length,lastMessage:Z[Z.length-1]?.timestamp||0},600000)}getMessageSummary($,Z){let J=`summary:${$}:${Z}`;return this.get(J)}cacheToolResult($,Z,J){let W=this.hashInput(Z),X=`tool:${$}:${W}`;this.set(X,J,1800000)}getToolResult($,Z){let J=this.hashInput(Z),W=`tool:${$}:${J}`;return this.get(W)}cacheCompressedContext($,Z){let J=`compressed:${$}`;this.set(J,Z,900000)}getCompressedContext($){let Z=`compressed:${$}`;return this.get(Z)}getStats(){this.cleanExpired();let $=0,Z=0,J=[];for(let[W,X]of Array.from(this.cache.entries()))$+=X.accessCount,Z+=this.estimateItemSize(X),J.push({key:W,accessCount:X.accessCount,lastAccess:X.lastAccess});return J.sort((W,X)=>X.accessCount-W.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Z,topKeys:J.slice(0,10)}}cleanExpired(){let $=Date.now(),Z=[];for(let[J,W]of Array.from(this.cache.entries()))if($-W.timestamp>W.ttl)Z.push(J);Z.forEach((J)=>this.cache.delete(J))}evictLeastUsed(){let $=null,Z=1/0,J=Date.now();for(let[W,X]of Array.from(this.cache.entries())){let Y=1/(J-X.lastAccess+1),V=X.accessCount,B=Y*V;if(B<Z)Z=B,$=W}if($)this.cache.delete($)}hashInput($){let Z=JSON.stringify($),J=0;for(let W=0;W<Z.length;W++){let X=Z.charCodeAt(W);J=(J<<5)-J+X,J=J&J}return Math.abs(J).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Z){let J=this.cache.get($);if(J)return J.ttl=Z,J.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Z=this.cache.get($);if(!Z)return-1;let J=Z.ttl-(Date.now()-Z.timestamp);return Math.max(0,J)}warmup($){$.forEach(({key:Z,value:J,ttl:W})=>{this.set(Z,J,W)})}}class O8{contextData=null;maxSize;accessLog=new Map;constructor($=1000){this.maxSize=$}setContext($){this.contextData={...$},this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("context")}getContext(){if(this.contextData)this.recordAccess("context");return this.contextData}addMessage($){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.conversation.messages.push($),this.contextData.layers.conversation.lastActivity=Date.now(),this.contextData.metadata.lastUpdated=Date.now(),this.enforceMemoryLimit(),this.recordAccess("messages")}getRecentMessages($=10){if(!this.contextData)return[];let Z=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Z.slice(-$)}addToolCall($){if(!this.contextData)throw Error("上下文数据未初始化");if(this.contextData.layers.tool.recentCalls.push($),this.contextData.metadata.lastUpdated=Date.now(),this.contextData.layers.tool.recentCalls.length>50)this.contextData.layers.tool.recentCalls=this.contextData.layers.tool.recentCalls.slice(-25);this.recordAccess("tools")}updateToolState($,Z){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Z,this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("tools")}getToolState($){if(!this.contextData)return null;return this.recordAccess("tools"),this.contextData.layers.tool.toolStates[$]}updateWorkspace($){if(!this.contextData)throw Error("上下文数据未初始化");Object.assign(this.contextData.layers.workspace,$),this.contextData.metadata.lastUpdated=Date.now(),this.recordAccess("workspace")}clear(){this.contextData=null,this.accessLog.clear()}getMemoryInfo(){if(!this.contextData)return{hasData:!1,messageCount:0,toolCallCount:0,lastUpdated:null};return{hasData:!0,messageCount:this.contextData.layers.conversation.messages.length,toolCallCount:this.contextData.layers.tool.recentCalls.length,lastUpdated:this.contextData.metadata.lastUpdated}}recordAccess($){this.accessLog.set($,Date.now())}enforceMemoryLimit(){if(!this.contextData)return;let $=this.contextData.layers.conversation.messages;if($.length>this.maxSize){let Z=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Z)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}import{nanoid as j$}from"nanoid";import*as I$ from"node:fs/promises";import*as V9 from"node:path";import*as T1 from"node:fs";import{createReadStream as EZ}from"node:fs";import*as e from"node:fs/promises";import*as z8 from"node:path";import{createInterface as _Z}from"node:readline";class q${filePath;constructor($){this.filePath=$}async append($){try{await e.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=JSON.stringify($)+`
1335
1335
  `;await e.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,Z),Z}}async appendBatch($){try{await e.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=$.map((J)=>JSON.stringify(J)).join(`
1336
1336
  `)+`
1337
1337
  `;await e.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,Z),Z}}async readAll(){try{if(!T1.existsSync(this.filePath))return[];let Z=(await e.readFile(this.filePath,"utf-8")).split(`
1338
- `).filter((W)=>W.trim().length>0),J=[];for(let W of Z)try{J.push(JSON.parse(W))}catch(X){console.warn(`[JSONLStore] 解析 JSON 行失败: ${W}`,X)}return J}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((Z,J)=>{if(!T1.existsSync(this.filePath)){Z();return}let W=DZ(this.filePath,"utf-8"),X=LZ({input:W,crlfDelay:Number.POSITIVE_INFINITY});X.on("line",async(Y)=>{let V=Y.trim();if(V.length===0)return;try{let B=JSON.parse(V);await $(B)}catch(B){console.warn(`[JSONLStore] 解析 JSON 行失败: ${V}`,B)}}),X.on("close",()=>Z()),X.on("error",J),W.on("error",J)})}async filter($){let Z=[];return await this.readStream((J)=>{if($(J))Z.push(J)}),Z}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!T1.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await e.stat(this.filePath),J=(await e.readFile(this.filePath,"utf-8")).split(`
1339
- `).filter((W)=>W.trim().length>0).length;return{exists:!0,size:$.size,lineCount:J}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await e.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await e.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class w8{projectPath;maxSessions;version;constructor($=N(),Z=100,J=M1()){this.projectPath=$,this.maxSessions=Z,this.version=J}createEvent($,Z,J){return{id:w$(),sessionId:Z,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:a8(this.projectPath),version:this.version,data:J}}async ensureSessionCreated($,Z){let J=W$(this.projectPath,$),W=new q$(J);if((await W.getStats()).lineCount>0)return;let Y=new Date().toISOString(),V={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,title:void 0,status:"running",agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},B=this.createEvent("session_created",$,V);await W.append(B)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;return Z}async initialize(){try{let $=t$(this.projectPath);await C$.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,X,Y){try{let V=W$(this.projectPath,$),B=new q$(V);await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=w$(),U={messageId:Q,role:Z,parentMessageId:W??void 0,createdAt:K,model:X?.model,usage:X?.usage},q=this.createEvent("message_created",$,U),H=typeof J==="string"?[this.createEvent("part_created",$,{partId:w$(),messageId:Q,partType:"text",payload:{text:J},createdAt:K})]:J.map((G)=>this.createEvent("part_created",$,{partId:w$(),messageId:Q,partType:G.type==="text"?"text":"image",payload:G.type==="text"?{text:G.text}:{mimeType:EZ(G.image_url.url)??"image/png",dataUrl:G.image_url.url},createdAt:K}));return await B.appendBatch([q,...H]),Q}catch(V){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,V),V}}async saveToolUse($,Z,J,W=null,X){try{let Y=W$(this.projectPath,$),V=new q$(Y);await this.ensureSessionCreated($,X);let B=new Date().toISOString(),K=W??w$(),Q=[];if(!W){let H={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:B};Q.push(this.createEvent("message_created",$,H))}let U=w$(),q={partId:U,messageId:K,partType:"tool_call",payload:{toolCallId:U,toolName:Z,input:J},createdAt:B};if(Q.push(this.createEvent("part_created",$,q)),Z==="Task"&&J&&typeof J==="object"){let H=J,G=typeof H.subagent_session_id==="string"?H.subagent_session_id:void 0,O=typeof H.subagent_type==="string"?H.subagent_type:void 0;if(G&&O){let F={partId:w$(),messageId:K,partType:"subtask_ref",payload:{childSessionId:G,agentType:O,status:"running",summary:typeof H.description==="string"?H.description:"",startedAt:B},createdAt:B};Q.push(this.createEvent("part_created",$,F))}}return await V.appendBatch(Q),U}catch(Y){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Y),Y}}async saveToolResult($,Z,J,W,X=null,Y,V,B){try{let K=W$(this.projectPath,$),Q=new q$(K);await this.ensureSessionCreated($,V);let U=new Date().toISOString(),q=X??w$(),H=[];if(!X){let O={messageId:q,role:"assistant",parentMessageId:void 0,createdAt:U};H.push(this.createEvent("message_created",$,O))}let G={partId:Z,messageId:q,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:Y??null},createdAt:U};if(H.push(this.createEvent("part_created",$,G)),B){let O=B.subagentStatus==="running"?null:U,F={partId:w$(),messageId:q,partType:"subtask_ref",payload:{childSessionId:B.subagentSessionId,agentType:B.subagentType,status:B.subagentStatus,summary:B.subagentSummary??"",startedAt:U,finishedAt:O},createdAt:U};H.push(this.createEvent("part_created",$,F))}return await Q.appendBatch(H),Z}catch(K){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,K),K}}async saveCompaction($,Z,J,W=null){try{let X=W$(this.projectPath,$),Y=new q$(X);await this.ensureSessionCreated($);let V=new Date().toISOString(),B=w$(),K={messageId:B,role:"system",parentMessageId:W??void 0,createdAt:V},Q=this.buildCompactionMetadata(J),U={partId:w$(),messageId:B,partType:"summary",payload:{text:Z,metadata:Q},createdAt:V},q=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,U)];return await Y.appendBatch(q),B}catch(X){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,X),X}}async initSession($){await this.ensureSessionCreated($)}async loadEvents($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();return W.length>0?W:null}catch{return null}}async loadSession($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();if(W.length===0)return null;let X=W.find((Y)=>Y.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(X?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();if(W.length===0)return null;let X=new Map;for(let K of W){if(K.type==="message_created")X.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 Q=X.get(K.data.messageId);if(Q){let U=K.data.payload;Q.content=U.text??""}}if(K.type==="part_created"&&K.data.partType==="image"){let Q=X.get(K.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
1340
- [Image]`:"[Image]"}}let Y=Array.from(X.values()),V=W[W.length-1],B=new Date(V.timestamp).getTime();return{messages:Y,topics:[],lastActivity:B}}catch{return null}}async listSessions(){try{let $=t$(this.projectPath);return(await C$.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=W$(this.projectPath,$),J=new q$(Z);if(!(await J.getStats()).exists)return null;let X=await J.readAll();if(X.length===0)return null;let Y=X[X.length-1],V=X.filter((B)=>B.type==="message_created"&&["user","assistant"].includes(B.data.role)).length;return{sessionId:$,lastActivity:new Date(Y.timestamp).getTime(),messageCount:V,topics:[]}}catch{return null}}async deleteSession($){try{let Z=W$(this.projectPath,$);await new q$(Z).delete()}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((X)=>this.getSessionSummary(X)))).filter((X)=>X!==null).sort((X,Y)=>Y.lastActivity-X.lastActivity).slice(this.maxSessions).map((X)=>X.sessionId);await Promise.all(W.map((X)=>this.deleteSession(X))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let W=W$(this.projectPath,J),Y=await new q$(W).getStats();Z+=Y.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=t$(this.projectPath);await C$.mkdir($,{recursive:!0,mode:493});let Z=V9.join($,".health-check");return await C$.writeFile(Z,"test","utf-8"),await C$.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return n8()}}function EZ($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class g0{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||b$();this.options={storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new O8(this.options.storage.maxMemorySize),this.persistent=new w8(N(),100),this.cache=new F8(this.options.storage.cacheSize,300000),this.compressor=new G8,this.filter=new B0(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let W=J.sessionId||this.generateSessionId(),X=Date.now(),Y={layers:{system:await this.createSystemContext(),session:{sessionId:W,userId:$,preferences:Z,configuration:J,startTime:X},conversation:{messages:[],topics:[],lastActivity:X},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:X}};return this.memory.setContext(Y),await this.persistent.initSession(W),this.currentSessionId=W,console.log(`新会话已创建: ${W}`),W}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new H8().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let W={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(W);let X=this.memory.getContext();if(X&&this.shouldCompress(X))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,W=null,X,Y){return this.persistent.saveMessage($,Z,J,W,X,Y)}async saveToolUse($,Z,J,W=null,X){return this.persistent.saveToolUse($,Z,J,W,X)}async saveToolResult($,Z,J,W,X=null,Y,V,B){return this.persistent.saveToolResult($,Z,J,W,X,Y,V,B)}async saveCompaction($,Z,J,W=null){return this.persistent.saveCompaction($,Z,J,W)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),W=this.shouldCompress(J),X;if(W){let Y=this.hashContext(J);if(X=this.cache.getCompressedContext(Y)??void 0,!X)X=await this.compressor.compress(J),this.cache.cacheCompressedContext(Y,X)}return{context:J,compressed:X,tokenCount:X?X.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),W=[];for(let X of J){let Y=await this.persistent.getSessionSummary(X);if(Y){let V=this.calculateRelevance($,Y.topics);if(V>0)W.push({sessionId:X,summary:`${Y.messageCount}条消息,主题:${Y.topics.join("、")}`,lastActivity:Y.lastActivity,relevanceScore:V})}}return W.sort((X,Y)=>Y.relevanceScore-X.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return B9()}generateMessageId(){return B9()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=N();return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return K9.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),W=0;for(let X of Z)if(J.includes(X.toLowerCase())||X.toLowerCase().includes(J))W+=1;return W}}class m0{chatService;contextManager;memoryAdapter;constructor($,Z){this.chatService=$,this.contextManager=Z||new g0,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}var k=M("Agent");class V${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;constructor($,Z={},J,W){this.config=$,this.runtimeOptions=Z,this.executionPipeline=J||this.createDefaultPipeline(),this.sessionRuntime=W}createDefaultPipeline(){let $=new c$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new u0($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?c0(Z):j$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){this.log(`${Z} ${$.name} (${$.model})`);let J=b1($),W=I1(),X=J&&W;if(J&&!W)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(X)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await S1({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:X,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let Y=this.executionEngine?.getContextManager();this.executionEngine=new m0(this.chatService,Y),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=c0($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await C1(),l$().length===0)throw Error(`没有可用的模型配置
1338
+ `).filter((W)=>W.trim().length>0),J=[];for(let W of Z)try{J.push(JSON.parse(W))}catch(X){console.warn(`[JSONLStore] 解析 JSON 行失败: ${W}`,X)}return J}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((Z,J)=>{if(!T1.existsSync(this.filePath)){Z();return}let W=EZ(this.filePath,"utf-8"),X=_Z({input:W,crlfDelay:Number.POSITIVE_INFINITY});X.on("line",async(Y)=>{let V=Y.trim();if(V.length===0)return;try{let B=JSON.parse(V);await $(B)}catch(B){console.warn(`[JSONLStore] 解析 JSON 行失败: ${V}`,B)}}),X.on("close",()=>Z()),X.on("error",J),W.on("error",J)})}async filter($){let Z=[];return await this.readStream((J)=>{if($(J))Z.push(J)}),Z}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!T1.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await e.stat(this.filePath),J=(await e.readFile(this.filePath,"utf-8")).split(`
1339
+ `).filter((W)=>W.trim().length>0).length;return{exists:!0,size:$.size,lineCount:J}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await e.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await e.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class w8{projectPath;maxSessions;version;constructor($=N(),Z=100,J=M1()){this.projectPath=$,this.maxSessions=Z,this.version=J}createEvent($,Z,J){return{id:j$(),sessionId:Z,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:a8(this.projectPath),version:this.version,data:J}}async ensureSessionCreated($,Z){let J=W$(this.projectPath,$),W=new q$(J);if((await W.getStats()).lineCount>0)return;let Y=new Date().toISOString(),V={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,title:void 0,status:"running",agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},B=this.createEvent("session_created",$,V);await W.append(B)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;return Z}async initialize(){try{let $=e$(this.projectPath);await I$.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,X,Y){try{let V=W$(this.projectPath,$),B=new q$(V);await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=j$(),U={messageId:Q,role:Z,parentMessageId:W??void 0,createdAt:K,model:X?.model,usage:X?.usage},q=this.createEvent("message_created",$,U),H=typeof J==="string"?[this.createEvent("part_created",$,{partId:j$(),messageId:Q,partType:"text",payload:{text:J},createdAt:K})]:J.map((G)=>this.createEvent("part_created",$,{partId:j$(),messageId:Q,partType:G.type==="text"?"text":"image",payload:G.type==="text"?{text:G.text}:{mimeType:AZ(G.image_url.url)??"image/png",dataUrl:G.image_url.url},createdAt:K}));return await B.appendBatch([q,...H]),Q}catch(V){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,V),V}}async saveToolUse($,Z,J,W=null,X){try{let Y=W$(this.projectPath,$),V=new q$(Y);await this.ensureSessionCreated($,X);let B=new Date().toISOString(),K=W??j$(),Q=[];if(!W){let H={messageId:K,role:"assistant",parentMessageId:void 0,createdAt:B};Q.push(this.createEvent("message_created",$,H))}let U=j$(),q={partId:U,messageId:K,partType:"tool_call",payload:{toolCallId:U,toolName:Z,input:J},createdAt:B};if(Q.push(this.createEvent("part_created",$,q)),Z==="Task"&&J&&typeof J==="object"){let H=J,G=typeof H.subagent_session_id==="string"?H.subagent_session_id:void 0,O=typeof H.subagent_type==="string"?H.subagent_type:void 0;if(G&&O){let F={partId:j$(),messageId:K,partType:"subtask_ref",payload:{childSessionId:G,agentType:O,status:"running",summary:typeof H.description==="string"?H.description:"",startedAt:B},createdAt:B};Q.push(this.createEvent("part_created",$,F))}}return await V.appendBatch(Q),U}catch(Y){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Y),Y}}async saveToolResult($,Z,J,W,X=null,Y,V,B){try{let K=W$(this.projectPath,$),Q=new q$(K);await this.ensureSessionCreated($,V);let U=new Date().toISOString(),q=X??j$(),H=[];if(!X){let O={messageId:q,role:"assistant",parentMessageId:void 0,createdAt:U};H.push(this.createEvent("message_created",$,O))}let G={partId:Z,messageId:q,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:Y??null},createdAt:U};if(H.push(this.createEvent("part_created",$,G)),B){let O=B.subagentStatus==="running"?null:U,F={partId:j$(),messageId:q,partType:"subtask_ref",payload:{childSessionId:B.subagentSessionId,agentType:B.subagentType,status:B.subagentStatus,summary:B.subagentSummary??"",startedAt:U,finishedAt:O},createdAt:U};H.push(this.createEvent("part_created",$,F))}return await Q.appendBatch(H),Z}catch(K){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,K),K}}async saveCompaction($,Z,J,W=null){try{let X=W$(this.projectPath,$),Y=new q$(X);await this.ensureSessionCreated($);let V=new Date().toISOString(),B=j$(),K={messageId:B,role:"system",parentMessageId:W??void 0,createdAt:V},Q=this.buildCompactionMetadata(J),U={partId:j$(),messageId:B,partType:"summary",payload:{text:Z,metadata:Q},createdAt:V},q=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,U)];return await Y.appendBatch(q),B}catch(X){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,X),X}}async initSession($){await this.ensureSessionCreated($)}async loadEvents($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();return W.length>0?W:null}catch{return null}}async loadSession($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();if(W.length===0)return null;let X=W.find((Y)=>Y.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(X?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=W$(this.projectPath,$),W=await new q$(Z).readAll();if(W.length===0)return null;let X=new Map;for(let K of W){if(K.type==="message_created")X.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 Q=X.get(K.data.messageId);if(Q){let U=K.data.payload;Q.content=U.text??""}}if(K.type==="part_created"&&K.data.partType==="image"){let Q=X.get(K.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
1340
+ [Image]`:"[Image]"}}let Y=Array.from(X.values()),V=W[W.length-1],B=new Date(V.timestamp).getTime();return{messages:Y,topics:[],lastActivity:B}}catch{return null}}async listSessions(){try{let $=e$(this.projectPath);return(await I$.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=W$(this.projectPath,$),J=new q$(Z);if(!(await J.getStats()).exists)return null;let X=await J.readAll();if(X.length===0)return null;let Y=X[X.length-1],V=X.filter((B)=>B.type==="message_created"&&["user","assistant"].includes(B.data.role)).length;return{sessionId:$,lastActivity:new Date(Y.timestamp).getTime(),messageCount:V,topics:[]}}catch{return null}}async deleteSession($){try{let Z=W$(this.projectPath,$);await new q$(Z).delete()}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((X)=>this.getSessionSummary(X)))).filter((X)=>X!==null).sort((X,Y)=>Y.lastActivity-X.lastActivity).slice(this.maxSessions).map((X)=>X.sessionId);await Promise.all(W.map((X)=>this.deleteSession(X))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Z=0;for(let J of $){let W=W$(this.projectPath,J),Y=await new q$(W).getStats();Z+=Y.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=e$(this.projectPath);await I$.mkdir($,{recursive:!0,mode:493});let Z=V9.join($,".health-check");return await I$.writeFile(Z,"test","utf-8"),await I$.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return n8()}}function AZ($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class g0{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||T$();this.options={storage:{maxMemorySize:1000,persistentPath:Z,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new O8(this.options.storage.maxMemorySize),this.persistent=new w8(N(),100),this.cache=new F8(this.options.storage.cacheSize,300000),this.compressor=new G8,this.filter=new K0(this.options.defaultFilter)}async initialize(){if(this.initialized)return;try{if(await this.persistent.initialize(),!(await this.persistent.checkStorageHealth()).isAvailable)console.warn("警告:持久化存储不可用,将仅使用内存存储");this.initialized=!0,console.log("上下文管理器初始化完成")}catch($){throw console.error("上下文管理器初始化失败:",$),$}}async createSession($,Z={},J={}){let W=J.sessionId||this.generateSessionId(),X=Date.now(),Y={layers:{system:await this.createSystemContext(),session:{sessionId:W,userId:$,preferences:Z,configuration:J,startTime:X},conversation:{messages:[],topics:[],lastActivity:X},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:X}};return this.memory.setContext(Y),await this.persistent.initSession(W),this.currentSessionId=W,console.log(`新会话已创建: ${W}`),W}async loadSession($){try{let Z=this.memory.getContext();if(!Z||Z.layers.session.sessionId!==$){let J=await this.persistent.loadEvents($);if(!J||J.length===0)return!1;if(Z=new H8().assembleContextData(J,await this.createSystemContext(),await this.createWorkspaceContext()),!Z)return!1;this.memory.setContext(Z)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Z){return console.error("加载会话失败:",Z),!1}}async addMessage($,Z,J){if(!this.currentSessionId)throw Error("没有活动会话");let W={id:this.generateMessageId(),role:$,content:Z,timestamp:Date.now(),metadata:J};this.memory.addMessage(W);let X=this.memory.getContext();if(X&&this.shouldCompress(X))await this.compressCurrentContext();this.saveCurrentSessionAsync()}async addToolCall($){if(!this.currentSessionId)throw Error("没有活动会话");if(this.memory.addToolCall($),$.status==="success"&&$.output)this.cache.cacheToolResult($.name,$.input,$.output);this.saveCurrentSessionAsync()}async saveMessage($,Z,J,W=null,X,Y){return this.persistent.saveMessage($,Z,J,W,X,Y)}async saveToolUse($,Z,J,W=null,X){return this.persistent.saveToolUse($,Z,J,W,X)}async saveToolResult($,Z,J,W,X=null,Y,V,B){return this.persistent.saveToolResult($,Z,J,W,X,Y,V,B)}async saveCompaction($,Z,J,W=null){return this.persistent.saveCompaction($,Z,J,W)}updateToolState($,Z){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Z)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Z=this.memory.getContext();if(!Z)throw Error("没有可用的上下文数据");let J=this.filter.filter(Z,$),W=this.shouldCompress(J),X;if(W){let Y=this.hashContext(J);if(X=this.cache.getCompressedContext(Y)??void 0,!X)X=await this.compressor.compress(J),this.cache.cacheCompressedContext(Y,X)}return{context:J,compressed:X,tokenCount:X?X.tokenCount:J.metadata.totalTokens}}async searchSessions($,Z=10){let J=await this.persistent.listSessions(),W=[];for(let X of J){let Y=await this.persistent.getSessionSummary(X);if(Y){let V=this.calculateRelevance($,Y.topics);if(V>0)W.push({sessionId:X,summary:`${Y.messageCount}条消息,主题:${Y.topics.join("、")}`,lastActivity:Y.lastActivity,relevanceScore:V})}}return W.sort((X,Y)=>Y.relevanceScore-X.relevanceScore).slice(0,Z)}getCachedToolResult($,Z){return this.cache.getToolResult($,Z)}async getStats(){let[$,Z,J]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Z,storage:J}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return B9()}generateMessageId(){return B9()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=N();return{projectPath:$,currentFiles:[],recentFiles:[],environment:{nodeVersion:process.version,platform:process.platform,cwd:$}}}catch($){return{currentFiles:[],recentFiles:[],environment:{}}}}shouldCompress($){return $.metadata.totalTokens>this.options.compressionThreshold}async compressCurrentContext(){let $=this.memory.getContext();if(!$)return;let Z=await this.compressor.compress($);$.layers.conversation.summary=Z.summary,this.memory.setContext($)}async saveCurrentSession(){}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Z=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return K9.createHash("md5").update(Z).digest("hex")}calculateRelevance($,Z){let J=$.toLowerCase(),W=0;for(let X of Z)if(J.includes(X.toLowerCase())||X.toLowerCase().includes(J))W+=1;return W}}class m0{chatService;contextManager;memoryAdapter;constructor($,Z){this.chatService=$,this.contextManager=Z||new g0,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Z)=>{$.push(Z)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeTask($){let Z=[{role:"user",content:$.prompt}],J=await this.chatService.chat(Z);return{taskId:$.id,content:J.content,metadata:{taskType:$.type}}}}var k=M("Agent");class V${config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;chatService;executionEngine;attachmentCollector;activeSkillContext;currentModelMaxContextTokens;currentModelId;sessionRuntime;constructor($,Z={},J,W){this.config=$,this.runtimeOptions=Z,this.executionPipeline=J||this.createDefaultPipeline(),this.sessionRuntime=W}createDefaultPipeline(){let $=new l$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new u0($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?c0(Z):N$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){this.log(`${Z} ${$.name} (${$.model})`);let J=b1($),W=I1(),X=J&&W;if(J&&!W)this.log("模型支持 Thinking,但用户未开启(按 Tab 开启)");else if(X)this.log("Thinking 模式已启用,启用 reasoning_content 支持");this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await S1({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:X,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let Y=this.executionEngine?.getContextManager();this.executionEngine=new m0(this.chatService,Y),this.currentModelId=$.id}async switchModelIfNeeded($){if(this.sessionRuntime){await this.sessionRuntime.refresh({modelId:$}),this.syncRuntimeState();return}if(!$||$===this.currentModelId)return;let Z=c0($);if(!Z){this.log(`Warning: 模型配置未找到: ${$}`);return}await this.applyModelConfig(Z,"切换模型")}static async create($={}){if($.sessionId)throw Error("Agent.create() does not accept sessionId. Create a SessionRuntime explicitly and use Agent.createWithRuntime().");if(await C1(),i$().length===0)throw Error(`没有可用的模型配置
1341
1341
 
1342
1342
  `+`请先使用以下命令添加模型:
1343
1343
  `+` /model add
1344
1344
 
1345
1345
  `+`或运行初始化向导:
1346
- `+" /init");let J=t();if(!J)throw Error("配置未初始化,请确保应用已正确启动");v1.getInstance().validateConfig(J);let X={...$};if(!X.toolWhitelist&&J.allowedTools?.length)X.toolWhitelist=J.allowedTools;if(!X.toolBlacklist&&J.disallowedTools?.length)X.toolBlacklist=J.disallowedTools;let Y=new V$(J,X);if(await Y.initialize(),X.toolWhitelist&&X.toolWhitelist.length>0)Y.applyToolWhitelist(X.toolWhitelist);if(X.toolBlacklist&&X.toolBlacklist.length>0)Y.applyToolBlacklist(X.toolBlacklist);return Y}static async createWithRuntime($,Z={}){let J=t(),W={...Z};if(!W.toolWhitelist&&J?.allowedTools?.length)W.toolWhitelist=J.allowedTools;if(!W.toolBlacklist&&J?.disallowedTools?.length)W.toolBlacklist=J.disallowedTools;let X=new V$($.getConfig(),W,$.createExecutionPipeline(W),$);return await X.initialize(),X}async initialize(){if(this.isInitialized)return;try{if(this.log("初始化Agent..."),this.sessionRuntime){await this.initializeSystemPrompt(),await this.sessionRuntime.refresh(this.runtimeOptions),this.syncRuntimeState(),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.executionPipeline.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 S0({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.executionPipeline.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async*chatStream($,Z,J){if(!this.isInitialized)throw Error("Agent未初始化");let W=await this.processAtMentionsForContent($);if(Z){let B={signal:Z.signal,...J},K;if(Z.permissionMode==="plan")K=yield*this.runPlanLoop(W,Z,B);else if(Z.permissionMode==="spec")K=yield*this.runSpecLoop(W,Z,B);else K=yield*this.runLoop(W,Z,B);if(K.success&&K.metadata?.targetMode&&Z.permissionMode==="plan"){let Q=K.metadata.targetMode,U=K.metadata.planContent;k.debug(`Plan 模式已批准,切换到 ${Q} 模式并重新执行`),await x$().setPermissionMode(Q);let q={...Z,permissionMode:Q},H=W;if(U){let G=`
1346
+ `+" /init");let J=t();if(!J)throw Error("配置未初始化,请确保应用已正确启动");v1.getInstance().validateConfig(J);let X={...$};if(!X.toolWhitelist&&J.allowedTools?.length)X.toolWhitelist=J.allowedTools;if(!X.toolBlacklist&&J.disallowedTools?.length)X.toolBlacklist=J.disallowedTools;let Y=new V$(J,X);if(await Y.initialize(),X.toolWhitelist&&X.toolWhitelist.length>0)Y.applyToolWhitelist(X.toolWhitelist);if(X.toolBlacklist&&X.toolBlacklist.length>0)Y.applyToolBlacklist(X.toolBlacklist);return Y}static async createWithRuntime($,Z={}){let J=t(),W={...Z};if(!W.toolWhitelist&&J?.allowedTools?.length)W.toolWhitelist=J.allowedTools;if(!W.toolBlacklist&&J?.disallowedTools?.length)W.toolBlacklist=J.disallowedTools;let X=new V$($.getConfig(),W,$.createExecutionPipeline(W),$);return await X.initialize(),X}async initialize(){if(this.isInitialized)return;try{if(this.log("初始化Agent..."),this.sessionRuntime){await this.initializeSystemPrompt(),await this.sessionRuntime.refresh(this.runtimeOptions),this.syncRuntimeState(),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.executionPipeline.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 P0({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000}),this.isInitialized=!0,this.log(`Agent初始化完成,已加载 ${this.executionPipeline.getRegistry().getAll().length} 个工具`)}catch($){throw this.error("Agent初始化失败",$),$}}async executeTask($){if(!this.isInitialized)throw Error("Agent未初始化");this.activeTask=$;try{this.log(`开始执行任务: ${$.id}`);let Z=await this.executionEngine.executeTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Z}catch(Z){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Z),Z}}async*chatStream($,Z,J){if(!this.isInitialized)throw Error("Agent未初始化");let W=await this.processAtMentionsForContent($);if(Z){let B={signal:Z.signal,...J},K;if(Z.permissionMode==="plan")K=yield*this.runPlanLoop(W,Z,B);else if(Z.permissionMode==="spec")K=yield*this.runSpecLoop(W,Z,B);else K=yield*this.runLoop(W,Z,B);if(K.success&&K.metadata?.targetMode&&Z.permissionMode==="plan"){let Q=K.metadata.targetMode,U=K.metadata.planContent;k.debug(`Plan 模式已批准,切换到 ${Q} 模式并重新执行`),await f$().setPermissionMode(Q);let q={...Z,permissionMode:Q},H=W;if(U){let G=`
1347
1347
 
1348
1348
  <approved-plan>
1349
1349
  ${U}
1350
1350
  </approved-plan>
1351
1351
 
1352
1352
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof W==="string")H=W+G;else H=[...W,{type:"text",text:G}]}K=yield*this.runLoop(H,q,B)}return K}let X=typeof W==="string"?W:W.filter((B)=>B.type==="text").map((B)=>B.text).join(`
1353
- `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-4fkv1hhp.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await $0({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=C0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:C0(V.text)}:B)}else X=[{type:"text",text:C0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=V1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${B1(Q)}
1353
+ `),Y={id:this.generateTaskId(),type:"simple",prompt:X};return{success:!0,finalMessage:(await this.executeTask(Y)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:W}=await import("./chunk-4fkv1hhp.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await Z0({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=I0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:I0(V.text)}:B)}else X=[{type:"text",text:I0("")},...$]}return yield*this.executeLoop(X,Z,J,W)}async*runSpecLoop($,Z,J){k.debug("Processing Spec mode message...");let W=m.getInstance(),X=Z.workspaceRoot||N();try{await W.initialize(X)}catch(U){k.warn("SpecManager initialization warning:",U)}let Y=W.getCurrentSpec(),V=await W.getSteeringContextString(),B=V1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${B1(Q)}
1354
1354
 
1355
1355
  ${$}`;else{let U=$.filter((q)=>q.type==="text");if(U.length>0){let q=U[0];K=$.map((H)=>H===q?{type:"text",text:`${B1(Q)}
1356
1356
 
1357
- ${q.text}`}:H)}else K=[{type:"text",text:B1(Q)},...$]}return yield*this.executeLoop(K,Z,J,B)}async*runLoop($,Z,J){k.debug("Processing enhanced chat message...");let W=Z.systemPrompt??await this.buildSystemPromptOnDemand();return yield*this.executeLoop($,Z,J,W)}async buildSystemPromptOnDemand(){let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await $0({projectPath:N(),replaceDefault:$,append:Z,includeEnvironment:!0,language:this.config.language})).prompt}executeLoop($,Z,J,W){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return Q9(X,$,Z,J,W)}buildLoopDependencies(){return{chatService:this.chatService,executionPipeline:this.executionPipeline,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,k.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($)}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.executionPipeline?this.executionPipeline.getRegistry().getAll():[]}getToolRegistry(){return this.executionPipeline.getRegistry()}applyToolWhitelist($){let Z=this.executionPipeline.getRegistry(),W=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of W)Z.unregister(X.name);k.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${W.length} tools)`)}applyToolBlacklist($){let Z=this.executionPipeline.getRegistry(),J=new Set($);for(let W of Z.getAll())if(J.has(W.name))Z.unregister(W.name);k.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let W=Z.get(J.kind)||0;Z.set(J.kind,W+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.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($,Z){k.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){k.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await $0({projectPath:N(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language});if(J.prompt)this.log("系统提示配置验证成功"),k.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((W)=>W.loaded).map((W)=>W.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await P1({sessionId:"default",configDir:q9.join(U9.homedir(),".blade")});k.debug(`Registering ${$.length} builtin tools...`),this.executionPipeline.getRegistry().registerAll($);let Z=this.executionPipeline.getRegistry().getAll().length;k.debug(`Builtin tools registered: ${Z} tools`),k.debug(`[Tools] ${this.executionPipeline.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw k.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{if(this.runtimeOptions.mcpConfig&&this.runtimeOptions.mcpConfig.length>0)await Y1(this.runtimeOptions.mcpConfig);let $=L$();if(Object.keys($).length===0){k.debug("No MCP servers configured");return}let Z=F$.getInstance();for(let[W,X]of Object.entries($))try{k.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,X),k.debug(`MCP server "${W}" connected`)}catch(Y){k.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();if(J.length>0)this.executionPipeline.getRegistry().registerAll(J),k.debug(`Registered ${J.length} MCP tools`),k.debug(`[MCP Tools] ${J.map((W)=>W.name).join(", ")}`)}catch($){k.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0){k.debug(`Subagents already loaded: ${P.getAllNames().join(", ")}`);return}try{let $=P.loadFromStandardLocations();if($>0)k.debug(`Loaded ${$} subagents: ${P.getAllNames().join(", ")}`);else k.debug("No subagents configured")}catch($){k.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await D0({cwd:N()});if($.skills.length>0)k.debug(`Discovered ${$.skills.length} skills: ${$.skills.map((Z)=>Z.name).join(", ")}`);else k.debug("No skills configured");for(let Z of $.errors)k.warn(`Warning: Skill loading error at ${Z.path}: ${Z.error}`)}catch($){k.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;k.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((W)=>{return Z.some((X)=>{if(X===W.name)return!0;let Y=X.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===W.name)return!0;return!1})});return k.debug(`Filtered tools: ${J.map((W)=>W.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)k.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let W of $)if(W.type==="text")Z.push(W.text);if(Z.length===0)return $;let J=Z.join(`
1357
+ ${q.text}`}:H)}else K=[{type:"text",text:B1(Q)},...$]}return yield*this.executeLoop(K,Z,J,B)}async*runLoop($,Z,J){k.debug("Processing enhanced chat message...");let W=Z.systemPrompt??await this.buildSystemPromptOnDemand();return yield*this.executeLoop($,Z,J,W)}async buildSystemPromptOnDemand(){let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt;return(await Z0({projectPath:N(),replaceDefault:$,append:Z,includeEnvironment:!0,language:this.config.language})).prompt}executeLoop($,Z,J,W){if(!this.isInitialized)throw Error("Agent未初始化");let X=this.buildLoopDependencies();return Q9(X,$,Z,J,W)}buildLoopDependencies(){return{chatService:this.chatService,executionPipeline:this.executionPipeline,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,k.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($)}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.executionPipeline?this.executionPipeline.getRegistry().getAll():[]}getToolRegistry(){return this.executionPipeline.getRegistry()}applyToolWhitelist($){let Z=this.executionPipeline.getRegistry(),W=Z.getAll().filter((X)=>!$.includes(X.name));for(let X of W)Z.unregister(X.name);k.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${W.length} tools)`)}applyToolBlacklist($){let Z=this.executionPipeline.getRegistry(),J=new Set($);for(let W of Z.getAll())if(J.has(W.name))Z.unregister(W.name);k.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let W=Z.get(J.kind)||0;Z.set(J.kind,W+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.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($,Z){k.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){k.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Z0({projectPath:N(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language});if(J.prompt)this.log("系统提示配置验证成功"),k.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((W)=>W.loaded).map((W)=>W.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await P1({sessionId:"default",configDir:q9.join(U9.homedir(),".blade")});k.debug(`Registering ${$.length} builtin tools...`),this.executionPipeline.getRegistry().registerAll($);let Z=this.executionPipeline.getRegistry().getAll().length;k.debug(`Builtin tools registered: ${Z} tools`),k.debug(`[Tools] ${this.executionPipeline.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw k.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{if(this.runtimeOptions.mcpConfig&&this.runtimeOptions.mcpConfig.length>0)await Y1(this.runtimeOptions.mcpConfig);let $=E$();if(Object.keys($).length===0){k.debug("No MCP servers configured");return}let Z=O$.getInstance();for(let[W,X]of Object.entries($))try{k.debug(`Connecting to MCP server: ${W}`),await Z.registerServer(W,X),k.debug(`MCP server "${W}" connected`)}catch(Y){k.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();if(J.length>0)this.executionPipeline.getRegistry().registerAll(J),k.debug(`Registered ${J.length} MCP tools`),k.debug(`[MCP Tools] ${J.map((W)=>W.name).join(", ")}`)}catch($){k.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0){k.debug(`Subagents already loaded: ${P.getAllNames().join(", ")}`);return}try{let $=P.loadFromStandardLocations();if($>0)k.debug(`Loaded ${$} subagents: ${P.getAllNames().join(", ")}`);else k.debug("No subagents configured")}catch($){k.warn("Failed to load subagents:",$)}}async discoverSkills(){try{let $=await L0({cwd:N()});if($.skills.length>0)k.debug(`Discovered ${$.skills.length} skills: ${$.skills.map((Z)=>Z.name).join(", ")}`);else k.debug("No skills configured");for(let Z of $.errors)k.warn(`Warning: Skill loading error at ${Z.path}: ${Z.error}`)}catch($){k.warn("Failed to discover skills:",$)}}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;k.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((W)=>{return Z.some((X)=>{if(X===W.name)return!0;let Y=X.match(/^(\w+)\(.*\)$/);if(Y&&Y[1]===W.name)return!0;return!1})});return k.debug(`Filtered tools: ${J.map((W)=>W.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)k.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let W of $)if(W.type==="text")Z.push(W.text);if(Z.length===0)return $;let J=Z.join(`
1358
1358
  `);try{let W=await this.attachmentCollector.collect(J);if(W.length===0)return $;k.debug(`Processed ${W.length} @ file mentions in multimodal message`);let X=this.buildAttachmentText(W);if(!X)return $;return[...$,{type:"text",text:X}]}catch(W){return k.error("Failed to process @ mentions in multimodal message:",W),$}}buildAttachmentText($){let Z=[],J=[];for(let X of $)if(X.type==="file"){let Y=X.metadata?.lineRange?` (lines ${X.metadata.lineRange.start}${X.metadata.lineRange.end?`-${X.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${X.path}"${Y?` range="${Y}"`:""}>`,X.content,"</file>")}else if(X.type==="directory")Z.push(`<directory path="${X.path}">`,X.content,"</directory>");else if(X.type==="error")J.push(`- @${X.path}: ${X.error}`);let W="";if(Z.length>0)W+=`
1359
1359
 
1360
1360
  <system-reminder>
@@ -1377,8 +1377,8 @@ Warning: Some files could not be loaded:
1377
1377
 
1378
1378
  Warning: Some files could not be loaded:
1379
1379
  `,X+=W.join(`
1380
- `);return X}}import i$ from"node:fs";import _Z from"node:os";import H9 from"node:path";var L0=M("Agent");class K0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=H9.join(_Z.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!K0.instance)K0.instance=new K0;return K0.instance}ensureDirectory(){if(!i$.existsSync(this.sessionsDir))i$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return H9.join(this.sessionsDir,`${Z}.json`)}saveSession($){try{let Z=this.getSessionPath($.id),J=JSON.stringify($,null,2);i$.writeFileSync(Z,J,"utf-8"),this.cache.set($.id,$),L0.debug(`Session saved: ${$.id}`)}catch(Z){L0.warn(`Failed to save session ${$.id}:`,Z)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!i$.existsSync(Z))return;let J=i$.readFileSync(Z,"utf-8"),W=JSON.parse(J);return this.cache.set($,W),W}catch(Z){L0.warn(`Failed to load session ${$}:`,Z);return}}updateSession($,Z){let J=this.loadSession($);if(!J)return;let W={...J,...Z,lastActiveAt:Date.now()};return this.saveSession(W),W}appendMessages($,Z){let J=this.loadSession($);if(!J)return;return this.updateSession($,{messages:[...J.messages,...Z]})}markCompleted($,Z,J){return this.updateSession($,{status:Z.success?"completed":"failed",result:Z,stats:J,completedAt:Date.now()})}deleteSession($){try{let Z=this.getSessionPath($);if(i$.existsSync(Z))i$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return L0.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=i$.readdirSync(this.sessionsDir),Z=[];for(let J of $){if(!J.endsWith(".json"))continue;let W=J.replace(".json",""),X=this.loadSession(W);if(X)Z.push(X)}return Z.sort((J,W)=>W.lastActiveAt-J.lastActiveAt)}catch($){return L0.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let Z=Date.now(),J=this.listSessions(),W=0;for(let X of J){if(X.status==="running")continue;if(Z-X.lastActiveAt>$){if(this.deleteSession(X.id))W++}}if(W>0)L0.info(`Cleaned up ${W} expired agent sessions`);return W}clearCache(){this.cache.clear()}}var Q0=M("Agent");class c{static instance=null;runningAgents=new Map;sessionStore=K0.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!c.instance)c.instance=new c;return c.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let W of $)if(W.status==="running"){let X=this.runningAgents.has(W.id),Y=Z-W.lastActiveAt;if(!X||Y>1800000)Q0.warn(`Cleaning up orphaned agent session: ${W.id}`),this.sessionStore.updateSession(W.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:W,parentSessionId:X,permissionMode:Y,agentId:V,existingMessages:B,taskListId:K}=$,Q=V||AZ(),U=new AbortController,q={id:Q,subagentType:Z.name,description:J,prompt:W,messages:B||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:X,taskListId:K};this.sessionStore.saveSession(q);let H=Date.now(),G=this.executeAgent(Q,Z,W,X,Y,U.signal,B,K);return this.runningAgents.set(Q,{id:Q,promise:G,abortController:U,startTime:H}),G.finally(()=>{this.runningAgents.delete(Q)}),Q0.info(`Background agent started: ${Q} (${Z.name})`),Q}async executeAgent($,Z,J,W,X,Y,V,B){let K=Date.now(),Q;try{if(Y.aborted)throw Error("Agent execution was cancelled");let U=Z.systemPrompt||"",q=Z.model&&Z.model!=="inherit"?Z.model:void 0;Q=await y1.create({sessionId:$,modelId:q});let H=await V$.createWithRuntime(Q,{sessionId:$,systemPrompt:U,toolWhitelist:Z.tools,modelId:q}),G={messages:V||[],userId:"subagent",sessionId:$,taskListId:B,workspaceRoot:N(),permissionMode:X,subagentInfo:{parentSessionId:W||"",subagentType:Z.name,isSidechain:!1}},O=await N$(H.chatStream(J,G,{signal:Y}));this.sessionStore.updateSession($,{messages:G.messages});let F=Date.now()-K,z=O.success?{success:!0,message:O.finalMessage||"",agentId:$,stats:{tokens:O.metadata?.tokensUsed||0,toolCalls:O.metadata?.toolCallsCount||0,duration:F}}:{success:!1,message:"",agentId:$,error:O.error?.message||"Unknown error",stats:{duration:F}};return this.sessionStore.markCompleted($,{success:z.success,message:z.message,error:z.error},z.stats),Q0.info(`Background agent completed: ${$} (success=${z.success})`),z}catch(U){let q=Date.now()-K,H=U instanceof Error?U.message:String(U);return this.sessionStore.markCompleted($,{success:!1,message:"",error:H},{duration:q}),Q0.warn(`Background agent failed: ${$}`,U),{success:!1,message:"",agentId:$,error:H,stats:{duration:q}}}finally{await Q?.dispose()}}getAgent($){return this.sessionStore.loadSession($)}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000){let J=this.runningAgents.get($);if(!J)return this.sessionStore.loadSession($);if(Z>0){let W=new Promise((Y)=>setTimeout(()=>Y("timeout"),Z));if(await Promise.race([J.promise,W])==="timeout")return this.sessionStore.loadSession($)}else await J.promise;return this.sessionStore.loadSession($)}resumeAgent($,Z,J,W,X){let Y=this.sessionStore.loadSession($);if(!Y){Q0.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){Q0.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:J,description:Y.description,prompt:Z,parentSessionId:W||Y.parentSessionId,permissionMode:X,agentId:$,existingMessages:Y.messages,taskListId:Y.taskListId})}killAgent($){let Z=this.runningAgents.get($);if(!Z){let J=this.sessionStore.loadSession($);if(J&&J.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return Z.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),Q0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}}import{nanoid as RZ}from"nanoid";class j8{config;constructor($){this.config=$}async execute($){let Z=Date.now(),J=$.subagentSessionId??RZ();try{let W=this.buildSystemPrompt($),X=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,Y=await V$.create({toolWhitelist:this.config.tools,modelId:X}),V="",B=0,K=0,Q={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1},U=$.onEvent,q=await N$(Y.chatStream($.prompt,{messages:[],userId:"subagent",sessionId:J,workspaceRoot:N(),permissionMode:$.permissionMode,systemPrompt:W,subagentInfo:Q}),U);if(q.success)V=q.finalMessage||"",B=q.metadata?.toolCallsCount||0,K=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let H=Date.now()-Z;return{success:!0,message:V,agentId:J,stats:{tokens:K,toolCalls:B,duration:H}}}catch(W){let X=Date.now()-Z;return{success:!1,message:"",agentId:J,error:W instanceof Error?W.message:String(W),stats:{duration:X}}}}buildSystemPrompt($){return this.config.systemPrompt||""}}import{EventEmitter as kZ}from"events";class E0 extends kZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!E0.instance)E0.instance=new E0;return E0.instance}publish($,Z,J){this.emit("event",{sessionId:$,type:Z,properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var U0=E0.getInstance();import{basename as a$}from"node:path";function N8($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?a$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?a$(J):"file"}`}case"Read":{let J=Z.file_path;return`Reading ${J?a$(J):"file"}`}case"Bash":{let{command:J,description:W}=Z;if(W)return`${W}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:W}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(W){let Y=a$(W);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:W}=Z;return J?`Updating task ${W||""}: ${J}`.trim():`Updating task ${W||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?a$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:W}=Z;if(J)return`${W||"Agent"}: ${J}`;return`Running ${W||"agent"}`}case"LSP":{let{operation:J,filePath:W}=Z,X=W?a$(W):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?a$(J):"notebook"}`}case"EnterSpecMode":return`Creating spec: ${Z.name||"new spec"}`;case"UpdateSpec":return`Updating ${Z.fileType}.md`;case"GetSpecContext":return"Getting spec context";case"TransitionSpecPhase":return`Transitioning to: ${Z.targetPhase}`;case"AddTask":{let J=Z.title;return`Adding task: ${(J&&J.length>30?J.substring(0,30)+"...":J)||"task"}`}case"UpdateTaskStatus":{let{status:J,taskId:W}=Z;return`${J==="completed"?"[done]":J==="in_progress"?"[in progress]":"[paused]"} Task ${W?.substring(0,8)||""}: ${J}`}case"ValidateSpec":return"Validating spec";case"ExitSpecMode":return Z.archive?"Archiving spec":"Exiting spec mode";default:return`${$}`}}function bZ($,Z){if(!Z?.success&&!Z?.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!!Z.metadata?.detail}}function TZ($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!G9(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let W=5,X=J.slice(0,W).map((Y)=>Y.relative_path);if(J.length>W)X.push(`... (+${J.length-W} more)`);return X.join(`
1381
- `)}case"Grep":{let J=Z.llmContent;if(!Array.isArray(J)||!J.length)return null;let W=5,X=J.slice(0,W).map((Y)=>{let V=a$(Y.file_path);if(Y.line_number)return`${V}:${Y.line_number}`;return V});if(J.length>W)X.push(`... (+${J.length-W} more)`);return X.join(`
1380
+ `);return X}}import a$ from"node:fs";import RZ from"node:os";import H9 from"node:path";var E0=M("Agent");class Q0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=H9.join(RZ.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!Q0.instance)Q0.instance=new Q0;return Q0.instance}ensureDirectory(){if(!a$.existsSync(this.sessionsDir))a$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return H9.join(this.sessionsDir,`${Z}.json`)}saveSession($){try{let Z=this.getSessionPath($.id),J=JSON.stringify($,null,2);a$.writeFileSync(Z,J,"utf-8"),this.cache.set($.id,$),E0.debug(`Session saved: ${$.id}`)}catch(Z){E0.warn(`Failed to save session ${$.id}:`,Z)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!a$.existsSync(Z))return;let J=a$.readFileSync(Z,"utf-8"),W=JSON.parse(J);return this.cache.set($,W),W}catch(Z){E0.warn(`Failed to load session ${$}:`,Z);return}}updateSession($,Z){let J=this.loadSession($);if(!J)return;let W={...J,...Z,lastActiveAt:Date.now()};return this.saveSession(W),W}appendMessages($,Z){let J=this.loadSession($);if(!J)return;return this.updateSession($,{messages:[...J.messages,...Z]})}markCompleted($,Z,J){return this.updateSession($,{status:Z.success?"completed":"failed",result:Z,stats:J,completedAt:Date.now()})}deleteSession($){try{let Z=this.getSessionPath($);if(a$.existsSync(Z))a$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return E0.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=a$.readdirSync(this.sessionsDir),Z=[];for(let J of $){if(!J.endsWith(".json"))continue;let W=J.replace(".json",""),X=this.loadSession(W);if(X)Z.push(X)}return Z.sort((J,W)=>W.lastActiveAt-J.lastActiveAt)}catch($){return E0.warn("Failed to list sessions:",$),[]}}listRunningSessions(){return this.listSessions().filter(($)=>$.status==="running")}cleanupExpiredSessions($=604800000){let Z=Date.now(),J=this.listSessions(),W=0;for(let X of J){if(X.status==="running")continue;if(Z-X.lastActiveAt>$){if(this.deleteSession(X.id))W++}}if(W>0)E0.info(`Cleaned up ${W} expired agent sessions`);return W}clearCache(){this.cache.clear()}}var U0=M("Agent");class c{static instance=null;runningAgents=new Map;sessionStore=Q0.getInstance();constructor(){this.cleanupOrphanedSessions()}static getInstance(){if(!c.instance)c.instance=new c;return c.instance}cleanupOrphanedSessions(){let $=this.sessionStore.listSessions(),Z=Date.now(),J=1800000;for(let W of $)if(W.status==="running"){let X=this.runningAgents.has(W.id),Y=Z-W.lastActiveAt;if(!X||Y>1800000)U0.warn(`Cleaning up orphaned agent session: ${W.id}`),this.sessionStore.updateSession(W.id,{status:"failed",result:{success:!1,message:"",error:"Session was orphaned (process restart or timeout)"},completedAt:Z})}}startBackgroundAgent($){let{config:Z,description:J,prompt:W,parentSessionId:X,permissionMode:Y,agentId:V,existingMessages:B,taskListId:K}=$,Q=V||kZ(),U=new AbortController,q={id:Q,subagentType:Z.name,description:J,prompt:W,messages:B||[],status:"running",createdAt:Date.now(),lastActiveAt:Date.now(),parentSessionId:X,taskListId:K};this.sessionStore.saveSession(q);let H=Date.now(),G=this.executeAgent(Q,Z,W,X,Y,U.signal,B,K);return this.runningAgents.set(Q,{id:Q,promise:G,abortController:U,startTime:H}),G.finally(()=>{this.runningAgents.delete(Q)}),U0.info(`Background agent started: ${Q} (${Z.name})`),Q}async executeAgent($,Z,J,W,X,Y,V,B){let K=Date.now(),Q;try{if(Y.aborted)throw Error("Agent execution was cancelled");let U=Z.systemPrompt||"",q=Z.model&&Z.model!=="inherit"?Z.model:void 0;Q=await y1.create({sessionId:$,modelId:q});let H=await V$.createWithRuntime(Q,{sessionId:$,systemPrompt:U,toolWhitelist:Z.tools,modelId:q}),G={messages:V||[],userId:"subagent",sessionId:$,taskListId:B,workspaceRoot:N(),permissionMode:X,subagentInfo:{parentSessionId:W||"",subagentType:Z.name,isSidechain:!1}},O=await D$(H.chatStream(J,G,{signal:Y}));this.sessionStore.updateSession($,{messages:G.messages});let F=Date.now()-K,z=O.success?{success:!0,message:O.finalMessage||"",agentId:$,stats:{tokens:O.metadata?.tokensUsed||0,toolCalls:O.metadata?.toolCallsCount||0,duration:F}}:{success:!1,message:"",agentId:$,error:O.error?.message||"Unknown error",stats:{duration:F}};return this.sessionStore.markCompleted($,{success:z.success,message:z.message,error:z.error},z.stats),U0.info(`Background agent completed: ${$} (success=${z.success})`),z}catch(U){let q=Date.now()-K,H=U instanceof Error?U.message:String(U);return this.sessionStore.markCompleted($,{success:!1,message:"",error:H},{duration:q}),U0.warn(`Background agent failed: ${$}`,U),{success:!1,message:"",agentId:$,error:H,stats:{duration:q}}}finally{await Q?.dispose()}}getAgent($){return this.sessionStore.loadSession($)}isRunning($){return this.runningAgents.has($)}async waitForCompletion($,Z=30000){let J=this.runningAgents.get($);if(!J)return this.sessionStore.loadSession($);if(Z>0){let W=new Promise((Y)=>setTimeout(()=>Y("timeout"),Z));if(await Promise.race([J.promise,W])==="timeout")return this.sessionStore.loadSession($)}else await J.promise;return this.sessionStore.loadSession($)}resumeAgent($,Z,J,W,X){let Y=this.sessionStore.loadSession($);if(!Y){U0.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){U0.warn(`Cannot resume agent ${$}: still running`);return}return this.startBackgroundAgent({config:J,description:Y.description,prompt:Z,parentSessionId:W||Y.parentSessionId,permissionMode:X,agentId:$,existingMessages:Y.messages,taskListId:Y.taskListId})}killAgent($){let Z=this.runningAgents.get($);if(!Z){let J=this.sessionStore.loadSession($);if(J&&J.status==="running")this.sessionStore.updateSession($,{status:"cancelled"});return!1}return Z.abortController.abort(),this.sessionStore.updateSession($,{status:"cancelled"}),U0.info(`Background agent cancelled: ${$}`),!0}listAll(){return this.sessionStore.listSessions()}listRunning(){return this.sessionStore.listRunningSessions()}getRunningCount(){return this.runningAgents.size}killAll(){for(let[$]of this.runningAgents)this.killAgent($)}cleanupExpiredSessions($){return this.sessionStore.cleanupExpiredSessions($)}}import{nanoid as bZ}from"nanoid";class j8{config;constructor($){this.config=$}async execute($){let Z=Date.now(),J=$.subagentSessionId??bZ();try{let W=this.buildSystemPrompt($),X=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,Y=await V$.create({toolWhitelist:this.config.tools,modelId:X}),V="",B=0,K=0,Q={parentSessionId:$.parentSessionId||"",subagentType:this.config.name,isSidechain:!1},U=$.onEvent,q=await D$(Y.chatStream($.prompt,{messages:[],userId:"subagent",sessionId:J,workspaceRoot:N(),permissionMode:$.permissionMode,systemPrompt:W,subagentInfo:Q}),U);if(q.success)V=q.finalMessage||"",B=q.metadata?.toolCallsCount||0,K=q.metadata?.tokensUsed||0;else throw Error(q.error?.message||"Subagent execution failed");let H=Date.now()-Z;return{success:!0,message:V,agentId:J,stats:{tokens:K,toolCalls:B,duration:H}}}catch(W){let X=Date.now()-Z;return{success:!1,message:"",agentId:J,error:W instanceof Error?W.message:String(W),stats:{duration:X}}}}buildSystemPrompt($){return this.config.systemPrompt||""}}import{EventEmitter as TZ}from"events";class _0 extends TZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!_0.instance)_0.instance=new _0;return _0.instance}publish($,Z,J){this.emit("event",{sessionId:$,type:Z,properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var q0=_0.getInstance();import{basename as n$}from"node:path";function N8($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?n$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?n$(J):"file"}`}case"Read":{let J=Z.file_path;return`Reading ${J?n$(J):"file"}`}case"Bash":{let{command:J,description:W}=Z;if(W)return`${W}`;return`Running: ${J?J.substring(0,40):"command"}${J&&J.length>40?"...":""}`}case"Glob":return`Searching files: ${Z.pattern}`;case"Grep":{let{pattern:J,path:W}=Z,X=J&&J.length>30?J.substring(0,30)+"...":J;if(W){let Y=n$(W);return`Searching "${X}" in ${Y}`}return`Searching "${X}"`}case"WebFetch":{let J=Z.url;if(J)try{return`Fetching ${new URL(J).hostname}`}catch{return"Fetching URL"}return"Fetching URL"}case"WebSearch":{let J=Z.query;return`Searching: "${J&&J.length>40?J.substring(0,40)+"...":J}"`}case"TaskCreate":return`Creating task: ${Z.subject||"task"}`;case"TaskGet":return`Reading task ${Z.taskId||""}`.trim();case"TaskUpdate":{let{status:J,taskId:W}=Z;return J?`Updating task ${W||""}: ${J}`.trim():`Updating task ${W||""}`.trim()}case"TaskList":return"Listing tasks";case"UndoEdit":{let J=Z.file_path;return`Undoing changes to ${J?n$(J):"file"}`}case"Skill":return`Invoking skill: ${Z.skill}`;case"Task":{let{description:J,subagent_type:W}=Z;if(J)return`${W||"Agent"}: ${J}`;return`Running ${W||"agent"}`}case"LSP":{let{operation:J,filePath:W}=Z,X=W?n$(W):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?n$(J):"notebook"}`}case"EnterSpecMode":return`Creating spec: ${Z.name||"new spec"}`;case"UpdateSpec":return`Updating ${Z.fileType}.md`;case"GetSpecContext":return"Getting spec context";case"TransitionSpecPhase":return`Transitioning to: ${Z.targetPhase}`;case"AddTask":{let J=Z.title;return`Adding task: ${(J&&J.length>30?J.substring(0,30)+"...":J)||"task"}`}case"UpdateTaskStatus":{let{status:J,taskId:W}=Z;return`${J==="completed"?"[done]":J==="in_progress"?"[in progress]":"[paused]"} Task ${W?.substring(0,8)||""}: ${J}`}case"ValidateSpec":return"Validating spec";case"ExitSpecMode":return Z.archive?"Archiving spec":"Exiting spec mode";default:return`${$}`}}function MZ($,Z){if(!Z?.success&&!Z?.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!!Z.metadata?.detail}}function vZ($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!G9(Z.metadata))return null;let{matches:J}=Z.metadata;if(!J?.length)return null;let W=5,X=J.slice(0,W).map((Y)=>Y.relative_path);if(J.length>W)X.push(`... (+${J.length-W} more)`);return X.join(`
1381
+ `)}case"Grep":{let J=Z.llmContent;if(!Array.isArray(J)||!J.length)return null;let W=5,X=J.slice(0,W).map((Y)=>{let V=n$(Y.file_path);if(Y.line_number)return`${V}:${Y.line_number}`;return V});if(J.length>W)X.push(`... (+${J.length-W} more)`);return X.join(`
1382
1382
  `)}case"Read":{let J=Z.metadata?.content_preview||Z.llmContent;if(typeof J!=="string"||!J)return null;let W=J.split(`
1383
1383
  `),X=W.length,Y=3;if(X<=Y+1)return J;return`${W.slice(0,Y).join(`
1384
1384
  `)}
@@ -1397,9 +1397,9 @@ Warning: Some files could not be loaded:
1397
1397
  `),X=5;if(W.length>5)return W.slice(0,5).join(`
1398
1398
  `)+`
1399
1399
  ... (+${W.length-5} more)`;return J||null}if(Array.isArray(J)&&J.length>0){let X=J.slice(0,5).map((Y)=>Y.title||Y.url||"");if(J.length>5)X.push(`... (+${J.length-5} more)`);return X.join(`
1400
- `)}return null}case"Task":{let J=Z.metadata?.subagentSummary||(typeof Z.llmContent==="string"?Z.llmContent:null);if(!J)return null;return J.length>200?`${J.slice(0,200)}...`:J}case"TaskOutput":{let J=typeof Z.llmContent==="string"?Z.llmContent:null;if(!J)return null;return J.length>200?`${J.slice(0,200)}...`:J}case"Skill":{let J=Z.metadata?.skillName;return J?`Skill: ${J}`:null}default:{let J=Z.metadata?.detail;return typeof J==="string"?J:null}}}function O9($,Z){let J=Z.success?"ok":Z.error?"fail":"warn",W=Z.metadata?.summary||(Z.success?"执行成功":"执行失败"),X=bZ($,Z)?TZ($,Z)||void 0:void 0;return{status:J,summary:W,detail:X}}function z9($){let Z={ok:"[OK]",fail:"[FAIL]",warn:"[WARN]"}[$.status];return $.detail?`${Z} ${$.summary}
1401
- ${$.detail}`:`${Z} ${$.summary}`}function MZ($){let Z=$.message||"Unknown error";if(Z.includes("Too Many Requests")||Z.includes("429")){let J=$.cause;if(J?.responseBody)try{let W=JSON.parse(J.responseBody);if(W.message)return W.message}catch{}return"API 请求过于频繁,请稍后重试"}if(Z.includes("ECONNREFUSED")||Z.includes("ETIMEDOUT"))return"网络连接失败,请检查网络设置";if(Z.includes("401")||Z.includes("Unauthorized"))return"API 认证失败,请检查 API Key 配置";return Z.split(`
1402
- `)[0]}function vZ($){return P.getAllNames().includes($)}function CZ(){let $=P.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function IZ(){return`
1400
+ `)}return null}case"Task":{let J=Z.metadata?.subagentSummary||(typeof Z.llmContent==="string"?Z.llmContent:null);if(!J)return null;return J.length>200?`${J.slice(0,200)}...`:J}case"TaskOutput":{let J=typeof Z.llmContent==="string"?Z.llmContent:null;if(!J)return null;return J.length>200?`${J.slice(0,200)}...`:J}case"Skill":{let J=Z.metadata?.skillName;return J?`Skill: ${J}`:null}default:{let J=Z.metadata?.detail;return typeof J==="string"?J:null}}}function O9($,Z){let J=Z.success?"ok":Z.error?"fail":"warn",W=Z.metadata?.summary||(Z.success?"执行成功":"执行失败"),X=MZ($,Z)?vZ($,Z)||void 0:void 0;return{status:J,summary:W,detail:X}}function z9($){let Z={ok:"[OK]",fail:"[FAIL]",warn:"[WARN]"}[$.status];return $.detail?`${Z} ${$.summary}
1401
+ ${$.detail}`:`${Z} ${$.summary}`}function CZ($){let Z=$.message||"Unknown error";if(Z.includes("Too Many Requests")||Z.includes("429")){let J=$.cause;if(J?.responseBody)try{let W=JSON.parse(J.responseBody);if(W.message)return W.message}catch{}return"API 请求过于频繁,请稍后重试"}if(Z.includes("ECONNREFUSED")||Z.includes("ETIMEDOUT"))return"网络连接失败,请检查网络设置";if(Z.includes("401")||Z.includes("Unauthorized"))return"API 认证失败,请检查 API Key 配置";return Z.split(`
1402
+ `)[0]}function IZ($){return P.getAllNames().includes($)}function SZ(){let $=P.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function PZ(){return`
1403
1403
  ## Task
1404
1404
 
1405
1405
  Launch a new agent to handle complex, multi-step tasks autonomously.
@@ -1430,7 +1430,7 @@ Usage notes:
1430
1430
  - 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
1431
1431
  - 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.
1432
1432
  - 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.
1433
- `.trim()}var D8=D({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:q0.object({subagent_type:q0.string().refine(vZ,($)=>({message:`Invalid subagent type: "${$}". Available: ${CZ()}`})).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:q0.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:q0.string().min(10).describe("Detailed task instructions"),run_in_background:q0.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),resume:q0.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript."),subagent_session_id:q0.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 IZ()},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"],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($,Z){let{subagent_type:J,description:W,prompt:X,run_in_background:Y=!1,resume:V,subagent_session_id:B}=$,{updateOutput:K}=Z,Q=Z.sessionId,U=typeof B==="string"&&B.length>0?B:typeof V==="string"&&V.length>0?V:w9();try{let q=P.getAllNames(),H=P.getSubagent(J);if(!H)return{success:!1,llmContent:`Unknown subagent type: ${J}. Available types: ${q.join(", ")||"none"}`,error:{type:"execution_error",message:`Unknown subagent type: ${J}`},metadata:{summary:`未知的 subagent 类型: ${J}`}};if(V)return PZ(V,X,H,W,Z);if(Y)return SZ(H,W,X,Z,U);K?.(`启动 ${J} subagent: ${W}`);let G=new j8(H),O=w9(8);l0.getState().app.actions.startSubagentProgress(O,J,W);let F={prompt:X,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode,subagentSessionId:U,onEvent:(E)=>{switch(E.kind){case"tool_start":{let j=E.toolCall,b="function"in j?j.function.name:"Unknown";if(l0.getState().app.actions.updateSubagentTool(b),Q){if(U0.publish(Q,"subagent.update",{subagentSessionId:U,toolName:b}),"function"in j)U0.publish(Q,"subagent.tool.start",{subagentSessionId:U,toolCallId:j.id,toolName:b,arguments:j.function.arguments,toolKind:E.toolKind})}break}case"tool_result":{if(!Q)break;let j=E.toolCall;if(!("function"in j))break;U0.publish(Q,"subagent.tool.result",{subagentSessionId:U,toolCallId:j.id,toolName:j.function.name,success:!E.result.error,summary:E.result.metadata?.summary,output:z9(O9(j.function.name,E.result)),metadata:E.result.metadata});break}case"content_delta":{if(Q)U0.publish(Q,"subagent.delta",{subagentSessionId:U,delta:E.delta});break}case"thinking_delta":{if(Q)U0.publish(Q,"subagent.thinking.delta",{subagentSessionId:U,delta:E.delta});break}case"stream_end":{if(Q)U0.publish(Q,"subagent.stream.end",{subagentSessionId:U});break}default:break}}};K?.("执行任务中...");let z=Date.now(),w=await G.execute(F),L=Date.now()-z;try{let j=await X$.getInstance().executeSubagentStopHooks(J,{projectDir:N(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",taskDescription:W,success:w.success,resultSummary:w.message.slice(0,500),error:w.error});if(!j.shouldStop&&j.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${j.continueReason}`);let b={prompt:j.continueReason,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode},a=Date.now();w=await G.execute(b),L+=Date.now()-a}if(j.warning)console.warn(`[Task] SubagentStop hook warning: ${j.warning}`)}catch(E){console.warn("[Task] SubagentStop hook execution failed:",E)}if(l0.getState().app.actions.completeSubagentProgress(w.success),w.success)return{success:!0,llmContent:w.message,metadata:{summary:`${J} 任务完成`,subagent_type:J,description:W,duration:L,stats:w.stats,subagentSessionId:U,subagentType:J,subagentStatus:"completed",subagentSummary:w.message.slice(0,500)}};else return{success:!1,llmContent:`Subagent execution failed: ${w.error}`,error:{type:"execution_error",message:w.error||"Unknown error"},metadata:{summary:`${J} 任务失败`,subagentSessionId:U,subagentType:J,subagentStatus:"failed"}}}catch(q){l0.getState().app.actions.completeSubagentProgress(!1);let H=q,G=MZ(H);return{success:!1,llmContent:`Subagent execution error: ${H.message}`,error:{type:"execution_error",message:H.message,details:q},metadata:{summary:`Subagent 执行异常: ${G}`}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});function SZ($,Z,J,W,X){let V=c.getInstance().startBackgroundAgent({config:$,description:Z,prompt:J,parentSessionId:W.sessionId,permissionMode:W.permissionMode,agentId:X});return{success:!0,llmContent:{agent_id:V,status:"running",message:`Agent started in background. Use TaskOutput(task_id: "${V}") to retrieve results.`},metadata:{summary:`后台 Agent 已启动: ${V}`,agent_id:V,subagent_type:$.name,description:Z,background:!0,subagentSessionId:V,subagentType:$.name,subagentStatus:"running"}}}function PZ($,Z,J,W,X){let Y=c.getInstance();if(!Y.getAgent($))return{success:!1,llmContent:`Cannot resume agent ${$}: session not found`,error:{type:"execution_error",message:`Agent session not found: ${$}`},metadata:{summary:`恢复 Agent 失败: 会话不存在 ${$}`}};if(Y.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,error:{type:"execution_error",message:`Agent is still running: ${$}`},metadata:{summary:`恢复 Agent 失败: 仍在运行 ${$}`}};let B=Y.resumeAgent($,Z,J,X.sessionId,X.permissionMode);if(!B)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:B,status:"running",resumed_from:$,message:`Agent resumed in background. Use TaskOutput(task_id: "${B}") to retrieve results.`},metadata:{summary:`恢复 Agent: ${B}`,agent_id:B,resumed_from:$,subagent_type:J.name,description:W,background:!0,subagentSessionId:B,subagentType:J.name,subagentStatus:"running"}}}import{z as x1}from"zod";var L8=D({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:x1.object({task_id:x1.string().min(1).describe("The task ID to get output from"),block:x1.boolean().default(!0).describe("Whether to wait for completion"),timeout:x1.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
1433
+ `.trim()}var D8=D({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:H0.object({subagent_type:H0.string().refine(IZ,($)=>({message:`Invalid subagent type: "${$}". Available: ${SZ()}`})).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:H0.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:H0.string().min(10).describe("Detailed task instructions"),run_in_background:H0.boolean().default(!1).describe("Set to true to run this agent in the background. Use TaskOutput to read the output later."),resume:H0.string().optional().describe("Optional agent ID to resume from. If provided, the agent will continue from the previous execution transcript."),subagent_session_id:H0.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 PZ()},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"],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($,Z){let{subagent_type:J,description:W,prompt:X,run_in_background:Y=!1,resume:V,subagent_session_id:B}=$,{updateOutput:K}=Z,Q=Z.sessionId,U=typeof B==="string"&&B.length>0?B:typeof V==="string"&&V.length>0?V:w9();try{let q=P.getAllNames(),H=P.getSubagent(J);if(!H)return{success:!1,llmContent:`Unknown subagent type: ${J}. Available types: ${q.join(", ")||"none"}`,error:{type:"execution_error",message:`Unknown subagent type: ${J}`},metadata:{summary:`未知的 subagent 类型: ${J}`}};if(V)return xZ(V,X,H,W,Z);if(Y)return yZ(H,W,X,Z,U);K?.(`启动 ${J} subagent: ${W}`);let G=new j8(H),O=w9(8);l0.getState().app.actions.startSubagentProgress(O,J,W);let F={prompt:X,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode,subagentSessionId:U,onEvent:(E)=>{switch(E.kind){case"tool_start":{let j=E.toolCall,b="function"in j?j.function.name:"Unknown";if(l0.getState().app.actions.updateSubagentTool(b),Q){if(q0.publish(Q,"subagent.update",{subagentSessionId:U,toolName:b}),"function"in j)q0.publish(Q,"subagent.tool.start",{subagentSessionId:U,toolCallId:j.id,toolName:b,arguments:j.function.arguments,toolKind:E.toolKind})}break}case"tool_result":{if(!Q)break;let j=E.toolCall;if(!("function"in j))break;q0.publish(Q,"subagent.tool.result",{subagentSessionId:U,toolCallId:j.id,toolName:j.function.name,success:!E.result.error,summary:E.result.metadata?.summary,output:z9(O9(j.function.name,E.result)),metadata:E.result.metadata});break}case"content_delta":{if(Q)q0.publish(Q,"subagent.delta",{subagentSessionId:U,delta:E.delta});break}case"thinking_delta":{if(Q)q0.publish(Q,"subagent.thinking.delta",{subagentSessionId:U,delta:E.delta});break}case"stream_end":{if(Q)q0.publish(Q,"subagent.stream.end",{subagentSessionId:U});break}default:break}}};K?.("执行任务中...");let z=Date.now(),w=await G.execute(F),L=Date.now()-z;try{let j=await X$.getInstance().executeSubagentStopHooks(J,{projectDir:N(),sessionId:Z.sessionId||"unknown",permissionMode:Z.permissionMode||"default",taskDescription:W,success:w.success,resultSummary:w.message.slice(0,500),error:w.error});if(!j.shouldStop&&j.continueReason){console.log(`[Task] SubagentStop hook 阻止停止,继续执行: ${j.continueReason}`);let b={prompt:j.continueReason,parentSessionId:Z.sessionId,permissionMode:Z.permissionMode},a=Date.now();w=await G.execute(b),L+=Date.now()-a}if(j.warning)console.warn(`[Task] SubagentStop hook warning: ${j.warning}`)}catch(E){console.warn("[Task] SubagentStop hook execution failed:",E)}if(l0.getState().app.actions.completeSubagentProgress(w.success),w.success)return{success:!0,llmContent:w.message,metadata:{summary:`${J} 任务完成`,subagent_type:J,description:W,duration:L,stats:w.stats,subagentSessionId:U,subagentType:J,subagentStatus:"completed",subagentSummary:w.message.slice(0,500)}};else return{success:!1,llmContent:`Subagent execution failed: ${w.error}`,error:{type:"execution_error",message:w.error||"Unknown error"},metadata:{summary:`${J} 任务失败`,subagentSessionId:U,subagentType:J,subagentStatus:"failed"}}}catch(q){l0.getState().app.actions.completeSubagentProgress(!1);let H=q,G=CZ(H);return{success:!1,llmContent:`Subagent execution error: ${H.message}`,error:{type:"execution_error",message:H.message,details:q},metadata:{summary:`Subagent 执行异常: ${G}`}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});function yZ($,Z,J,W,X){let V=c.getInstance().startBackgroundAgent({config:$,description:Z,prompt:J,parentSessionId:W.sessionId,permissionMode:W.permissionMode,agentId:X});return{success:!0,llmContent:{agent_id:V,status:"running",message:`Agent started in background. Use TaskOutput(task_id: "${V}") to retrieve results.`},metadata:{summary:`后台 Agent 已启动: ${V}`,agent_id:V,subagent_type:$.name,description:Z,background:!0,subagentSessionId:V,subagentType:$.name,subagentStatus:"running"}}}function xZ($,Z,J,W,X){let Y=c.getInstance();if(!Y.getAgent($))return{success:!1,llmContent:`Cannot resume agent ${$}: session not found`,error:{type:"execution_error",message:`Agent session not found: ${$}`},metadata:{summary:`恢复 Agent 失败: 会话不存在 ${$}`}};if(Y.isRunning($))return{success:!1,llmContent:`Cannot resume agent ${$}: still running`,error:{type:"execution_error",message:`Agent is still running: ${$}`},metadata:{summary:`恢复 Agent 失败: 仍在运行 ${$}`}};let B=Y.resumeAgent($,Z,J,X.sessionId,X.permissionMode);if(!B)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:B,status:"running",resumed_from:$,message:`Agent resumed in background. Use TaskOutput(task_id: "${B}") to retrieve results.`},metadata:{summary:`恢复 Agent: ${B}`,agent_id:B,resumed_from:$,subagent_type:J.name,description:W,background:!0,subagentSessionId:B,subagentType:J.name,subagentStatus:"running"}}}import{z as x1}from"zod";var L8=D({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:x1.object({task_id:x1.string().min(1).describe("The task ID to get output from"),block:x1.boolean().default(!0).describe("Whether to wait for completion"),timeout:x1.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
1434
1434
  - Retrieves output from a running or completed task (background shell, agent, or remote session)
1435
1435
  - Takes a task_id parameter identifying the task
1436
1436
  - Returns the task output along with status information
@@ -1438,7 +1438,7 @@ Usage notes:
1438
1438
  - Use block=false for non-blocking check of current status
1439
1439
  - Task IDs can be found using the /tasks command
1440
1440
  - Works with all task types: background shells, async agents, and remote sessions
1441
- `.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:W,timeout:X}=$;if(J.startsWith("bash_"))return j9(J,W,X);let Y=n.getInstance(),V=c.getInstance();if(Y.getProcess(J))return j9(J,W,X);if(V.getAgent(J))return yZ(J,W,X);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function j9($,Z,J){let W=n.getInstance(),X=W.getProcess($);if(!X)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running")await xZ($,J);let Y=W.consumeOutput($);if(!Y)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let V={task_id:Y.id,type:"shell",status:Y.status,command:Y.command,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal,started_at:new Date(Y.startedAt).toISOString(),finished_at:Y.endedAt?new Date(Y.endedAt).toISOString():void 0,stdout:Y.stdout,stderr:Y.stderr};return{success:!0,llmContent:V,metadata:{summary:`获取任务输出: ${$}`,...V}}}async function yZ($,Z,J){let W=c.getInstance(),X=W.getAgent($);if(!X)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running"){if(X=await W.waitForCompletion($,J),!X)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let Y={task_id:X.id,type:"agent",status:X.status,subagent_type:X.subagentType,description:X.description,created_at:new Date(X.createdAt).toISOString(),last_active_at:new Date(X.lastActiveAt).toISOString(),completed_at:X.completedAt?new Date(X.completedAt).toISOString():void 0,result:X.result,stats:X.stats},V=X.status==="completed"?"completed":X.status==="failed"?"failed":"running";return{success:!0,llmContent:Y,metadata:{summary:`获取任务输出: ${$}`,...Y,subagentSessionId:X.id,subagentType:X.subagentType,subagentStatus:V,subagentSummary:typeof X.result?.message==="string"?X.result.message.slice(0,500):void 0}}}async function xZ($,Z){let J=n.getInstance(),W=Date.now();return new Promise((X)=>{let Y=setInterval(()=>{let V=J.getProcess($);if(!V||V.status!=="running"){clearInterval(Y),X();return}if(Date.now()-W>=Z){clearInterval(Y),X();return}},100)})}import{z as x}from"zod";import*as _0 from"fs/promises";import*as h1 from"path";import{z as l}from"zod";var E8=l.enum(["pending","in_progress","completed"]),fZ=l.enum(["high","medium","low"]),N9=l.object({id:l.string(),subject:l.string(),description:l.string(),status:E8,activeForm:l.string().optional(),owner:l.string().optional(),priority:fZ.default("medium"),blocks:l.array(l.string()).default([]),blockedBy:l.array(l.string()).default([]),metadata:l.record(l.unknown()).optional(),createdAt:l.string(),startedAt:l.string().optional(),completedAt:l.string().optional()});class H0{static instances=new Map;tasks=[];nextId=1;loaded=!1;filePath;constructor($,Z){this.filePath=h1.join(Z,"tasks",`${$}-agent-${$}.json`)}static getInstance($,Z){let J=`${$}-${Z}`;if(!H0.instances.has(J))H0.instances.set(J,new H0($,Z));return H0.instances.get(J)}async createTask($){await this.ensureLoaded();let Z=new Date().toISOString(),J={id:String(this.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:[],metadata:$.metadata,createdAt:Z};return this.nextId+=1,this.tasks=[...this.tasks,J],await this.saveTasks(),J}async getTask($){return await this.ensureLoaded(),this.tasks.find((Z)=>Z.id===$)||null}async listTasks(){return await this.ensureLoaded(),this.getSortedTasks()}async updateTask($,Z){await this.ensureLoaded();let J=this.tasks.findIndex((B)=>B.id===$);if(J===-1)return{task:null,updatedFields:[]};let W=this.tasks[J],X=[],Y={...W};if(Z.subject!==void 0&&Z.subject!==W.subject)Y.subject=Z.subject,X.push("subject");if(Z.description!==void 0&&Z.description!==W.description)Y.description=Z.description,X.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==W.activeForm)Y.activeForm=Z.activeForm,X.push("activeForm");if(Z.owner!==void 0&&Z.owner!==W.owner)Y.owner=Z.owner,X.push("owner");if(Z.metadata!==void 0)Y.metadata=pZ(W.metadata,Z.metadata),X.push("metadata");let V;if(Z.status!==void 0&&Z.status!==W.status){if(Y.status=Z.status,Z.status==="in_progress"&&!W.startedAt)Y.startedAt=new Date().toISOString();if(Z.status==="completed"&&!W.completedAt)Y.completedAt=new Date().toISOString();V={from:W.status,to:Z.status},X.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(Y.blocks=f1([...W.blocks,...Z.addBlocks]),Y.blocks.length!==W.blocks.length)X.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(Y.blockedBy=f1([...W.blockedBy,...Z.addBlockedBy]),Y.blockedBy.length!==W.blockedBy.length)X.push("blockedBy")}return this.tasks=this.tasks.map((B)=>B.id===$?Y:B),await this.syncDependencyEdges(Y,Z.addBlocks,Z.addBlockedBy),await this.saveTasks(),{task:Y,updatedFields:X,statusChange:V}}async deleteTask($){await this.ensureLoaded();let Z=this.tasks.length;if(this.tasks=this.tasks.filter((J)=>J.id!==$).map((J)=>({...J,blocks:J.blocks.filter((W)=>W!==$),blockedBy:J.blockedBy.filter((W)=>W!==$)})),this.tasks.length===Z)return!1;return await this.saveTasks(),!0}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){let $={in_progress:0,pending:1,completed:2},Z={high:0,medium:1,low:2};return[...this.tasks].sort((J,W)=>{let X=$[J.status]-$[W.status];if(X!==0)return X;let Y=Z[J.priority]-Z[W.priority];if(Y!==0)return Y;return Number(J.id)-Number(W.id)})}async syncDependencyEdges($,Z,J){for(let W of Z||[])this.tasks=this.tasks.map((X)=>X.id===W?{...X,blockedBy:f1([...X.blockedBy,$.id])}:X);for(let W of J||[])this.tasks=this.tasks.map((X)=>X.id===W?{...X,blocks:f1([...X.blocks,$.id])}:X)}async ensureLoaded(){if(!this.loaded)await this.loadTasks(),this.loaded=!0}async loadTasks(){try{let $=JSON.parse(await _0.readFile(this.filePath,"utf-8")),Z=hZ($);this.tasks=Z.tasks,this.nextId=Z.nextId}catch($){if($.code!=="ENOENT")console.warn("加载任务列表失败:",$);this.tasks=[],this.nextId=1}}async saveTasks(){await _0.mkdir(h1.dirname(this.filePath),{recursive:!0,mode:493});let $={nextId:this.nextId,tasks:this.tasks};await _0.writeFile(this.filePath,JSON.stringify($,null,2),"utf-8")}}function hZ($){let J=($&&typeof $==="object"&&Array.isArray($.tasks)?$.tasks:Array.isArray($)?$:[]).map((Y)=>N9.safeParse(Y)).filter((Y)=>Y.success).map((Y)=>Y.data),W=$&&typeof $==="object"&&typeof $.nextId==="number"?$.nextId:void 0,X=J.reduce((Y,V)=>{let B=Number(V.id);return Number.isFinite(B)?Math.max(Y,B):Y},0);return{tasks:J,nextId:Math.max(W||1,X+1)}}function f1($){return[...new Set($.filter(Boolean))]}function pZ($,Z){let J={...$||{}};for(let[W,X]of Object.entries(Z))if(X===null)delete J[W];else J[W]=X;return J}var dZ=`Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
1441
+ `.trim(),usageNotes:["task_id is required - the ID returned when starting a background task","block=true (default) waits for task completion","block=false returns current status immediately","timeout defaults to 30000ms (30 seconds), max 600000ms (10 minutes)"],examples:[{description:"Get output from a background shell",params:{task_id:"bash_abc123",block:!0,timeout:30000}},{description:"Check agent status without blocking",params:{task_id:"session_xyz789",block:!1}}]},async execute($,Z){let{task_id:J,block:W,timeout:X}=$;if(J.startsWith("bash_"))return j9(J,W,X);let Y=n.getInstance(),V=c.getInstance();if(Y.getProcess(J))return j9(J,W,X);if(V.getAgent(J))return fZ(J,W,X);return{success:!1,llmContent:`Unknown task ID: ${J}.`,error:{type:"validation_error",message:`Unknown task ID: ${J}`},metadata:{summary:`获取任务输出: ${J} (未知ID)`}}},version:"1.0.0",category:"Task",tags:["task","output","background","shell","agent"],extractSignatureContent:($)=>$.task_id,abstractPermissionRule:()=>"*"});async function j9($,Z,J){let W=n.getInstance(),X=W.getProcess($);if(!X)return{success:!1,llmContent:`Shell not found: ${$}`,error:{type:"execution_error",message:"Shell 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running")await hZ($,J);let Y=W.consumeOutput($);if(!Y)return{success:!1,llmContent:`Failed to get output for shell: ${$}`,error:{type:"execution_error",message:"Failed to consume output"},metadata:{summary:`获取任务输出: ${$} (失败)`}};let V={task_id:Y.id,type:"shell",status:Y.status,command:Y.command,pid:Y.pid,exit_code:Y.exitCode,signal:Y.signal,started_at:new Date(Y.startedAt).toISOString(),finished_at:Y.endedAt?new Date(Y.endedAt).toISOString():void 0,stdout:Y.stdout,stderr:Y.stderr};return{success:!0,llmContent:V,metadata:{summary:`获取任务输出: ${$}`,...V}}}async function fZ($,Z,J){let W=c.getInstance(),X=W.getAgent($);if(!X)return{success:!1,llmContent:`Agent not found: ${$}`,error:{type:"execution_error",message:"Agent 会话不存在或已清理"},metadata:{summary:`获取任务输出: ${$} (未找到)`}};if(Z&&X.status==="running"){if(X=await W.waitForCompletion($,J),!X)return{success:!1,llmContent:`Failed to wait for agent: ${$}`,error:{type:"execution_error",message:"Wait for completion failed"},metadata:{summary:`获取任务输出: ${$} (等待失败)`}}}let Y={task_id:X.id,type:"agent",status:X.status,subagent_type:X.subagentType,description:X.description,created_at:new Date(X.createdAt).toISOString(),last_active_at:new Date(X.lastActiveAt).toISOString(),completed_at:X.completedAt?new Date(X.completedAt).toISOString():void 0,result:X.result,stats:X.stats},V=X.status==="completed"?"completed":X.status==="failed"?"failed":"running";return{success:!0,llmContent:Y,metadata:{summary:`获取任务输出: ${$}`,...Y,subagentSessionId:X.id,subagentType:X.subagentType,subagentStatus:V,subagentSummary:typeof X.result?.message==="string"?X.result.message.slice(0,500):void 0}}}async function hZ($,Z){let J=n.getInstance(),W=Date.now();return new Promise((X)=>{let Y=setInterval(()=>{let V=J.getProcess($);if(!V||V.status!=="running"){clearInterval(Y),X();return}if(Date.now()-W>=Z){clearInterval(Y),X();return}},100)})}import{z as x}from"zod";import*as A0 from"fs/promises";import*as h1 from"path";import{z as l}from"zod";var E8=l.enum(["pending","in_progress","completed"]),pZ=l.enum(["high","medium","low"]),N9=l.object({id:l.string(),subject:l.string(),description:l.string(),status:E8,activeForm:l.string().optional(),owner:l.string().optional(),priority:pZ.default("medium"),blocks:l.array(l.string()).default([]),blockedBy:l.array(l.string()).default([]),metadata:l.record(l.unknown()).optional(),createdAt:l.string(),startedAt:l.string().optional(),completedAt:l.string().optional()});class G0{static instances=new Map;tasks=[];nextId=1;loaded=!1;filePath;constructor($,Z){this.filePath=h1.join(Z,"tasks",`${$}-agent-${$}.json`)}static getInstance($,Z){let J=`${$}-${Z}`;if(!G0.instances.has(J))G0.instances.set(J,new G0($,Z));return G0.instances.get(J)}async createTask($){await this.ensureLoaded();let Z=new Date().toISOString(),J={id:String(this.nextId),subject:$.subject,description:$.description,activeForm:$.activeForm,owner:$.owner,priority:$.priority||"medium",status:"pending",blocks:[],blockedBy:[],metadata:$.metadata,createdAt:Z};return this.nextId+=1,this.tasks=[...this.tasks,J],await this.saveTasks(),J}async getTask($){return await this.ensureLoaded(),this.tasks.find((Z)=>Z.id===$)||null}async listTasks(){return await this.ensureLoaded(),this.getSortedTasks()}async updateTask($,Z){await this.ensureLoaded();let J=this.tasks.findIndex((B)=>B.id===$);if(J===-1)return{task:null,updatedFields:[]};let W=this.tasks[J],X=[],Y={...W};if(Z.subject!==void 0&&Z.subject!==W.subject)Y.subject=Z.subject,X.push("subject");if(Z.description!==void 0&&Z.description!==W.description)Y.description=Z.description,X.push("description");if(Z.activeForm!==void 0&&Z.activeForm!==W.activeForm)Y.activeForm=Z.activeForm,X.push("activeForm");if(Z.owner!==void 0&&Z.owner!==W.owner)Y.owner=Z.owner,X.push("owner");if(Z.metadata!==void 0)Y.metadata=uZ(W.metadata,Z.metadata),X.push("metadata");let V;if(Z.status!==void 0&&Z.status!==W.status){if(Y.status=Z.status,Z.status==="in_progress"&&!W.startedAt)Y.startedAt=new Date().toISOString();if(Z.status==="completed"&&!W.completedAt)Y.completedAt=new Date().toISOString();V={from:W.status,to:Z.status},X.push("status")}if(Z.addBlocks&&Z.addBlocks.length>0){if(Y.blocks=f1([...W.blocks,...Z.addBlocks]),Y.blocks.length!==W.blocks.length)X.push("blocks")}if(Z.addBlockedBy&&Z.addBlockedBy.length>0){if(Y.blockedBy=f1([...W.blockedBy,...Z.addBlockedBy]),Y.blockedBy.length!==W.blockedBy.length)X.push("blockedBy")}return this.tasks=this.tasks.map((B)=>B.id===$?Y:B),await this.syncDependencyEdges(Y,Z.addBlocks,Z.addBlockedBy),await this.saveTasks(),{task:Y,updatedFields:X,statusChange:V}}async deleteTask($){await this.ensureLoaded();let Z=this.tasks.length;if(this.tasks=this.tasks.filter((J)=>J.id!==$).map((J)=>({...J,blocks:J.blocks.filter((W)=>W!==$),blockedBy:J.blockedBy.filter((W)=>W!==$)})),this.tasks.length===Z)return!1;return await this.saveTasks(),!0}getStats(){return{total:this.tasks.length,completed:this.tasks.filter(($)=>$.status==="completed").length,inProgress:this.tasks.filter(($)=>$.status==="in_progress").length,pending:this.tasks.filter(($)=>$.status==="pending").length}}getSortedTasks(){let $={in_progress:0,pending:1,completed:2},Z={high:0,medium:1,low:2};return[...this.tasks].sort((J,W)=>{let X=$[J.status]-$[W.status];if(X!==0)return X;let Y=Z[J.priority]-Z[W.priority];if(Y!==0)return Y;return Number(J.id)-Number(W.id)})}async syncDependencyEdges($,Z,J){for(let W of Z||[])this.tasks=this.tasks.map((X)=>X.id===W?{...X,blockedBy:f1([...X.blockedBy,$.id])}:X);for(let W of J||[])this.tasks=this.tasks.map((X)=>X.id===W?{...X,blocks:f1([...X.blocks,$.id])}:X)}async ensureLoaded(){if(!this.loaded)await this.loadTasks(),this.loaded=!0}async loadTasks(){try{let $=JSON.parse(await A0.readFile(this.filePath,"utf-8")),Z=dZ($);this.tasks=Z.tasks,this.nextId=Z.nextId}catch($){if($.code!=="ENOENT")console.warn("加载任务列表失败:",$);this.tasks=[],this.nextId=1}}async saveTasks(){await A0.mkdir(h1.dirname(this.filePath),{recursive:!0,mode:493});let $={nextId:this.nextId,tasks:this.tasks};await A0.writeFile(this.filePath,JSON.stringify($,null,2),"utf-8")}}function dZ($){let J=($&&typeof $==="object"&&Array.isArray($.tasks)?$.tasks:Array.isArray($)?$:[]).map((Y)=>N9.safeParse(Y)).filter((Y)=>Y.success).map((Y)=>Y.data),W=$&&typeof $==="object"&&typeof $.nextId==="number"?$.nextId:void 0,X=J.reduce((Y,V)=>{let B=Number(V.id);return Number.isFinite(B)?Math.max(Y,B):Y},0);return{tasks:J,nextId:Math.max(W||1,X+1)}}function f1($){return[...new Set($.filter(Boolean))]}function uZ($,Z){let J={...$||{}};for(let[W,X]of Object.entries(Z))if(X===null)delete J[W];else J[W]=X;return J}var gZ=`Use this tool to create a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
1442
1442
 
1443
1443
  ## When to Use This Tool
1444
1444
 
@@ -1466,7 +1466,7 @@ Skip using this tool when:
1466
1466
  - description: What needs to be done
1467
1467
  - activeForm: Present continuous form shown while in_progress (for example, "Running tests")
1468
1468
 
1469
- All tasks are created with status pending. Check TaskList first to avoid creating duplicates.`,uZ=`Use this tool to update a task in the task list.
1469
+ All tasks are created with status pending. Check TaskList first to avoid creating duplicates.`,mZ=`Use this tool to update a task in the task list.
1470
1470
 
1471
1471
  ## When to Use This Tool
1472
1472
 
@@ -1482,7 +1482,7 @@ Only mark a task completed when it is fully accomplished. If tests are failing,
1482
1482
 
1483
1483
  Status progresses: pending -> in_progress -> completed
1484
1484
 
1485
- Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function _8($){return[gZ($),mZ($),cZ($),lZ($)]}function gZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskCreate",displayName:"Task Create",kind:"readonly",isConcurrencySafe:!1,schema:x.object({subject:x.string().min(1).describe("A brief title for the task"),description:x.string().min(1).describe("What needs to be done"),activeForm:x.string().optional().describe("Present continuous form shown while in_progress"),owner:x.string().optional().describe("Optional owner for the task"),priority:x.enum(["high","medium","low"]).default("medium"),metadata:x.record(x.unknown()).optional()}),description:{short:"Create a new task in the task list",long:dZ},async execute(W,X){try{let Y=d1(X,Z,J),V=await Y.createTask(W),B=await Y.listTasks(),K=Y.getStats();return p1({llmContent:{task:G0(V),tasks:B.map(G0),stats:K},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:B,stats:K})}catch(Y){return u1(Y,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.subject,abstractPermissionRule:()=>"*"})}function mZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskGet",displayName:"Task Get",kind:"readonly",isConcurrencySafe:!0,schema:x.object({taskId:x.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(W,X){try{let V=await d1(X,Z,J).getTask(W.taskId);return{success:!0,llmContent:{task:V?G0(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${W.taskId} 不存在`}}}catch(Y){return u1(Y,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function cZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskUpdate",displayName:"Task Update",kind:"readonly",isConcurrencySafe:!1,schema:x.object({taskId:x.string().min(1).describe("The ID of the task to update"),subject:x.string().min(1).optional().describe("New subject for the task"),description:x.string().min(1).optional().describe("New description for the task"),activeForm:x.string().min(1).optional(),status:E8.or(x.literal("deleted")).optional(),owner:x.string().optional(),addBlocks:x.array(x.string()).optional(),addBlockedBy:x.array(x.string()).optional(),metadata:x.record(x.unknown()).optional()}),description:{short:"Update a task in the task list",long:uZ},async execute(W,X){try{let Y=d1(X,Z,J),V=W.status;if(V==="deleted"){let H=await Y.deleteTask(W.taskId),G=await Y.listTasks(),O=Y.getStats();return p1({llmContent:{success:H,taskId:W.taskId,updatedFields:H?["deleted"]:[],error:H?void 0:"Task not found",tasks:G.map(G0),stats:O},summary:H?`删除任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:G,stats:O})}let{task:B,updatedFields:K,statusChange:Q}=await Y.updateTask(W.taskId,{subject:W.subject,description:W.description,activeForm:W.activeForm,status:V,owner:W.owner,addBlocks:W.addBlocks,addBlockedBy:W.addBlockedBy,metadata:W.metadata}),U=await Y.listTasks(),q=Y.getStats();return p1({llmContent:{success:B!==null,taskId:W.taskId,task:B?G0(B):null,updatedFields:K,error:B?void 0:"Task not found",statusChange:Q,tasks:U.map(G0),stats:q},summary:B?`更新任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:U,stats:q})}catch(Y){return u1(Y,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function lZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskList",displayName:"Task List",kind:"readonly",isConcurrencySafe:!0,schema:x.object({}),description:{short:"List all tasks",long:"Use this tool to check the current task list and avoid creating duplicate tasks."},async execute(W,X){try{let Y=d1(X,Z,J),V=await Y.listTasks(),B=Y.getStats();return p1({llmContent:{tasks:V.map(G0),stats:B},summary:V.length===0?"暂无任务":`任务列表 (${B.completed}/${B.total} 完成)`,tasks:V,stats:B})}catch(Y){return u1(Y,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function d1($,Z,J){return H0.getInstance($.taskListId||$.sessionId||Z,J)}function p1($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function u1($,Z){let J=$;return{success:!1,llmContent:`Task operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function G0($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as D9 from"os";import*as L9 from"path";import{z as $$}from"zod";import*as n$ from"fs/promises";import*as i0 from"path";class H${static instances=new Map;teamsDir;constructor($){this.teamsDir=i0.join($,"teams")}static getInstance($){if(!H$.instances.has($))H$.instances.set($,new H$($));return H$.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return i0.join(this.teamsDir,H$.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),W=this.getTeamFilePath(Z),X={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead@${Z}`,leadSessionId:$.leadSessionId,teamFilePath:W,members:[{id:`team-lead@${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(X),X}async loadTeam($){try{let Z=await n$.readFile(this.getTeamFilePath($),"utf-8");return iZ(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await n$.mkdir(i0.dirname(Z),{recursive:!0,mode:493}),await n$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await n$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let W=await this.loadTeam(J.name);if(W)Z.push(W)}return Z.sort((J,W)=>W.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),W={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((X)=>X.status==="running"?{...X,status:"cancelled",completedAt:X.completedAt||J}:X)};return await this.saveTeam(W),W}async getUniqueTeamName($){let Z=H$.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,W=2;while(await this.loadTeam(J))J=`${Z}-${W}`,W+=1;return J}}function iZ($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var aZ=$$.object({name:$$.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:$$.string().min(1).describe("Registered subagent type to launch for this teammate"),description:$$.string().min(3).max(100).optional(),prompt:$$.string().min(10).describe("Detailed assignment for this teammate")});function R8($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||L9.join(D9.homedir(),".blade");return[nZ({sessionId:Z,configDir:J}),rZ({configDir:J}),sZ({configDir:J})]}function nZ($){return D({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:$$.object({team_name:$$.string().min(1).describe("Name for the new agent team"),description:$$.string().optional().describe("Team description or purpose"),agent_type:$$.string().optional().describe("Optional role/type label for the team lead"),members:$$.array(aZ).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:Z3(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{oZ();let W=$3(Z.members.map((H)=>H.name));if(W)return g1(`Duplicate teammate name: ${W}`,"创建团队失败");let X=Z.members.map((H)=>H.subagent_type).filter((H)=>!P.getSubagent(H));if(X.length>0)return g1(`Invalid subagent type(s): ${[...new Set(X)].join(", ")}. Available: ${P.getAllNames().join(", ")||"none"}`,"创建团队失败");let Y=c.getInstance(),V=H$.getInstance($.configDir),B=await V.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),K=Date.now(),Q=[];for(let H of Z.members){let G=P.getSubagent(H.subagent_type);if(!G)continue;let O=`${H$.sanitizeName(H.name)}@${B.name}`,F=tZ({teamName:B.name,teamDescription:Z.description,memberName:H.name,memberPrompt:H.prompt,teamFileHint:B.teamFilePath}),z=Y.startBackgroundAgent({config:G,description:H.description||H.name,prompt:F,parentSessionId:J.sessionId||$.sessionId,permissionMode:J.permissionMode,agentId:O,taskListId:B.name});Q.push({id:O,name:H.name,subagentType:H.subagent_type,description:H.description||H.name,prompt:H.prompt,agentId:z,status:"running",joinedAt:K})}let U={...B,members:[...B.members,...Q],updatedAt:Date.now()};await V.saveTeam(U);let q=await A8(V,U);return{success:!0,llmContent:{team:A0(q),message:Q.length>0?`Team created with ${Q.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} (${Q.length} teammates)`,team_name:q.name,team_file_path:q.teamFilePath,lead_agent_id:q.leadAgentId,member_agent_ids:Q.map((H)=>H.agentId).filter(Boolean)}}}catch(W){return k8(W,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function rZ($){return D({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:$$.object({team_name:$$.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(Z){try{let J=H$.getInstance($.configDir);if(!Z.team_name){let Y=await Promise.all((await J.listTeams()).map((V)=>A8(J,V)));return{success:!0,llmContent:{teams:Y.map(A0)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(A0)}}}let W=await J.loadTeam(Z.team_name);if(!W)return g1(`Team not found: ${Z.team_name}`,"读取团队失败");let X=await A8(J,W);return{success:!0,llmContent:{team:A0(X)},metadata:{summary:`Agent Team ${X.name}: ${E9(X)}`,team:A0(X)}}}catch(J){return k8(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function sZ($){return D({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:$$.object({team_name:$$.string().min(1).describe("Team name to delete"),kill_running:$$.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(Z){try{let J=H$.getInstance($.configDir),W=await J.loadTeam(Z.team_name);if(!W)return g1(`Team not found: ${Z.team_name}`,"删除团队失败");let X=c.getInstance(),Y=[];if(Z.kill_running){for(let B of W.members)if(B.agentId&&X.killAgent(B.agentId))Y.push(B.agentId)}let V=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:V?A0(V):null,killed_agent_ids:Y},metadata:{summary:`删除 Agent Team: ${W.name}`,team_name:W.name,killed_agent_ids:Y}}}catch(J){return k8(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function oZ(){if(P.getAllNames().length===0)P.loadFromStandardLocations()}function tZ($){return`
1485
+ Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function _8($){return[cZ($),lZ($),iZ($),aZ($)]}function cZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskCreate",displayName:"Task Create",kind:"readonly",isConcurrencySafe:!1,schema:x.object({subject:x.string().min(1).describe("A brief title for the task"),description:x.string().min(1).describe("What needs to be done"),activeForm:x.string().optional().describe("Present continuous form shown while in_progress"),owner:x.string().optional().describe("Optional owner for the task"),priority:x.enum(["high","medium","low"]).default("medium"),metadata:x.record(x.unknown()).optional()}),description:{short:"Create a new task in the task list",long:gZ},async execute(W,X){try{let Y=d1(X,Z,J),V=await Y.createTask(W),B=await Y.listTasks(),K=Y.getStats();return p1({llmContent:{task:F0(V),tasks:B.map(F0),stats:K},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:B,stats:K})}catch(Y){return u1(Y,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.subject,abstractPermissionRule:()=>"*"})}function lZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskGet",displayName:"Task Get",kind:"readonly",isConcurrencySafe:!0,schema:x.object({taskId:x.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(W,X){try{let V=await d1(X,Z,J).getTask(W.taskId);return{success:!0,llmContent:{task:V?F0(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${W.taskId} 不存在`}}}catch(Y){return u1(Y,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function iZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskUpdate",displayName:"Task Update",kind:"readonly",isConcurrencySafe:!1,schema:x.object({taskId:x.string().min(1).describe("The ID of the task to update"),subject:x.string().min(1).optional().describe("New subject for the task"),description:x.string().min(1).optional().describe("New description for the task"),activeForm:x.string().min(1).optional(),status:E8.or(x.literal("deleted")).optional(),owner:x.string().optional(),addBlocks:x.array(x.string()).optional(),addBlockedBy:x.array(x.string()).optional(),metadata:x.record(x.unknown()).optional()}),description:{short:"Update a task in the task list",long:mZ},async execute(W,X){try{let Y=d1(X,Z,J),V=W.status;if(V==="deleted"){let H=await Y.deleteTask(W.taskId),G=await Y.listTasks(),O=Y.getStats();return p1({llmContent:{success:H,taskId:W.taskId,updatedFields:H?["deleted"]:[],error:H?void 0:"Task not found",tasks:G.map(F0),stats:O},summary:H?`删除任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:G,stats:O})}let{task:B,updatedFields:K,statusChange:Q}=await Y.updateTask(W.taskId,{subject:W.subject,description:W.description,activeForm:W.activeForm,status:V,owner:W.owner,addBlocks:W.addBlocks,addBlockedBy:W.addBlockedBy,metadata:W.metadata}),U=await Y.listTasks(),q=Y.getStats();return p1({llmContent:{success:B!==null,taskId:W.taskId,task:B?F0(B):null,updatedFields:K,error:B?void 0:"Task not found",statusChange:Q,tasks:U.map(F0),stats:q},summary:B?`更新任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:U,stats:q})}catch(Y){return u1(Y,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function aZ($){let{sessionId:Z,configDir:J}=$;return D({name:"TaskList",displayName:"Task List",kind:"readonly",isConcurrencySafe:!0,schema:x.object({}),description:{short:"List all tasks",long:"Use this tool to check the current task list and avoid creating duplicate tasks."},async execute(W,X){try{let Y=d1(X,Z,J),V=await Y.listTasks(),B=Y.getStats();return p1({llmContent:{tasks:V.map(F0),stats:B},summary:V.length===0?"暂无任务":`任务列表 (${B.completed}/${B.total} 完成)`,tasks:V,stats:B})}catch(Y){return u1(Y,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function d1($,Z,J){return G0.getInstance($.taskListId||$.sessionId||Z,J)}function p1($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function u1($,Z){let J=$;return{success:!1,llmContent:`Task operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function F0($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as D9 from"os";import*as L9 from"path";import{z as $$}from"zod";import*as r$ from"fs/promises";import*as i0 from"path";class H${static instances=new Map;teamsDir;constructor($){this.teamsDir=i0.join($,"teams")}static getInstance($){if(!H$.instances.has($))H$.instances.set($,new H$($));return H$.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return i0.join(this.teamsDir,H$.sanitizeName($),"config.json")}async createTeam($){let Z=await this.getUniqueTeamName($.name),J=Date.now(),W=this.getTeamFilePath(Z),X={name:Z,description:$.description,createdAt:J,updatedAt:J,leadAgentId:`team-lead@${Z}`,leadSessionId:$.leadSessionId,teamFilePath:W,members:[{id:`team-lead@${Z}`,name:"team-lead",subagentType:$.leadAgentType||"team-lead",description:"Team lead for coordinating the agent team",status:"leader",joinedAt:J},...$.members]};return await this.saveTeam(X),X}async loadTeam($){try{let Z=await r$.readFile(this.getTeamFilePath($),"utf-8");return nZ(JSON.parse(Z))}catch(Z){if(Z.code!=="ENOENT")console.warn(`Failed to load team ${$}:`,Z);return}}async saveTeam($){let Z=this.getTeamFilePath($.name);await r$.mkdir(i0.dirname(Z),{recursive:!0,mode:493}),await r$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await r$.readdir(this.teamsDir,{withFileTypes:!0}),Z=[];for(let J of $){if(!J.isDirectory())continue;let W=await this.loadTeam(J.name);if(W)Z.push(W)}return Z.sort((J,W)=>W.updatedAt-J.updatedAt)}catch($){if($.code!=="ENOENT")console.warn("Failed to list teams:",$);return[]}}async markDeleted($){let Z=await this.loadTeam($);if(!Z)return;let J=Date.now(),W={...Z,deletedAt:J,updatedAt:J,members:Z.members.map((X)=>X.status==="running"?{...X,status:"cancelled",completedAt:X.completedAt||J}:X)};return await this.saveTeam(W),W}async getUniqueTeamName($){let Z=H$.sanitizeName($);if(!Z)throw Error("team_name must contain at least one letter or number");let J=Z,W=2;while(await this.loadTeam(J))J=`${Z}-${W}`,W+=1;return J}}function nZ($){if(!$||typeof $!=="object")return;let Z=$;if(!Z.name||!Array.isArray(Z.members))return;return{name:Z.name,description:Z.description,createdAt:typeof Z.createdAt==="number"?Z.createdAt:Date.now(),updatedAt:typeof Z.updatedAt==="number"?Z.updatedAt:Date.now(),deletedAt:typeof Z.deletedAt==="number"?Z.deletedAt:void 0,leadAgentId:Z.leadAgentId||`team-lead@${Z.name}`,leadSessionId:Z.leadSessionId,teamFilePath:Z.teamFilePath||"",members:Z.members.map((J)=>({id:J.id,name:J.name,subagentType:J.subagentType,description:J.description,prompt:J.prompt,agentId:J.agentId,status:J.status,joinedAt:J.joinedAt,completedAt:J.completedAt}))}}var rZ=$$.object({name:$$.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:$$.string().min(1).describe("Registered subagent type to launch for this teammate"),description:$$.string().min(3).max(100).optional(),prompt:$$.string().min(10).describe("Detailed assignment for this teammate")});function R8($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||L9.join(D9.homedir(),".blade");return[sZ({sessionId:Z,configDir:J}),oZ({configDir:J}),tZ({configDir:J})]}function sZ($){return D({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:$$.object({team_name:$$.string().min(1).describe("Name for the new agent team"),description:$$.string().optional().describe("Team description or purpose"),agent_type:$$.string().optional().describe("Optional role/type label for the team lead"),members:$$.array(rZ).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:W3(),usageNotes:["Use TeamCreate when a task benefits from coordinated parallel agents","Each member is launched with the requested subagent_type as a background agent","Use TeamStatus to inspect teammate progress and collect agent IDs for TaskOutput"]},async execute(Z,J){try{eZ();let W=J3(Z.members.map((H)=>H.name));if(W)return g1(`Duplicate teammate name: ${W}`,"创建团队失败");let X=Z.members.map((H)=>H.subagent_type).filter((H)=>!P.getSubagent(H));if(X.length>0)return g1(`Invalid subagent type(s): ${[...new Set(X)].join(", ")}. Available: ${P.getAllNames().join(", ")||"none"}`,"创建团队失败");let Y=c.getInstance(),V=H$.getInstance($.configDir),B=await V.createTeam({name:Z.team_name,description:Z.description,leadAgentType:Z.agent_type,leadSessionId:J.sessionId||$.sessionId,members:[]}),K=Date.now(),Q=[];for(let H of Z.members){let G=P.getSubagent(H.subagent_type);if(!G)continue;let O=`${H$.sanitizeName(H.name)}@${B.name}`,F=$3({teamName:B.name,teamDescription:Z.description,memberName:H.name,memberPrompt:H.prompt,teamFileHint:B.teamFilePath}),z=Y.startBackgroundAgent({config:G,description:H.description||H.name,prompt:F,parentSessionId:J.sessionId||$.sessionId,permissionMode:J.permissionMode,agentId:O,taskListId:B.name});Q.push({id:O,name:H.name,subagentType:H.subagent_type,description:H.description||H.name,prompt:H.prompt,agentId:z,status:"running",joinedAt:K})}let U={...B,members:[...B.members,...Q],updatedAt:Date.now()};await V.saveTeam(U);let q=await A8(V,U);return{success:!0,llmContent:{team:R0(q),message:Q.length>0?`Team created with ${Q.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} (${Q.length} teammates)`,team_name:q.name,team_file_path:q.teamFilePath,lead_agent_id:q.leadAgentId,member_agent_ids:Q.map((H)=>H.agentId).filter(Boolean)}}}catch(W){return k8(W,"创建团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","agents","subagent","parallel"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function oZ($){return D({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:$$.object({team_name:$$.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(Z){try{let J=H$.getInstance($.configDir);if(!Z.team_name){let Y=await Promise.all((await J.listTeams()).map((V)=>A8(J,V)));return{success:!0,llmContent:{teams:Y.map(R0)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(R0)}}}let W=await J.loadTeam(Z.team_name);if(!W)return g1(`Team not found: ${Z.team_name}`,"读取团队失败");let X=await A8(J,W);return{success:!0,llmContent:{team:R0(X)},metadata:{summary:`Agent Team ${X.name}: ${E9(X)}`,team:R0(X)}}}catch(J){return k8(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function tZ($){return D({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:$$.object({team_name:$$.string().min(1).describe("Team name to delete"),kill_running:$$.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(Z){try{let J=H$.getInstance($.configDir),W=await J.loadTeam(Z.team_name);if(!W)return g1(`Team not found: ${Z.team_name}`,"删除团队失败");let X=c.getInstance(),Y=[];if(Z.kill_running){for(let B of W.members)if(B.agentId&&X.killAgent(B.agentId))Y.push(B.agentId)}let V=await J.markDeleted(Z.team_name);return{success:!0,llmContent:{team:V?R0(V):null,killed_agent_ids:Y},metadata:{summary:`删除 Agent Team: ${W.name}`,team_name:W.name,killed_agent_ids:Y}}}catch(J){return k8(J,"删除团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","delete","agents"],extractSignatureContent:(Z)=>Z.team_name,abstractPermissionRule:()=>"*"})}function eZ(){if(P.getAllNames().length===0)P.loadFromStandardLocations()}function $3($){return`
1486
1486
  You are ${$.memberName}, a teammate in Blade agent team "${$.teamName}".
1487
1487
 
1488
1488
  Team purpose: ${$.teamDescription||"Coordinate parallel agent work"}.
@@ -1494,7 +1494,7 @@ Work independently on your assignment and return a concise final result for the
1494
1494
 
1495
1495
  Assignment:
1496
1496
  ${$.memberPrompt}
1497
- `.trim()}async function A8($,Z){let J=c.getInstance(),W=!1,X=Z.members.map((V)=>{if(!V.agentId)return V;let B=J.getAgent(V.agentId);if(!B)return{...V,status:"unknown"};let K=eZ(B);if(K!==V.status||B.completedAt!==V.completedAt)return W=!0,{...V,status:K,completedAt:B.completedAt};return V}),Y={...Z,members:X};if(W)await $.saveTeam(Y);return Y}function eZ($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function A0($){let Z=c.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":E9($),team_file_path:$.teamFilePath,lead_agent_id:$.leadAgentId,lead_session_id:$.leadSessionId,created_at:new Date($.createdAt).toISOString(),updated_at:new Date($.updatedAt).toISOString(),deleted_at:$.deletedAt?new Date($.deletedAt).toISOString():void 0,members:$.members.map((J)=>{let W=J.agentId?Z.getAgent(J.agentId):void 0;return{id:J.id,name:J.name,subagent_type:J.subagentType,description:J.description,agent_id:J.agentId,status:J.status,task_output_id:J.agentId,result:W?.result,stats:W?.stats}})}}function E9($){let Z=$.members.reduce((J,W)=>{return J[W.status]=(J[W.status]||0)+1,J},{});return Object.entries(Z).map(([J,W])=>`${W} ${J}`).join(", ")}function $3($){let Z=new Set;for(let J of $){let W=H$.sanitizeName(J);if(Z.has(W))return J;Z.add(W)}return}function g1($,Z){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:Z}}}function k8($,Z){let J=$;return{success:!1,llmContent:`Team operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function Z3(){return`
1497
+ `.trim()}async function A8($,Z){let J=c.getInstance(),W=!1,X=Z.members.map((V)=>{if(!V.agentId)return V;let B=J.getAgent(V.agentId);if(!B)return{...V,status:"unknown"};let K=Z3(B);if(K!==V.status||B.completedAt!==V.completedAt)return W=!0,{...V,status:K,completedAt:B.completedAt};return V}),Y={...Z,members:X};if(W)await $.saveTeam(Y);return Y}function Z3($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function R0($){let Z=c.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":E9($),team_file_path:$.teamFilePath,lead_agent_id:$.leadAgentId,lead_session_id:$.leadSessionId,created_at:new Date($.createdAt).toISOString(),updated_at:new Date($.updatedAt).toISOString(),deleted_at:$.deletedAt?new Date($.deletedAt).toISOString():void 0,members:$.members.map((J)=>{let W=J.agentId?Z.getAgent(J.agentId):void 0;return{id:J.id,name:J.name,subagent_type:J.subagentType,description:J.description,agent_id:J.agentId,status:J.status,task_output_id:J.agentId,result:W?.result,stats:W?.stats}})}}function E9($){let Z=$.members.reduce((J,W)=>{return J[W.status]=(J[W.status]||0)+1,J},{});return Object.entries(Z).map(([J,W])=>`${W} ${J}`).join(", ")}function J3($){let Z=new Set;for(let J of $){let W=H$.sanitizeName(J);if(Z.has(W))return J;Z.add(W)}return}function g1($,Z){return{success:!1,llmContent:$,error:{type:"validation_error",message:$},metadata:{summary:Z}}}function k8($,Z){let J=$;return{success:!1,llmContent:`Team operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function W3(){return`
1498
1498
  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.
1499
1499
 
1500
1500
  When to use:
@@ -1509,7 +1509,7 @@ Workflow:
1509
1509
  4. Inspect progress with TeamStatus.
1510
1510
  5. Retrieve detailed teammate output with TaskOutput using the member task_output_id.
1511
1511
  6. Stop the team with TeamDelete when the work is complete or cancelled.
1512
- `.trim()}import{z as B$}from"zod";import{isPlainObject as A9}from"lodash-es";function R9($){if(!A9($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function J3($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(A9($)){let Z=$;if(typeof Z.message==="string")return Z.message}return String($)}var b8=D({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",isConcurrencySafe:!0,schema:B$.object({url:B$.string().url().describe("URL to request"),method:B$.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:B$.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:B$.object({with_generated_alt:B$.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:B$.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:B$.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:B$.record(B$.string()).optional().describe("Request headers (optional)"),body:B$.string().optional().describe("Request body (optional)"),timeout:y.timeout(1000,120000,30000),follow_redirects:B$.boolean().default(!0).describe("Follow redirects"),max_redirects:B$.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:B$.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
1512
+ `.trim()}import{z as B$}from"zod";import{isPlainObject as A9}from"lodash-es";function R9($){if(!A9($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function X3($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(A9($)){let Z=$;if(typeof Z.message==="string")return Z.message}return String($)}var b8=D({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",isConcurrencySafe:!0,schema:B$.object({url:B$.string().url().describe("URL to request"),method:B$.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:B$.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:B$.object({with_generated_alt:B$.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:B$.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:B$.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:B$.record(B$.string()).optional().describe("Request headers (optional)"),body:B$.string().optional().describe("Request body (optional)"),timeout:y.timeout(1000,120000,30000),follow_redirects:B$.boolean().default(!0).describe("Follow redirects"),max_redirects:B$.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:B$.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
1513
1513
  - Fetches content from a specified URL and processes it using an AI model
1514
1514
  - Takes a URL and a prompt as input
1515
1515
  - Fetches the URL content, converts HTML to markdown
@@ -1526,19 +1526,19 @@ Usage notes:
1526
1526
  - Results may be summarized if the content is very large
1527
1527
  - Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
1528
1528
  - 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.
1529
- `},async execute($,Z){let{url:J,method:W="GET",extract_content:X=!1,jina_options:Y,headers:V={},body:B,timeout:K=30000,follow_redirects:Q=!0,max_redirects:U=5,return_headers:q=!1}=$,{updateOutput:H}=Z,G=Z.signal??new AbortController().signal;try{if(X)try{let E=Date.now(),j=await V3({url:J,jinaOptions:Y,timeout:K,signal:G,updateOutput:H}),b=Date.now()-E;if(j.response_time=b,!q)delete j.headers;let a={url:J,method:"GET",status:j.status,response_time:b,content_length:Buffer.byteLength(j.body||"","utf8"),redirected:j.redirected||!1,redirect_count:j.redirect_count??0,final_url:j.url,content_type:j.content_type,redirect_chain:j.redirect_chain},v=_9(J);return{success:!0,llmContent:j,metadata:{...a,summary:`GET ${v} - ${j.status}`}}}catch{H?.("[WARN] Jina Reader 失败,使用标准方式获取")}H?.(`发送 ${W} 请求到: ${J}`);let O=Date.now(),F=await W3({url:J,method:W,headers:V,body:B,timeout:K,follow_redirects:Q,max_redirects:U,signal:G}),z=Date.now()-O;if(F.response_time=z,!q)delete F.headers;let w={url:J,method:W,status:F.status,response_time:z,content_length:Buffer.byteLength(F.body||"","utf8"),redirected:F.redirected||!1,redirect_count:F.redirect_count??0,final_url:F.url,content_type:F.content_type,redirect_chain:F.redirect_chain},L=_9(J);if(F.status>=400)return{success:!1,llmContent:`HTTP error ${F.status}: ${F.status_text}`,error:{type:"execution_error",message:`HTTP error ${F.status}: ${F.status_text}`,details:{...w,response_body:F.body}},metadata:{...w,summary:`请求失败: HTTP ${F.status} ${F.status_text}`}};return{success:!0,llmContent:F,metadata:{...w,summary:`${W} ${L} - ${F.status}`}}}catch(O){if(R9(O)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let F=J3(O);return{success:!1,llmContent:`Network request failed: ${F}`,error:{type:"execution_error",message:F,details:O},metadata:{summary:`请求失败: ${F}`}}}},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 W3($){let{url:Z,method:J,headers:W,body:X,timeout:Y,follow_redirects:V,max_redirects:B,signal:K}=$,Q={"User-Agent":"Blade-AI/1.0",...W},U=Z,q=J,H=X,G=0,O=[];while(!0){let F={...Q};if(H&&q!=="GET"&&q!=="HEAD"&&!Y3(F,"content-type"))F["Content-Type"]="application/json";let z=await k9(U,{method:q,headers:F,body:H&&q!=="GET"&&q!=="HEAD"?H:void 0,redirect:"manual"},Y,K),w=z.headers.get("location"),L=z.status>=300&&z.status<400,E=V&&L&&w&&G<B;if(L&&V&&!w)throw Error(`收到状态码 ${z.status} 但响应缺少 Location 头`);if(L&&V&&G>=B)throw Error(`超过最大重定向次数 (${B})`);if(E&&w){G++;let a=X3(w,U);if(O.push(`${z.status} -> ${a}`),z.status===303||(z.status===301||z.status===302)&&q!=="GET"&&q!=="HEAD")q="GET",H=void 0;U=a;continue}let j=await z.text(),b=b9(z.headers);return{status:z.status,status_text:z.statusText,headers:b,body:j,url:z.url||U,redirected:G>0,redirect_count:G,redirect_chain:O,content_type:b["content-type"],response_time:0}}}function _9($){try{return new URL($).hostname}catch{return $}}async function k9($,Z,J,W){let X=new AbortController,Y=setTimeout(()=>X.abort(),J),V=()=>X.abort();W?.addEventListener("abort",V);try{return await fetch($,{...Z,signal:X.signal})}catch(B){if(R9(B)==="AbortError"){if(B instanceof Error)throw B.message="请求被中止或超时",B;let K=Error("请求被中止或超时");throw K.name="AbortError",K}throw B}finally{clearTimeout(Y),W?.removeEventListener("abort",V)}}function X3($,Z){try{return new URL($,Z).toString()}catch{return $}}function b9($){let Z={};return $.forEach((J,W)=>{Z[W.toLowerCase()]=J}),Z}function Y3($,Z){let J=Z.toLowerCase();return Object.keys($).some((W)=>W.toLowerCase()===J)}async function V3($){let{url:Z,jinaOptions:J,timeout:W,signal:X,updateOutput:Y}=$,V=`https://r.jina.ai/${encodeURIComponent(Z)}`;Y?.(`使用 Jina Reader 提取内容: ${Z}`);let B={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(J?.with_generated_alt)B["X-With-Generated-Alt"]="true";if(J?.with_links_summary)B["X-With-Links-Summary"]="true";if(J?.wait_for_selector)B["X-Wait-For-Selector"]=J.wait_for_selector;try{let K=await k9(V,{method:"GET",headers:B},W,X);if(!K.ok)throw Error(`Jina Reader error: ${K.status} ${K.statusText}`);let Q=await K.text(),U=B3(Q);return Y?.(`[OK] Jina Reader 成功提取内容 (${U.content.length} 字符)`),{status:K.status,status_text:K.statusText,headers:b9(K.headers),body:K3(U),url:U.sourceUrl||Z,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(K){throw Y?.("[WARN] Jina Reader 失败,回退到直接获取"),K}}function B3($){let Z=$.split(`
1529
+ `},async execute($,Z){let{url:J,method:W="GET",extract_content:X=!1,jina_options:Y,headers:V={},body:B,timeout:K=30000,follow_redirects:Q=!0,max_redirects:U=5,return_headers:q=!1}=$,{updateOutput:H}=Z,G=Z.signal??new AbortController().signal;try{if(X)try{let E=Date.now(),j=await K3({url:J,jinaOptions:Y,timeout:K,signal:G,updateOutput:H}),b=Date.now()-E;if(j.response_time=b,!q)delete j.headers;let a={url:J,method:"GET",status:j.status,response_time:b,content_length:Buffer.byteLength(j.body||"","utf8"),redirected:j.redirected||!1,redirect_count:j.redirect_count??0,final_url:j.url,content_type:j.content_type,redirect_chain:j.redirect_chain},v=_9(J);return{success:!0,llmContent:j,metadata:{...a,summary:`GET ${v} - ${j.status}`}}}catch{H?.("[WARN] Jina Reader 失败,使用标准方式获取")}H?.(`发送 ${W} 请求到: ${J}`);let O=Date.now(),F=await Y3({url:J,method:W,headers:V,body:B,timeout:K,follow_redirects:Q,max_redirects:U,signal:G}),z=Date.now()-O;if(F.response_time=z,!q)delete F.headers;let w={url:J,method:W,status:F.status,response_time:z,content_length:Buffer.byteLength(F.body||"","utf8"),redirected:F.redirected||!1,redirect_count:F.redirect_count??0,final_url:F.url,content_type:F.content_type,redirect_chain:F.redirect_chain},L=_9(J);if(F.status>=400)return{success:!1,llmContent:`HTTP error ${F.status}: ${F.status_text}`,error:{type:"execution_error",message:`HTTP error ${F.status}: ${F.status_text}`,details:{...w,response_body:F.body}},metadata:{...w,summary:`请求失败: HTTP ${F.status} ${F.status_text}`}};return{success:!0,llmContent:F,metadata:{...w,summary:`${W} ${L} - ${F.status}`}}}catch(O){if(R9(O)==="AbortError")return{success:!1,llmContent:"Request aborted",error:{type:"execution_error",message:"操作被中止"},metadata:{summary:"请求失败: 操作被中止"}};let F=X3(O);return{success:!1,llmContent:`Network request failed: ${F}`,error:{type:"execution_error",message:F,details:O},metadata:{summary:`请求失败: ${F}`}}}},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 Y3($){let{url:Z,method:J,headers:W,body:X,timeout:Y,follow_redirects:V,max_redirects:B,signal:K}=$,Q={"User-Agent":"Blade-AI/1.0",...W},U=Z,q=J,H=X,G=0,O=[];while(!0){let F={...Q};if(H&&q!=="GET"&&q!=="HEAD"&&!B3(F,"content-type"))F["Content-Type"]="application/json";let z=await k9(U,{method:q,headers:F,body:H&&q!=="GET"&&q!=="HEAD"?H:void 0,redirect:"manual"},Y,K),w=z.headers.get("location"),L=z.status>=300&&z.status<400,E=V&&L&&w&&G<B;if(L&&V&&!w)throw Error(`收到状态码 ${z.status} 但响应缺少 Location 头`);if(L&&V&&G>=B)throw Error(`超过最大重定向次数 (${B})`);if(E&&w){G++;let a=V3(w,U);if(O.push(`${z.status} -> ${a}`),z.status===303||(z.status===301||z.status===302)&&q!=="GET"&&q!=="HEAD")q="GET",H=void 0;U=a;continue}let j=await z.text(),b=b9(z.headers);return{status:z.status,status_text:z.statusText,headers:b,body:j,url:z.url||U,redirected:G>0,redirect_count:G,redirect_chain:O,content_type:b["content-type"],response_time:0}}}function _9($){try{return new URL($).hostname}catch{return $}}async function k9($,Z,J,W){let X=new AbortController,Y=setTimeout(()=>X.abort(),J),V=()=>X.abort();W?.addEventListener("abort",V);try{return await fetch($,{...Z,signal:X.signal})}catch(B){if(R9(B)==="AbortError"){if(B instanceof Error)throw B.message="请求被中止或超时",B;let K=Error("请求被中止或超时");throw K.name="AbortError",K}throw B}finally{clearTimeout(Y),W?.removeEventListener("abort",V)}}function V3($,Z){try{return new URL($,Z).toString()}catch{return $}}function b9($){let Z={};return $.forEach((J,W)=>{Z[W.toLowerCase()]=J}),Z}function B3($,Z){let J=Z.toLowerCase();return Object.keys($).some((W)=>W.toLowerCase()===J)}async function K3($){let{url:Z,jinaOptions:J,timeout:W,signal:X,updateOutput:Y}=$,V=`https://r.jina.ai/${encodeURIComponent(Z)}`;Y?.(`使用 Jina Reader 提取内容: ${Z}`);let B={"User-Agent":"Blade-AI/1.0",Accept:"text/markdown"};if(J?.with_generated_alt)B["X-With-Generated-Alt"]="true";if(J?.with_links_summary)B["X-With-Links-Summary"]="true";if(J?.wait_for_selector)B["X-Wait-For-Selector"]=J.wait_for_selector;try{let K=await k9(V,{method:"GET",headers:B},W,X);if(!K.ok)throw Error(`Jina Reader error: ${K.status} ${K.statusText}`);let Q=await K.text(),U=Q3(Q);return Y?.(`[OK] Jina Reader 成功提取内容 (${U.content.length} 字符)`),{status:K.status,status_text:K.statusText,headers:b9(K.headers),body:U3(U),url:U.sourceUrl||Z,redirected:!1,redirect_count:0,content_type:"text/markdown",response_time:0}}catch(K){throw Y?.("[WARN] Jina Reader 失败,回退到直接获取"),K}}function Q3($){let Z=$.split(`
1530
1530
  `),J="",W="",X=0;for(let V=0;V<Z.length;V++){let B=Z[V];if(B.startsWith("Title: "))J=B.substring(7).trim();else if(B.startsWith("URL Source: "))W=B.substring(12).trim();else if(B.startsWith("Markdown Content:")){X=V+1;break}}let Y=Z.slice(X).join(`
1531
- `).trim();return{title:J||"Untitled",sourceUrl:W||"",content:Y||$}}function K3($){let Z="";if($.title)Z+=`# ${$.title}
1531
+ `).trim();return{title:J||"Untitled",sourceUrl:W||"",content:Y||$}}function U3($){let Z="";if($.title)Z+=`# ${$.title}
1532
1532
 
1533
1533
  `;if($.sourceUrl)Z+=`**Source**: ${$.sourceUrl}
1534
1534
 
1535
1535
  `;return Z+=`---
1536
1536
 
1537
- `,Z+=$.content,Z}import{ProxyAgent as N3,fetch as D3}from"undici";import{z as R0}from"zod";import{LRUCache as T9}from"lru-cache";import Q3 from"node:crypto";class M9{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new T9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,Z){let J=Z.toLowerCase().trim(),W=Q3.createHash("md5").update(J).digest("hex").substring(0,8);return`${$}:${W}`}get($,Z){if(!this.config.enabled)return null;let J=this.generateKey($,Z),W=this.cache.get(J);if(!W)return this.misses++,null;if(Date.now()>W.expiresAt)return this.cache.delete(J),this.misses++,null;return this.hits++,W.results}set($,Z,J){if(!this.config.enabled||J.length===0)return;let W=this.generateKey($,Z),X=Date.now(),Y={query:Z,provider:$,results:J,timestamp:X,expiresAt:X+this.config.ttl};this.cache.set(W,Y)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,Z=$>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(Z.toFixed(2))}}cleanup(){let $=Date.now(),Z=0;for(let[J,W]of this.cache.entries())if($>W.expiresAt)this.cache.delete(J),Z++;return Z}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 Z=Array.from(this.cache.entries());this.cache=new T9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[J,W]of Z.slice(-this.config.maxSize))this.cache.set(J,W)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var U3=new M9;function v9(){return U3}function q3($){return $.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function C9($){let Z=q3($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[J,...W]=Z.split(" - "),X=J.trim(),Y=W.join(" - ").trim()||Z;return{title:X,snippet:Y}}function a0($){try{let Z=new URL($),J=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${J}`}catch{return $}}function n0($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function H3($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:J}=C9($.Text);return{title:Z,snippet:J,url:$.FirstURL,display_url:a0($.FirstURL),source:n0($.FirstURL)}}function I9($){let Z=[];for(let J of $){if(J.Topics&&J.Topics.length>0){Z.push(...I9(J.Topics));continue}if(J.FirstURL&&J.Text){let{title:W,snippet:X}=C9(J.Text);Z.push({title:W,snippet:X,url:J.FirstURL,display_url:a0(J.FirstURL),source:n0(J.FirstURL)})}}return Z}function G3($){let Z=$,J=(Z.Results??[]).map((X)=>H3(X)).filter((X)=>X!==null),W=I9(Z.RelatedTopics??[]);return[...J,...W]}var F3={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:G3,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function O3($){let Z=$,J=[];for(let W of Z.results??[]){if(!W.url||!W.title)continue;J.push({title:W.title,snippet:W.content||W.title,url:W.url,display_url:a0(W.url),source:n0(W.url)})}return J}var S9=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function z3($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(J)=>{let W=new URL(`${$}/search`);return W.searchParams.set("q",J),W.searchParams.set("format","json"),W.searchParams.set("categories","general"),W.toString()},parseResponse:O3,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var r$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function w3($){let Z=[],J=$.split(`
1538
- `),W={};for(let X=0;X<J.length;X++){let Y=J[X].trim();if(Y.startsWith("Title: ")){if(W.title&&W.url)Z.push({title:W.title,url:W.url,snippet:W.snippet||W.title,display_url:a0(W.url),source:n0(W.url)});W={title:Y.substring(7).trim(),snippet:""}}else if(Y.startsWith("URL: "))W.url=Y.substring(5).trim();else if(Y.startsWith("Text: ")){let B=Y.substring(6).trim().replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();W.snippet=B.substring(0,300)}}if(W.title&&W.url)Z.push({title:W.title,url:W.url,snippet:W.snippet||W.title,display_url:a0(W.url),source:n0(W.url)});return Z}function j3(){return{name:"Exa",endpoint:`${r$.BASE_URL}${r$.ENDPOINT}`,searchFn:async($)=>{let Z={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:r$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},J=new AbortController,W=setTimeout(()=>J.abort(),r$.TIMEOUT);try{let X=await fetch(`${r$.BASE_URL}${r$.ENDPOINT}`,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(Z),signal:J.signal});if(clearTimeout(W),!X.ok)throw Error(`MCP error (${X.status})`);let V=(await X.text()).split(`
1539
- `);for(let B of V)if(B.startsWith("data: ")){let K=JSON.parse(B.substring(6));if(K.result&&K.result.content&&K.result.content.length>0)return w3(K.result.content[0].text)}throw Error("No search results found")}catch(X){if(clearTimeout(W),X.name==="AbortError")throw Error("MCP request timed out");throw X}},buildUrl:()=>`${r$.BASE_URL}${r$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function P9(){let $=[];return $.push(j3()),$.push(F3),$.push(...S9.map(z3)),$}function y9(){return 2+S9.length}var L3=15000,E3=8,r0={maxRetries:3,baseDelay:1000,maxDelay:8000};function _3(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new N3($)}catch(Z){console.warn(`Invalid proxy URL: ${$}`)}return}async function A3($,Z,J,W,X){let Y=new AbortController,V=setTimeout(()=>Y.abort(),J),B=()=>Y.abort();W?.addEventListener("abort",B);try{return await D3($,{...Z,signal:Y.signal,dispatcher:X})}catch(K){if(K.name==="AbortError")throw Error("搜索请求超时或被中止");throw K}finally{clearTimeout(V),W?.removeEventListener("abort",B)}}async function R3($,Z,J,W,X,Y){let V=null;for(let B=0;B<r0.maxRetries;B++)try{return await A3($,Z,J,W,X)}catch(K){if(V=K,W?.aborted)throw K;if(B<r0.maxRetries-1){let Q=Math.min(r0.baseDelay*Math.pow(2,B),r0.maxDelay);Y?.(`请求失败,${Q/1000}s 后重试 (${B+1}/${r0.maxRetries})...`),await new Promise((U)=>setTimeout(U,Q))}}throw V}async function k3($,Z,J,W,X,Y){let V=v9(),B=V.get($.name,Z);if(B)return Y?.(`使用缓存结果 (${$.name})`),{results:B,providerName:`${$.name} (cached)`};if($.searchFn)try{Y?.(`搜索中 (${$.name})...`);let z=await $.searchFn(Z);return V.set($.name,Z,z),{results:z,providerName:$.name}}catch(z){throw Error(`SDK search failed: ${z.message}`)}Y?.(`搜索中 (${$.name})...`);let K=$.buildUrl(Z),Q=$.method||"GET",q={headers:$.getHeaders(),method:Q};if(Q==="POST"&&$.buildBody)q.body=JSON.stringify($.buildBody(Z));let H=await R3(K,q,J,W,X,Y);if(!H.ok)throw Error(`HTTP ${H.status}`);let G=await H.text(),O;try{O=JSON.parse(G)}catch{throw Error("Failed to parse search result JSON")}let F=$.parseResponse(O);return V.set($.name,Z,F),{results:F,providerName:$.name}}async function b3($,Z,J,W){let X=P9(),Y=_3(),V=[];for(let B=0;B<X.length;B++){let K=X[B];if(J?.aborted)throw Error("搜索被用户中止");try{return W?.(`使用 ${K.name} 搜索...`),await k3(K,$,Z,J,Y,W)}catch(Q){let U=Q,q=`${K.name}: ${U.message}`;if(V.push(q),W?.(`[WARN] ${q}`),B===X.length-1)throw Error(`所有搜索提供商都失败了:
1537
+ `,Z+=$.content,Z}import{ProxyAgent as L3,fetch as E3}from"undici";import{z as k0}from"zod";import{LRUCache as T9}from"lru-cache";import q3 from"node:crypto";class M9{cache;config;hits=0;misses=0;constructor($){this.config={maxSize:$?.maxSize??100,ttl:$?.ttl??3600000,enabled:$?.enabled??!0},this.cache=new T9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1})}generateKey($,Z){let J=Z.toLowerCase().trim(),W=q3.createHash("md5").update(J).digest("hex").substring(0,8);return`${$}:${W}`}get($,Z){if(!this.config.enabled)return null;let J=this.generateKey($,Z),W=this.cache.get(J);if(!W)return this.misses++,null;if(Date.now()>W.expiresAt)return this.cache.delete(J),this.misses++,null;return this.hits++,W.results}set($,Z,J){if(!this.config.enabled||J.length===0)return;let W=this.generateKey($,Z),X=Date.now(),Y={query:Z,provider:$,results:J,timestamp:X,expiresAt:X+this.config.ttl};this.cache.set(W,Y)}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){let $=this.hits+this.misses,Z=$>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(Z.toFixed(2))}}cleanup(){let $=Date.now(),Z=0;for(let[J,W]of this.cache.entries())if($>W.expiresAt)this.cache.delete(J),Z++;return Z}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 Z=Array.from(this.cache.entries());this.cache=new T9({max:this.config.maxSize,ttl:this.config.ttl,updateAgeOnGet:!0,updateAgeOnHas:!1});for(let[J,W]of Z.slice(-this.config.maxSize))this.cache.set(J,W)}if($.ttl!==void 0)this.config.ttl=$.ttl;if($.enabled!==void 0)this.config.enabled=$.enabled}}var H3=new M9;function v9(){return H3}function G3($){return $.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'")}function C9($){let Z=G3($).trim();if(!Z.includes(" - "))return{title:Z,snippet:Z};let[J,...W]=Z.split(" - "),X=J.trim(),Y=W.join(" - ").trim()||Z;return{title:X,snippet:Y}}function a0($){try{let Z=new URL($),J=Z.pathname==="/"?"":Z.pathname;return`${Z.hostname}${J}`}catch{return $}}function n0($){try{return new URL($).hostname.toLowerCase()}catch{return""}}function F3($){if(!$.FirstURL||!$.Text)return null;let{title:Z,snippet:J}=C9($.Text);return{title:Z,snippet:J,url:$.FirstURL,display_url:a0($.FirstURL),source:n0($.FirstURL)}}function I9($){let Z=[];for(let J of $){if(J.Topics&&J.Topics.length>0){Z.push(...I9(J.Topics));continue}if(J.FirstURL&&J.Text){let{title:W,snippet:X}=C9(J.Text);Z.push({title:W,snippet:X,url:J.FirstURL,display_url:a0(J.FirstURL),source:n0(J.FirstURL)})}}return Z}function O3($){let Z=$,J=(Z.Results??[]).map((X)=>F3(X)).filter((X)=>X!==null),W=I9(Z.RelatedTopics??[]);return[...J,...W]}var z3={name:"DuckDuckGo",endpoint:"https://duckduckgo.com/",buildUrl:($)=>{let Z=new URL("https://duckduckgo.com/");return Z.searchParams.set("q",$),Z.searchParams.set("format","json"),Z.searchParams.set("no_html","1"),Z.searchParams.set("skip_disambig","1"),Z.searchParams.set("t","blade-code"),Z.searchParams.set("kl","us-en"),Z.toString()},parseResponse:O3,getHeaders:()=>({Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"})};function w3($){let Z=$,J=[];for(let W of Z.results??[]){if(!W.url||!W.title)continue;J.push({title:W.title,snippet:W.content||W.title,url:W.url,display_url:a0(W.url),source:n0(W.url)})}return J}var S9=["https://searx.be","https://search.ononoki.org","https://searx.tiekoetter.com","https://searx.work"];function j3($){return{name:`SearXNG(${(()=>{try{return new URL($).hostname}catch{return $}})()})`,endpoint:$,buildUrl:(J)=>{let W=new URL(`${$}/search`);return W.searchParams.set("q",J),W.searchParams.set("format","json"),W.searchParams.set("categories","general"),W.toString()},parseResponse:w3,getHeaders:()=>({Accept:"application/json","User-Agent":"Blade-AI-WebSearch/1.0"})}}var s$={BASE_URL:"https://mcp.exa.ai",ENDPOINT:"/mcp",DEFAULT_NUM_RESULTS:10,TIMEOUT:25000};function N3($){let Z=[],J=$.split(`
1538
+ `),W={};for(let X=0;X<J.length;X++){let Y=J[X].trim();if(Y.startsWith("Title: ")){if(W.title&&W.url)Z.push({title:W.title,url:W.url,snippet:W.snippet||W.title,display_url:a0(W.url),source:n0(W.url)});W={title:Y.substring(7).trim(),snippet:""}}else if(Y.startsWith("URL: "))W.url=Y.substring(5).trim();else if(Y.startsWith("Text: ")){let B=Y.substring(6).trim().replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();W.snippet=B.substring(0,300)}}if(W.title&&W.url)Z.push({title:W.title,url:W.url,snippet:W.snippet||W.title,display_url:a0(W.url),source:n0(W.url)});return Z}function D3(){return{name:"Exa",endpoint:`${s$.BASE_URL}${s$.ENDPOINT}`,searchFn:async($)=>{let Z={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:$,type:"auto",numResults:s$.DEFAULT_NUM_RESULTS,contextMaxCharacters:1e4}}},J=new AbortController,W=setTimeout(()=>J.abort(),s$.TIMEOUT);try{let X=await fetch(`${s$.BASE_URL}${s$.ENDPOINT}`,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json"},body:JSON.stringify(Z),signal:J.signal});if(clearTimeout(W),!X.ok)throw Error(`MCP error (${X.status})`);let V=(await X.text()).split(`
1539
+ `);for(let B of V)if(B.startsWith("data: ")){let K=JSON.parse(B.substring(6));if(K.result&&K.result.content&&K.result.content.length>0)return N3(K.result.content[0].text)}throw Error("No search results found")}catch(X){if(clearTimeout(W),X.name==="AbortError")throw Error("MCP request timed out");throw X}},buildUrl:()=>`${s$.BASE_URL}${s$.ENDPOINT}`,parseResponse:()=>[],getHeaders:()=>({})}}function P9(){let $=[];return $.push(D3()),$.push(z3),$.push(...S9.map(j3)),$}function y9(){return 2+S9.length}var _3=15000,A3=8,r0={maxRetries:3,baseDelay:1000,maxDelay:8000};function R3(){let $=process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy;if($)try{return new L3($)}catch(Z){console.warn(`Invalid proxy URL: ${$}`)}return}async function k3($,Z,J,W,X){let Y=new AbortController,V=setTimeout(()=>Y.abort(),J),B=()=>Y.abort();W?.addEventListener("abort",B);try{return await E3($,{...Z,signal:Y.signal,dispatcher:X})}catch(K){if(K.name==="AbortError")throw Error("搜索请求超时或被中止");throw K}finally{clearTimeout(V),W?.removeEventListener("abort",B)}}async function b3($,Z,J,W,X,Y){let V=null;for(let B=0;B<r0.maxRetries;B++)try{return await k3($,Z,J,W,X)}catch(K){if(V=K,W?.aborted)throw K;if(B<r0.maxRetries-1){let Q=Math.min(r0.baseDelay*Math.pow(2,B),r0.maxDelay);Y?.(`请求失败,${Q/1000}s 后重试 (${B+1}/${r0.maxRetries})...`),await new Promise((U)=>setTimeout(U,Q))}}throw V}async function T3($,Z,J,W,X,Y){let V=v9(),B=V.get($.name,Z);if(B)return Y?.(`使用缓存结果 (${$.name})`),{results:B,providerName:`${$.name} (cached)`};if($.searchFn)try{Y?.(`搜索中 (${$.name})...`);let z=await $.searchFn(Z);return V.set($.name,Z,z),{results:z,providerName:$.name}}catch(z){throw Error(`SDK search failed: ${z.message}`)}Y?.(`搜索中 (${$.name})...`);let K=$.buildUrl(Z),Q=$.method||"GET",q={headers:$.getHeaders(),method:Q};if(Q==="POST"&&$.buildBody)q.body=JSON.stringify($.buildBody(Z));let H=await b3(K,q,J,W,X,Y);if(!H.ok)throw Error(`HTTP ${H.status}`);let G=await H.text(),O;try{O=JSON.parse(G)}catch{throw Error("Failed to parse search result JSON")}let F=$.parseResponse(O);return V.set($.name,Z,F),{results:F,providerName:$.name}}async function M3($,Z,J,W){let X=P9(),Y=R3(),V=[];for(let B=0;B<X.length;B++){let K=X[B];if(J?.aborted)throw Error("搜索被用户中止");try{return W?.(`使用 ${K.name} 搜索...`),await T3(K,$,Z,J,Y,W)}catch(Q){let U=Q,q=`${K.name}: ${U.message}`;if(V.push(q),W?.(`[WARN] ${q}`),B===X.length-1)throw Error(`所有搜索提供商都失败了:
1540
1540
  ${V.join(`
1541
- `)}`)}}throw Error("No search providers available")}function T3($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function M3($){return $.trim().toLowerCase()}function x9($){if(!$||$.length===0)return[];return $.map(M3).filter(Boolean)}function f9($,Z){return $===Z||$.endsWith(`.${Z}`)}function v3($,Z,J){return $.filter((W)=>{let X=T3(W.url);if(!X)return!1;if(J.length>0&&J.some((Y)=>f9(X,Y)))return!1;if(Z.length>0&&!Z.some((Y)=>f9(X,Y)))return!1;return!0})}function C3($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var T8=D({name:"WebSearch",displayName:"Web Search",kind:"readonly",isConcurrencySafe:!0,schema:R0.object({query:R0.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:R0.array(R0.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:R0.array(R0.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
1541
+ `)}`)}}throw Error("No search providers available")}function v3($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function C3($){return $.trim().toLowerCase()}function x9($){if(!$||$.length===0)return[];return $.map(C3).filter(Boolean)}function f9($,Z){return $===Z||$.endsWith(`.${Z}`)}function I3($,Z,J){return $.filter((W)=>{let X=v3(W.url);if(!X)return!1;if(J.length>0&&J.some((Y)=>f9(X,Y)))return!1;if(Z.length>0&&!Z.some((Y)=>f9(X,Y)))return!1;return!0})}function S3($){let Z=$.trim().toLowerCase();return Z.length>80?Z.slice(0,80):Z}var T8=D({name:"WebSearch",displayName:"Web Search",kind:"readonly",isConcurrencySafe:!0,schema:k0.object({query:k0.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:k0.array(k0.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:k0.array(k0.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
1542
1542
  - Search the web and use the results to inform responses
1543
1543
  - Provides up-to-date information for current events and recent data
1544
1544
  - Returns search result information formatted as search result blocks, including links as markdown hyperlinks
@@ -1566,21 +1566,21 @@ Usage notes:
1566
1566
  IMPORTANT - Use the correct year in search queries:
1567
1567
  - You MUST use the current year when searching for recent information, documentation, or current events.
1568
1568
  - Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
1569
- `},async execute($,Z){let{query:J}=$,W=x9($.allowed_domains),X=x9($.blocked_domains),{updateOutput:Y}=Z,V=Z.signal??new AbortController().signal;Y?.(`Searching: "${J}" (${y9()} providers available)`);try{let{results:B,providerName:K}=await b3(J,L3,V,Y),Q=v3(B,W,X),U=Q.slice(0,E3),q={query:J,results:U,provider:K,total_results:Q.length,fetched_at:new Date().toISOString()},H={query:J,provider:K,fetched_at:q.fetched_at,total_results:Q.length,returned_results:U.length,allowed_domains:W,blocked_domains:X};if(U.length===0)return{success:!0,llmContent:q,metadata:{...H,summary:`搜索 "${J}" 找到 0 条结果`}};return{success:!0,llmContent:q,metadata:{...H,summary:`搜索 "${J}" 找到 ${U.length} 条结果`}}}catch(B){let K=B;return{success:!1,llmContent:`WebSearch call failed: ${K.message}`,error:{type:"execution_error",message:K.message,details:{query:J,allowedDomains:W,blockedDomains:X}},metadata:{summary:`搜索失败: ${K.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${C3($.query)}`,abstractPermissionRule:()=>"search:*"});async function I3(){try{return await F$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function P1($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||p9.join(h9.homedir(),".blade"),W=[G5,H5,O5,N5,A5,T5,v5,C5,b8,T8,D8,L8,..._8({sessionId:Z,configDir:J}),...R8({sessionId:Z,configDir:J}),D5,E5,...o4,y5,f5,m5,l5,w5,j5,z5],X=await I3();return[...W,...X]}var F0=M("Agent");class y1{config;options;approvalStore=new h0;baseRegistry=new c$;attachmentCollector;chatService;executionEngine;currentModelId;currentModelMaxContextTokens;initialized=!1;constructor($,Z){this.config=$;this.options=Z;this.attachmentCollector=new S0({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){if(await C1(),l$().length===0)throw Error(`没有可用的模型配置
1569
+ `},async execute($,Z){let{query:J}=$,W=x9($.allowed_domains),X=x9($.blocked_domains),{updateOutput:Y}=Z,V=Z.signal??new AbortController().signal;Y?.(`Searching: "${J}" (${y9()} providers available)`);try{let{results:B,providerName:K}=await M3(J,_3,V,Y),Q=I3(B,W,X),U=Q.slice(0,A3),q={query:J,results:U,provider:K,total_results:Q.length,fetched_at:new Date().toISOString()},H={query:J,provider:K,fetched_at:q.fetched_at,total_results:Q.length,returned_results:U.length,allowed_domains:W,blocked_domains:X};if(U.length===0)return{success:!0,llmContent:q,metadata:{...H,summary:`搜索 "${J}" 找到 0 条结果`}};return{success:!0,llmContent:q,metadata:{...H,summary:`搜索 "${J}" 找到 ${U.length} 条结果`}}}catch(B){let K=B;return{success:!1,llmContent:`WebSearch call failed: ${K.message}`,error:{type:"execution_error",message:K.message,details:{query:J,allowedDomains:W,blockedDomains:X}},metadata:{summary:`搜索失败: ${K.message}`}}}},version:"2.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${S3($.query)}`,abstractPermissionRule:()=>"search:*"});async function P3(){try{return await O$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function P1($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||p9.join(h9.homedir(),".blade"),W=[G5,H5,O5,N5,A5,T5,v5,C5,b8,T8,D8,L8,..._8({sessionId:Z,configDir:J}),...R8({sessionId:Z,configDir:J}),D5,E5,...o4,y5,f5,m5,l5,w5,j5,z5],X=await P3();return[...W,...X]}var O0=M("Agent");class y1{config;options;approvalStore=new p0;baseRegistry=new l$;attachmentCollector;chatService;executionEngine;currentModelId;currentModelMaxContextTokens;initialized=!1;constructor($,Z){this.config=$;this.options=Z;this.attachmentCollector=new P0({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){if(await C1(),i$().length===0)throw Error(`没有可用的模型配置
1570
1570
 
1571
1571
  `+`请先使用以下命令添加模型:
1572
1572
  `+` /model add
1573
1573
 
1574
1574
  `+`或运行初始化向导:
1575
- `+" /init");let J=t();if(!J)throw Error("配置未初始化,请确保应用已正确启动");v1.getInstance().validateConfig(J);let W=new y1(J,$);return await W.initialize(),W}get sessionId(){return this.options.sessionId}getConfig(){return this.config}getChatService(){return this.chatService}getExecutionEngine(){return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getCurrentModelMaxContextTokens(){return this.currentModelMaxContextTokens}async initialize(){if(this.initialized)return;await this.validateSystemPromptConfig(),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills(),await this.applyModelConfig(this.resolveModelConfig(this.options.modelId),"使用模型:"),this.initialized=!0,F0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId&&$.modelId!=="inherit"?$.modelId:j$()?.id;if(Z&&Z!==this.currentModelId)await this.applyModelConfig(this.resolveModelConfig(Z),"切换模型")}createExecutionPipeline($={}){let Z=new c$,J=$.toolWhitelist?new Set($.toolWhitelist):null,W=$.toolBlacklist?new Set($.toolBlacklist):null;for(let V of this.baseRegistry.getBuiltinTools()){if(W?.has(V.name))continue;if(!J||J.has(V.name))Z.register(V)}for(let V of this.baseRegistry.getMcpTools()){if(W?.has(V.name))continue;if(!J||J.has(V.name))Z.registerMcpTool(V)}let X={...this.config.permissions,...$.permissions},Y=$.permissionMode??this.config.permissionMode??"default";return new u0(Z,{permissionConfig:X,permissionMode:Y,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist})}async dispose(){this.approvalStore.clear(),await this.chatService?.dispose?.(),this.currentModelId=void 0,this.initialized=!1}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?c0(Z):j$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){F0.debug(`${Z} ${$.name} (${$.model})`);let J=b1($),W=I1(),X=J&&W;this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await S1({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:X,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let Y=this.executionEngine?.getContextManager();this.executionEngine=new m0(this.chatService,Y),this.currentModelId=$.id}async validateSystemPromptConfig(){try{await $0({projectPath:N(),includeEnvironment:!1,language:this.config.language})}catch($){F0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let Z=(await P1({sessionId:this.sessionId,configDir:u9.join(d9.homedir(),".blade")})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{if(this.options.mcpConfig&&this.options.mcpConfig.length>0)await Y1(this.options.mcpConfig);let $=L$();if(Object.keys($).length===0)return;let Z=F$.getInstance();for(let[W,X]of Object.entries($))try{await Z.registerServer(W,X)}catch(Y){F0.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();for(let W of J)this.baseRegistry.registerMcpTool(W)}catch($){F0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0)return;try{P.loadFromStandardLocations()}catch($){F0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await D0({cwd:N()})}catch($){F0.warn("Failed to discover skills:",$)}}}import*as G$ from"node:fs/promises";import{homedir as h3}from"node:os";import*as p from"node:path";import n9 from"gray-matter";function m1($,Z){return`${$}:${Z}`}function g9($,Z){return`${$}__${Z}`}import*as c1 from"node:fs/promises";import*as i9 from"node:path";import{z as _}from"zod";var S3=_.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"}),P3=_.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),y3=_.object({name:_.string().min(1,"Author name is required"),email:_.string().email().optional(),url:_.string().url().optional()}),c9=_.object({name:S3,description:_.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:P3,author:y3.optional(),license:_.string().optional(),repository:_.string().url().optional(),homepage:_.string().url().optional(),keywords:_.array(_.string()).optional(),dependencies:_.record(_.string()).optional(),bladeVersion:_.string().optional()}),m9=_.object({type:_.enum(["stdio","sse","http"]),command:_.string().optional(),args:_.array(_.string()).optional(),env:_.record(_.string()).optional(),url:_.string().url().optional(),headers:_.record(_.string()).optional(),timeout:_.number().positive().optional(),oauth:_.object({enabled:_.boolean().optional(),clientId:_.string().optional(),clientSecret:_.string().optional(),authorizationUrl:_.string().url().optional(),tokenUrl:_.string().url().optional(),scopes:_.array(_.string()).optional(),redirectUri:_.string().url().optional()}).optional(),healthCheck:_.object({enabled:_.boolean().optional(),interval:_.number().positive().optional(),timeout:_.number().positive().optional(),failureThreshold:_.number().positive().optional()}).optional()}),x3=_.union([_.object({mcpServers:_.record(m9)}),_.record(m9)]);function l9($){return x3.safeParse($)}var f3=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function k0($){for(let{dir:Z,source:J}of f3){let W=i9.join($,Z,"plugin.json");try{await c1.access(W)}catch{continue}try{let X=await c1.readFile(W,"utf-8"),Y=JSON.parse(X),V=c9.safeParse(Y);if(!V.success){let B=V.error.issues.map((K)=>`${K.path.join(".")}: ${K.message}`).join("; ");throw Error(`Invalid plugin.json: ${B}`)}return S.debug(`Parsed plugin manifest from ${W}`),{manifest:V.data,source:J,manifestPath:W}}catch(X){if(X instanceof SyntaxError)throw Error(`Invalid JSON in ${W}: ${X.message}`);throw X}}return null}async function a9($){try{return await k0($)!==null}catch{return!1}}class l1{async loadPlugin($,Z,J={}){let W=await k0($);if(!W)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:X,source:Y}=W,V=X.name;S.debug(`Loading plugin "${V}" from ${$}`);let B=J.skipCommands?[]:await this.loadCommands($,V),K=J.skipAgents?[]:await this.loadAgents($,V),Q=J.skipSkills?[]:await this.loadSkills($,V),U=J.skipHooks?void 0:await this.loadHooks($),q=J.skipMcp?void 0:await this.loadMcpConfig($,V);return S.debug(`Plugin "${V}" loaded: ${B.length} commands, ${K.length} agents, ${Q.length} skills`),{manifest:X,basePath:$,source:Z,manifestSource:Y,commands:B,agents:K,skills:Q,hooks:U,mcpServers:q,status:"active",loadedAt:new Date}}async loadCommands($,Z){let J=p.join($,"commands"),W=[];if(!await this.dirExists(J))return W;let X=await this.scanMarkdownFiles(J);for(let Y of X)try{let V=await this.parseCommandFile(Y,J,Z);if(V)W.push(V)}catch(V){S.warn(`Failed to load command from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseCommandFile($,Z,J){let W=await G$.readFile($,"utf-8"),{data:X,content:Y}=n9(W),B=p.relative(Z,$).split(p.sep),K=B.pop();if(!K)return null;let Q=K.replace(/\.md$/i,""),U=Q;if(B.length>0)U=[...B,Q].join("/");let q=m1(J,U),H=this.normalizeCommandConfig(X);return{originalName:U,namespacedName:q,pluginName:J,config:H,content:Y.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($,Z){let J=p.join($,"agents"),W=[];if(!await this.dirExists(J))return W;let X=await this.scanMarkdownFiles(J);for(let Y of X)try{let V=await this.parseAgentFile(Y,J,Z);if(V)W.push(V)}catch(V){S.warn(`Failed to load agent from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseAgentFile($,Z,J){let W=await G$.readFile($,"utf-8"),{data:X,content:Y}=n9(W),V=p.relative(Z,$),B=p.basename(V,".md"),K=X.name||B,Q=m1(J,K),U={name:Q,description:this.asString(X.description)||"",tools:this.parseStringArray(X.tools),color:this.asString(X.color),model:this.asString(X.model),permissionMode:this.asString(X.permissionMode),skills:this.parseStringArray(X.skills),systemPrompt:Y.trim(),source:`plugin:${J}`};return{originalName:K,namespacedName:Q,pluginName:J,config:U,path:$}}async loadSkills($,Z){let J=p.join($,"skills"),W=[];if(!await this.dirExists(J))return W;let X=await G$.readdir(J,{withFileTypes:!0});for(let Y of X){if(!Y.isDirectory())continue;let V=p.join(J,Y.name),B=p.join(V,"SKILL.md");try{let K=await r9(B,"project");if(K.success&&K.content){let Q=K.content.metadata.name,U=m1(Z,Q);W.push({originalName:Q,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:V})}}catch(K){S.warn(`Failed to load skill from ${B}: ${K instanceof Error?K.message:String(K)}`)}}return W}async loadHooks($){let Z=p.join($,"hooks","hooks.json");try{let J=await G$.readFile(Z,"utf-8"),W=JSON.parse(J);return W.hooks||W}catch{return}}async loadMcpConfig($,Z){let J=p.join($,".mcp.json");try{let W=await G$.readFile(J,"utf-8"),X=JSON.parse(W),Y=l9(X);if(!Y.success){S.warn(`Invalid .mcp.json in ${$}: ${Y.error}`);return}let V="mcpServers"in X?X.mcpServers:X,B={};for(let[K,Q]of Object.entries(V)){let U=g9(Z,K);B[U]=Q}return B}catch{return}}async scanMarkdownFiles($){let Z=[],J=async(W)=>{let X=await G$.readdir(W,{withFileTypes:!0});for(let Y of X){let V=p.join(W,Y.name);if(Y.isDirectory())await J(V);else if(Y.name.endsWith(".md"))Z.push(V)}};return await J($),Z}async dirExists($){try{return(await G$.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}static getPluginDirs($){let Z=h3();return[{path:p.join(Z,".claude","plugins"),source:"user",type:"claude"},{path:p.join(Z,".blade","plugins"),source:"user",type:"blade"},{path:p.join($,".claude","plugins"),source:"project",type:"claude"},{path:p.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,Z){let J=[],W=[];try{await G$.access($)}catch{return{plugins:J,errors:W}}let X=await G$.readdir($,{withFileTypes:!0});for(let Y of X){if(!Y.isDirectory())continue;let V=p.join($,Y.name);try{let B=await this.loadPlugin(V,Z);J.push(B)}catch(B){W.push({path:V,error:B instanceof Error?B.message:String(B)})}}return{plugins:J,errors:W}}}class O0{static instance=null;plugins=new Map;loader=new l1;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!O0.instance)O0.instance=new O0;return O0.instance}static resetInstance(){O0.instance=null}async initialize($,Z=[]){this.workspaceRoot=$,this.cliPluginDirs=Z;let J=[],W=[];for(let Y of Z)try{let V=await this.loader.loadPlugin(Y,"cli");this.plugins.set(V.manifest.name,V),J.push(V),S.info(`Loaded CLI plugin: ${V.manifest.name} from ${Y}`)}catch(V){W.push({path:Y,error:V instanceof Error?V.message:String(V)}),S.warn(`Failed to load CLI plugin from ${Y}: ${V}`)}let X=l1.getPluginDirs($);for(let{path:Y,source:V}of X){let B=await this.loader.discoverPluginsInDir(Y,V);for(let K of B.plugins){let Q=this.plugins.get(K.manifest.name);if(!Q||Q.source!=="cli")this.plugins.set(K.manifest.name,K),J.push(K)}W.push(...B.errors)}return this.initialized=!0,S.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(W.length>0?`, ${W.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:W}}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 Z of this.plugins.values())$[Z.source].push(Z);return $}getAllCommands(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.commands);return $}getAllSkills(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.skills);return $}getAllAgents(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.agents);return $}findCommand($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}findSkill($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.skills)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.skills)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}findAgent($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.agents)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.agents)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}hasCommandConflict($){let Z=0;for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$){if(Z++,Z>1)return!0}}return!1}getCommandProviders($){let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$){Z.push(J.manifest.name);break}}return Z}disable($){let Z=this.plugins.get($);if(Z&&Z.status==="active")return Z.status="inactive",S.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.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,Z=0,J=0,W=0,X=0;for(let Y of this.plugins.values())if(Y.status==="active")$++,J+=Y.commands.length,W+=Y.skills.length,X+=Y.agents.length;else Z++;return{total:this.plugins.size,active:$,inactive:Z,commands:J,skills:W,agents:X}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let Z=[],J=this.getBySource();if(J.cli.length>0){Z.push("## CLI 指定的插件");for(let W of J.cli){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}Z.push("")}if(J.project.length>0){Z.push("## 项目级插件");for(let W of J.project){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}Z.push("")}if(J.user.length>0){Z.push("## 用户级插件");for(let W of J.user){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}}return Z.join(`
1576
- `)}}function I$(){return O0.getInstance()}class M8{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=d.getInstance(),this.hookManager=X$.getInstance(),this.mcpRegistry=F$.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),Q$().clearPluginSkills(),P.clearPluginAgents(),S.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let Z=I$().getActive(),J=[],W=[],X=0,Y=0,V=0,B=0;for(let K of Z){let Q=await this.integratePlugin(K);J.push(Q),X+=Q.commandsRegistered,Y+=Q.skillsRegistered,V+=Q.agentsRegistered,B+=Q.mcpServersRegistered,W.push(...Q.errors)}if(X+Y+V>0)S.info(`Plugin integration complete: ${X} commands, ${Y} skills, ${V} agents, ${B} MCP servers`);return{plugins:J,totalCommands:X,totalSkills:Y,totalAgents:V,totalMcpServers:B,errors:W}}async integratePlugin($){let Z={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{Z.commandsRegistered=this.integrateCommands($)}catch(J){Z.errors.push(`Failed to integrate commands: ${J instanceof Error?J.message:String(J)}`)}try{Z.skillsRegistered=this.integrateSkills($)}catch(J){Z.errors.push(`Failed to integrate skills: ${J instanceof Error?J.message:String(J)}`)}try{Z.agentsRegistered=this.integrateAgents($)}catch(J){Z.errors.push(`Failed to integrate agents: ${J instanceof Error?J.message:String(J)}`)}try{Z.hooksRegistered=this.integrateHooks($)}catch(J){Z.errors.push(`Failed to integrate hooks: ${J instanceof Error?J.message:String(J)}`)}try{Z.mcpServersRegistered=await this.integrateMcp($)}catch(J){Z.errors.push(`Failed to integrate MCP servers: ${J instanceof Error?J.message:String(J)}`)}return S.debug(`Integrated plugin "${$.manifest.name}": ${Z.commandsRegistered} commands, ${Z.skillsRegistered} skills, ${Z.agentsRegistered} agents`),Z}integrateCommands($){let Z=0;for(let J of $.commands)this.commandRegistry.registerPluginCommand(J),Z++;return Z}integrateSkills($){let Z=Q$(),J=0;for(let W of $.skills)Z.registerPluginSkill(W),J++;return J}integrateAgents($){let Z=0;for(let J of $.agents)P.register({...J.config,name:J.namespacedName}),Z++;return Z}integrateHooks($){if(!$.hooks)return!1;let Z=this.hookManager.getConfig();return this.hookManager.loadConfig({...Z,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let Z=0;for(let[J,W]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(J,W),Z++}catch(X){S.warn(`Failed to register MCP server "${J}" from plugin "${$.manifest.name}": ${X instanceof Error?X.message:String(X)}`)}return Z}}async function i1(){return new M8().integrateAll()}function a1(){new M8().clearAllPluginResources()}import{execSync as s9}from"node:child_process";import*as Z$ from"node:fs/promises";import{homedir as p3}from"node:os";import*as b0 from"node:path";class o9{userPluginsDir;constructor($){this.userPluginsDir=$||b0.join(p3(),".blade","plugins")}async install($){try{let Z=this.parseGitUrl($);if(!Z)return{success:!1,error:`Invalid source URL: ${$}`};let J=this.extractPluginName(Z);if(!J)return{success:!1,error:`Could not extract plugin name from URL: ${Z}`};await Z$.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let W=b0.join(this.userPluginsDir,J);try{return await Z$.access(W),{success:!1,pluginName:J,pluginPath:W,error:`Plugin "${J}" already exists at ${W}. Use /plugins uninstall first.`}}catch{}S.info(`Cloning ${Z} to ${W}...`);try{s9(`git clone --depth 1 "${Z}" "${W}"`,{stdio:"pipe",timeout:60000})}catch(Y){return{success:!1,pluginName:J,error:`Failed to clone repository: ${Y instanceof Error?Y.message:String(Y)}`}}if(!await a9(W))return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let X;try{X=await k0(W)}catch(Y){return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:`Invalid plugin manifest: ${Y instanceof Error?Y.message:String(Y)}`}}if(!X)return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:"Invalid plugin manifest: No manifest found"};return S.info(`Successfully installed plugin: ${X.manifest.name}`),{success:!0,pluginName:X.manifest.name,pluginPath:W,manifest:X.manifest}}catch(Z){return{success:!1,error:`Installation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async uninstall($){try{let Z=b0.join(this.userPluginsDir,$);try{await Z$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}return await Z$.rm(Z,{recursive:!0,force:!0}),S.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:Z}}catch(Z){return{success:!1,pluginName:$,error:`Uninstallation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async listInstalled(){try{return await Z$.access(this.userPluginsDir),(await Z$.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name)}catch{return[]}}async update($){try{let Z=b0.join(this.userPluginsDir,$);try{await Z$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}let J=b0.join(Z,".git");try{await Z$.access(J)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}S.info(`Updating plugin: ${$}...`);try{s9(`git -C "${Z}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(X){return{success:!1,pluginName:$,error:`Failed to update: ${X instanceof Error?X.message:String(X)}`}}let W;try{W=await k0(Z)}catch(X){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${X instanceof Error?X.message:String(X)}`}}if(!W)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return S.info(`Successfully updated plugin: ${W.manifest.name}`),{success:!0,pluginName:W.manifest.name,pluginPath:Z,manifest:W.manifest}}catch(Z){return{success:!1,pluginName:$,error:`Update failed: ${Z instanceof Error?Z.message:String(Z)}`}}}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 Z=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[1];let J=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(J)return J[2];return null}}var v8=null;function s0($){if(!v8)v8=new o9($);return v8}import WW from"fuse.js";import G2 from"node:fs/promises";import F2 from"node:path";import d3 from"node:os";import t9 from"node:path";function I($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
1575
+ `+" /init");let J=t();if(!J)throw Error("配置未初始化,请确保应用已正确启动");v1.getInstance().validateConfig(J);let W=new y1(J,$);return await W.initialize(),W}get sessionId(){return this.options.sessionId}getConfig(){return this.config}getChatService(){return this.chatService}getExecutionEngine(){return this.executionEngine}getAttachmentCollector(){return this.attachmentCollector}getCurrentModelId(){return this.currentModelId}getCurrentModelMaxContextTokens(){return this.currentModelMaxContextTokens}async initialize(){if(this.initialized)return;await this.validateSystemPromptConfig(),await this.registerBuiltinTools(),await this.loadSubagents(),await this.discoverSkills(),await this.applyModelConfig(this.resolveModelConfig(this.options.modelId),"使用模型:"),this.initialized=!0,O0.debug(`[SessionRuntime ${this.sessionId}] initialized with ${this.baseRegistry.getAll().length} tools`)}async refresh($){if(!this.initialized){await this.initialize();return}let Z=$.modelId&&$.modelId!=="inherit"?$.modelId:N$()?.id;if(Z&&Z!==this.currentModelId)await this.applyModelConfig(this.resolveModelConfig(Z),"切换模型")}createExecutionPipeline($={}){let Z=new l$,J=$.toolWhitelist?new Set($.toolWhitelist):null,W=$.toolBlacklist?new Set($.toolBlacklist):null;for(let V of this.baseRegistry.getBuiltinTools()){if(W?.has(V.name))continue;if(!J||J.has(V.name))Z.register(V)}for(let V of this.baseRegistry.getMcpTools()){if(W?.has(V.name))continue;if(!J||J.has(V.name))Z.registerMcpTool(V)}let X={...this.config.permissions,...$.permissions},Y=$.permissionMode??this.config.permissionMode??"default";return new u0(Z,{permissionConfig:X,permissionMode:Y,approvalStore:this.approvalStore,maxHistorySize:1000,toolWhitelist:$.toolWhitelist,toolBlacklist:$.toolBlacklist})}async dispose(){this.approvalStore.clear(),await this.chatService?.dispose?.(),this.currentModelId=void 0,this.initialized=!1}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?c0(Z):N$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){O0.debug(`${Z} ${$.name} (${$.model})`);let J=b1($),W=I1(),X=J&&W;this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await S1({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:X,thinkingBudget:$.thinkingBudget,fallbackModels:$.fallbackModels,enablePromptCaching:$.enablePromptCaching,customHeaders:$.customHeaders,apiVersion:$.apiVersion,maxRetries:$.maxRetries});let Y=this.executionEngine?.getContextManager();this.executionEngine=new m0(this.chatService,Y),this.currentModelId=$.id}async validateSystemPromptConfig(){try{await Z0({projectPath:N(),includeEnvironment:!1,language:this.config.language})}catch($){O0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let Z=(await P1({sessionId:this.sessionId,configDir:u9.join(d9.homedir(),".blade")})).filter((J)=>!J.name.startsWith("mcp__"));this.baseRegistry.registerAll(Z),await this.registerMcpTools()}async registerMcpTools(){try{if(this.options.mcpConfig&&this.options.mcpConfig.length>0)await Y1(this.options.mcpConfig);let $=E$();if(Object.keys($).length===0)return;let Z=O$.getInstance();for(let[W,X]of Object.entries($))try{await Z.registerServer(W,X)}catch(Y){O0.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();for(let W of J)this.baseRegistry.registerMcpTool(W)}catch($){O0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0)return;try{P.loadFromStandardLocations()}catch($){O0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await L0({cwd:N()})}catch($){O0.warn("Failed to discover skills:",$)}}}import*as G$ from"node:fs/promises";import{homedir as d3}from"node:os";import*as p from"node:path";import n9 from"gray-matter";function m1($,Z){return`${$}:${Z}`}function g9($,Z){return`${$}__${Z}`}import*as c1 from"node:fs/promises";import*as i9 from"node:path";import{z as _}from"zod";var y3=_.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"}),x3=_.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),f3=_.object({name:_.string().min(1,"Author name is required"),email:_.string().email().optional(),url:_.string().url().optional()}),c9=_.object({name:y3,description:_.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:x3,author:f3.optional(),license:_.string().optional(),repository:_.string().url().optional(),homepage:_.string().url().optional(),keywords:_.array(_.string()).optional(),dependencies:_.record(_.string()).optional(),bladeVersion:_.string().optional()}),m9=_.object({type:_.enum(["stdio","sse","http"]),command:_.string().optional(),args:_.array(_.string()).optional(),env:_.record(_.string()).optional(),url:_.string().url().optional(),headers:_.record(_.string()).optional(),timeout:_.number().positive().optional(),oauth:_.object({enabled:_.boolean().optional(),clientId:_.string().optional(),clientSecret:_.string().optional(),authorizationUrl:_.string().url().optional(),tokenUrl:_.string().url().optional(),scopes:_.array(_.string()).optional(),redirectUri:_.string().url().optional()}).optional(),healthCheck:_.object({enabled:_.boolean().optional(),interval:_.number().positive().optional(),timeout:_.number().positive().optional(),failureThreshold:_.number().positive().optional()}).optional()}),h3=_.union([_.object({mcpServers:_.record(m9)}),_.record(m9)]);function l9($){return h3.safeParse($)}var p3=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function b0($){for(let{dir:Z,source:J}of p3){let W=i9.join($,Z,"plugin.json");try{await c1.access(W)}catch{continue}try{let X=await c1.readFile(W,"utf-8"),Y=JSON.parse(X),V=c9.safeParse(Y);if(!V.success){let B=V.error.issues.map((K)=>`${K.path.join(".")}: ${K.message}`).join("; ");throw Error(`Invalid plugin.json: ${B}`)}return S.debug(`Parsed plugin manifest from ${W}`),{manifest:V.data,source:J,manifestPath:W}}catch(X){if(X instanceof SyntaxError)throw Error(`Invalid JSON in ${W}: ${X.message}`);throw X}}return null}async function a9($){try{return await b0($)!==null}catch{return!1}}class l1{async loadPlugin($,Z,J={}){let W=await b0($);if(!W)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:X,source:Y}=W,V=X.name;S.debug(`Loading plugin "${V}" from ${$}`);let B=J.skipCommands?[]:await this.loadCommands($,V),K=J.skipAgents?[]:await this.loadAgents($,V),Q=J.skipSkills?[]:await this.loadSkills($,V),U=J.skipHooks?void 0:await this.loadHooks($),q=J.skipMcp?void 0:await this.loadMcpConfig($,V);return S.debug(`Plugin "${V}" loaded: ${B.length} commands, ${K.length} agents, ${Q.length} skills`),{manifest:X,basePath:$,source:Z,manifestSource:Y,commands:B,agents:K,skills:Q,hooks:U,mcpServers:q,status:"active",loadedAt:new Date}}async loadCommands($,Z){let J=p.join($,"commands"),W=[];if(!await this.dirExists(J))return W;let X=await this.scanMarkdownFiles(J);for(let Y of X)try{let V=await this.parseCommandFile(Y,J,Z);if(V)W.push(V)}catch(V){S.warn(`Failed to load command from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseCommandFile($,Z,J){let W=await G$.readFile($,"utf-8"),{data:X,content:Y}=n9(W),B=p.relative(Z,$).split(p.sep),K=B.pop();if(!K)return null;let Q=K.replace(/\.md$/i,""),U=Q;if(B.length>0)U=[...B,Q].join("/");let q=m1(J,U),H=this.normalizeCommandConfig(X);return{originalName:U,namespacedName:q,pluginName:J,config:H,content:Y.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($,Z){let J=p.join($,"agents"),W=[];if(!await this.dirExists(J))return W;let X=await this.scanMarkdownFiles(J);for(let Y of X)try{let V=await this.parseAgentFile(Y,J,Z);if(V)W.push(V)}catch(V){S.warn(`Failed to load agent from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseAgentFile($,Z,J){let W=await G$.readFile($,"utf-8"),{data:X,content:Y}=n9(W),V=p.relative(Z,$),B=p.basename(V,".md"),K=X.name||B,Q=m1(J,K),U={name:Q,description:this.asString(X.description)||"",tools:this.parseStringArray(X.tools),color:this.asString(X.color),model:this.asString(X.model),permissionMode:this.asString(X.permissionMode),skills:this.parseStringArray(X.skills),systemPrompt:Y.trim(),source:`plugin:${J}`};return{originalName:K,namespacedName:Q,pluginName:J,config:U,path:$}}async loadSkills($,Z){let J=p.join($,"skills"),W=[];if(!await this.dirExists(J))return W;let X=await G$.readdir(J,{withFileTypes:!0});for(let Y of X){if(!Y.isDirectory())continue;let V=p.join(J,Y.name),B=p.join(V,"SKILL.md");try{let K=await r9(B,"project");if(K.success&&K.content){let Q=K.content.metadata.name,U=m1(Z,Q);W.push({originalName:Q,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:V})}}catch(K){S.warn(`Failed to load skill from ${B}: ${K instanceof Error?K.message:String(K)}`)}}return W}async loadHooks($){let Z=p.join($,"hooks","hooks.json");try{let J=await G$.readFile(Z,"utf-8"),W=JSON.parse(J);return W.hooks||W}catch{return}}async loadMcpConfig($,Z){let J=p.join($,".mcp.json");try{let W=await G$.readFile(J,"utf-8"),X=JSON.parse(W),Y=l9(X);if(!Y.success){S.warn(`Invalid .mcp.json in ${$}: ${Y.error}`);return}let V="mcpServers"in X?X.mcpServers:X,B={};for(let[K,Q]of Object.entries(V)){let U=g9(Z,K);B[U]=Q}return B}catch{return}}async scanMarkdownFiles($){let Z=[],J=async(W)=>{let X=await G$.readdir(W,{withFileTypes:!0});for(let Y of X){let V=p.join(W,Y.name);if(Y.isDirectory())await J(V);else if(Y.name.endsWith(".md"))Z.push(V)}};return await J($),Z}async dirExists($){try{return(await G$.stat($)).isDirectory()}catch{return!1}}asString($){if(typeof $==="string"&&$.trim())return $.trim();return}parseStringArray($){if(!$)return;if(Array.isArray($))return $.map((Z)=>String(Z).trim()).filter(Boolean);if(typeof $==="string")return $.split(",").map((Z)=>Z.trim()).filter(Boolean);return}static getPluginDirs($){let Z=d3();return[{path:p.join(Z,".claude","plugins"),source:"user",type:"claude"},{path:p.join(Z,".blade","plugins"),source:"user",type:"blade"},{path:p.join($,".claude","plugins"),source:"project",type:"claude"},{path:p.join($,".blade","plugins"),source:"project",type:"blade"}]}async discoverPluginsInDir($,Z){let J=[],W=[];try{await G$.access($)}catch{return{plugins:J,errors:W}}let X=await G$.readdir($,{withFileTypes:!0});for(let Y of X){if(!Y.isDirectory())continue;let V=p.join($,Y.name);try{let B=await this.loadPlugin(V,Z);J.push(B)}catch(B){W.push({path:V,error:B instanceof Error?B.message:String(B)})}}return{plugins:J,errors:W}}}class z0{static instance=null;plugins=new Map;loader=new l1;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!z0.instance)z0.instance=new z0;return z0.instance}static resetInstance(){z0.instance=null}async initialize($,Z=[]){this.workspaceRoot=$,this.cliPluginDirs=Z;let J=[],W=[];for(let Y of Z)try{let V=await this.loader.loadPlugin(Y,"cli");this.plugins.set(V.manifest.name,V),J.push(V),S.info(`Loaded CLI plugin: ${V.manifest.name} from ${Y}`)}catch(V){W.push({path:Y,error:V instanceof Error?V.message:String(V)}),S.warn(`Failed to load CLI plugin from ${Y}: ${V}`)}let X=l1.getPluginDirs($);for(let{path:Y,source:V}of X){let B=await this.loader.discoverPluginsInDir(Y,V);for(let K of B.plugins){let Q=this.plugins.get(K.manifest.name);if(!Q||Q.source!=="cli")this.plugins.set(K.manifest.name,K),J.push(K)}W.push(...B.errors)}return this.initialized=!0,S.info(`Plugin system initialized: ${this.plugins.size} plugins loaded`+(W.length>0?`, ${W.length} errors`:"")),{plugins:Array.from(this.plugins.values()),errors:W}}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 Z of this.plugins.values())$[Z.source].push(Z);return $}getAllCommands(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.commands);return $}getAllSkills(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.skills);return $}getAllAgents(){let $=[];for(let Z of this.plugins.values())if(Z.status==="active")$.push(...Z.agents);return $}findCommand($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}findSkill($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.skills)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.skills)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}findAgent($){for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.agents)if(W.namespacedName===$)return W}let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.agents)if(W.originalName===$)Z.push(W)}if(Z.length===1)return Z[0];return}hasCommandConflict($){let Z=0;for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$){if(Z++,Z>1)return!0}}return!1}getCommandProviders($){let Z=[];for(let J of this.plugins.values()){if(J.status!=="active")continue;for(let W of J.commands)if(W.originalName===$){Z.push(J.manifest.name);break}}return Z}disable($){let Z=this.plugins.get($);if(Z&&Z.status==="active")return Z.status="inactive",S.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.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,Z=0,J=0,W=0,X=0;for(let Y of this.plugins.values())if(Y.status==="active")$++,J+=Y.commands.length,W+=Y.skills.length,X+=Y.agents.length;else Z++;return{total:this.plugins.size,active:$,inactive:Z,commands:J,skills:W,agents:X}}formatPluginList(){if(this.getAll().length===0)return"没有已加载的插件。";let Z=[],J=this.getBySource();if(J.cli.length>0){Z.push("## CLI 指定的插件");for(let W of J.cli){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}Z.push("")}if(J.project.length>0){Z.push("## 项目级插件");for(let W of J.project){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}Z.push("")}if(J.user.length>0){Z.push("## 用户级插件");for(let W of J.user){let X=W.status==="inactive"?" (禁用)":"";Z.push(`- **${W.manifest.name}** v${W.manifest.version}${X}`),Z.push(` ${W.manifest.description}`)}}return Z.join(`
1576
+ `)}}function S$(){return z0.getInstance()}class M8{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=d.getInstance(),this.hookManager=X$.getInstance(),this.mcpRegistry=O$.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),Q$().clearPluginSkills(),P.clearPluginAgents(),S.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let Z=S$().getActive(),J=[],W=[],X=0,Y=0,V=0,B=0;for(let K of Z){let Q=await this.integratePlugin(K);J.push(Q),X+=Q.commandsRegistered,Y+=Q.skillsRegistered,V+=Q.agentsRegistered,B+=Q.mcpServersRegistered,W.push(...Q.errors)}if(X+Y+V>0)S.info(`Plugin integration complete: ${X} commands, ${Y} skills, ${V} agents, ${B} MCP servers`);return{plugins:J,totalCommands:X,totalSkills:Y,totalAgents:V,totalMcpServers:B,errors:W}}async integratePlugin($){let Z={pluginName:$.manifest.name,commandsRegistered:0,skillsRegistered:0,agentsRegistered:0,hooksRegistered:!1,mcpServersRegistered:0,errors:[]};try{Z.commandsRegistered=this.integrateCommands($)}catch(J){Z.errors.push(`Failed to integrate commands: ${J instanceof Error?J.message:String(J)}`)}try{Z.skillsRegistered=this.integrateSkills($)}catch(J){Z.errors.push(`Failed to integrate skills: ${J instanceof Error?J.message:String(J)}`)}try{Z.agentsRegistered=this.integrateAgents($)}catch(J){Z.errors.push(`Failed to integrate agents: ${J instanceof Error?J.message:String(J)}`)}try{Z.hooksRegistered=this.integrateHooks($)}catch(J){Z.errors.push(`Failed to integrate hooks: ${J instanceof Error?J.message:String(J)}`)}try{Z.mcpServersRegistered=await this.integrateMcp($)}catch(J){Z.errors.push(`Failed to integrate MCP servers: ${J instanceof Error?J.message:String(J)}`)}return S.debug(`Integrated plugin "${$.manifest.name}": ${Z.commandsRegistered} commands, ${Z.skillsRegistered} skills, ${Z.agentsRegistered} agents`),Z}integrateCommands($){let Z=0;for(let J of $.commands)this.commandRegistry.registerPluginCommand(J),Z++;return Z}integrateSkills($){let Z=Q$(),J=0;for(let W of $.skills)Z.registerPluginSkill(W),J++;return J}integrateAgents($){let Z=0;for(let J of $.agents)P.register({...J.config,name:J.namespacedName}),Z++;return Z}integrateHooks($){if(!$.hooks)return!1;let Z=this.hookManager.getConfig();return this.hookManager.loadConfig({...Z,...$.hooks}),!0}async integrateMcp($){if(!$.mcpServers)return 0;let Z=0;for(let[J,W]of Object.entries($.mcpServers))try{await this.mcpRegistry.registerServer(J,W),Z++}catch(X){S.warn(`Failed to register MCP server "${J}" from plugin "${$.manifest.name}": ${X instanceof Error?X.message:String(X)}`)}return Z}}async function i1(){return new M8().integrateAll()}function a1(){new M8().clearAllPluginResources()}import{execSync as s9}from"node:child_process";import*as Z$ from"node:fs/promises";import{homedir as u3}from"node:os";import*as T0 from"node:path";class o9{userPluginsDir;constructor($){this.userPluginsDir=$||T0.join(u3(),".blade","plugins")}async install($){try{let Z=this.parseGitUrl($);if(!Z)return{success:!1,error:`Invalid source URL: ${$}`};let J=this.extractPluginName(Z);if(!J)return{success:!1,error:`Could not extract plugin name from URL: ${Z}`};await Z$.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let W=T0.join(this.userPluginsDir,J);try{return await Z$.access(W),{success:!1,pluginName:J,pluginPath:W,error:`Plugin "${J}" already exists at ${W}. Use /plugins uninstall first.`}}catch{}S.info(`Cloning ${Z} to ${W}...`);try{s9(`git clone --depth 1 "${Z}" "${W}"`,{stdio:"pipe",timeout:60000})}catch(Y){return{success:!1,pluginName:J,error:`Failed to clone repository: ${Y instanceof Error?Y.message:String(Y)}`}}if(!await a9(W))return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:"Invalid plugin: No .blade-plugin/plugin.json or .claude-plugin/plugin.json found"};let X;try{X=await b0(W)}catch(Y){return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:`Invalid plugin manifest: ${Y instanceof Error?Y.message:String(Y)}`}}if(!X)return await Z$.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:"Invalid plugin manifest: No manifest found"};return S.info(`Successfully installed plugin: ${X.manifest.name}`),{success:!0,pluginName:X.manifest.name,pluginPath:W,manifest:X.manifest}}catch(Z){return{success:!1,error:`Installation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async uninstall($){try{let Z=T0.join(this.userPluginsDir,$);try{await Z$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}return await Z$.rm(Z,{recursive:!0,force:!0}),S.info(`Successfully uninstalled plugin: ${$}`),{success:!0,pluginName:$,pluginPath:Z}}catch(Z){return{success:!1,pluginName:$,error:`Uninstallation failed: ${Z instanceof Error?Z.message:String(Z)}`}}}async listInstalled(){try{return await Z$.access(this.userPluginsDir),(await Z$.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name)}catch{return[]}}async update($){try{let Z=T0.join(this.userPluginsDir,$);try{await Z$.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}let J=T0.join(Z,".git");try{await Z$.access(J)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}S.info(`Updating plugin: ${$}...`);try{s9(`git -C "${Z}" pull --ff-only`,{stdio:"pipe",timeout:60000})}catch(X){return{success:!1,pluginName:$,error:`Failed to update: ${X instanceof Error?X.message:String(X)}`}}let W;try{W=await b0(Z)}catch(X){return{success:!1,pluginName:$,error:`Plugin manifest invalid after update: ${X instanceof Error?X.message:String(X)}`}}if(!W)return{success:!1,pluginName:$,error:"Plugin manifest not found after update"};return S.info(`Successfully updated plugin: ${W.manifest.name}`),{success:!0,pluginName:W.manifest.name,pluginPath:Z,manifest:W.manifest}}catch(Z){return{success:!1,pluginName:$,error:`Update failed: ${Z instanceof Error?Z.message:String(Z)}`}}}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 Z=$.match(/\/([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(Z)return Z[1];let J=$.match(/:([a-zA-Z0-9_-]+\/)?([a-zA-Z0-9_.-]+?)(?:\.git)?$/);if(J)return J[2];return null}}var v8=null;function s0($){if(!v8)v8=new o9($);return v8}import YW from"fuse.js";import G2 from"node:fs/promises";import F2 from"node:path";import g3 from"node:os";import t9 from"node:path";function I($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
1577
1577
 
1578
1578
  `),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>A().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var e9={name:"agents",description:"Manage agent configurations",fullDescription:"Create, edit, or delete custom subagents. Subagents are specialized agents that Claude can delegate tasks to.",usage:"/agents [list|create|help]",category:"System",examples:["/agents","/agents list","/agents help"],async handler($,Z){let J=$[0],W=I(Z);if(!J)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(J==="list"){let Y=P.getAllNames().map((q)=>P.getSubagent(q)).filter((q)=>q!==void 0);if(Y.length===0){let q=`**Agents 管理**
1579
1579
 
1580
1580
  `+`没有找到任何 agent 配置
1581
1581
 
1582
1582
  `+`**配置文件位置:**
1583
- `+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"使用 `/agents` 打开管理对话框";return W.sendMessage(q),{success:!0,message:"No agents found"}}let V=t9.join(N(),".blade","agents"),B=t9.join(d3.homedir(),".blade","agents"),K=Y.filter((q)=>q.configPath?.startsWith(V)),Q=Y.filter((q)=>q.configPath?.startsWith(B)),U=`**Agents 管理**
1583
+ `+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"使用 `/agents` 打开管理对话框";return W.sendMessage(q),{success:!0,message:"No agents found"}}let V=t9.join(N(),".blade","agents"),B=t9.join(g3.homedir(),".blade","agents"),K=Y.filter((q)=>q.configPath?.startsWith(V)),Q=Y.filter((q)=>q.configPath?.startsWith(B)),U=`**Agents 管理**
1584
1584
 
1585
1585
  找到 **${Y.length}** 个 agent:
1586
1586
 
@@ -1620,7 +1620,7 @@ IMPORTANT - Use the correct year in search queries:
1620
1620
  `+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
1621
1621
  `+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"**提示:** 创建文件后,重启 Blade 使配置生效";return W.sendMessage(Y),{success:!0,message:"Help displayed"}}if(J==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let X=`未知子命令: \`${J}\`
1622
1622
 
1623
- `+"使用 `/agents help` 查看可用命令";return W.sendMessage(X),{success:!1,error:`Unknown subcommand: ${J}`}}};async function u3($,Z){let J=I(Z);try{let W=t(),X=j$();if(!W||!X)return{success:!1,error:"配置未初始化"};let Y=i().session,V=Y.messages,B=Y.sessionId;if(!V||V.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let K=V.map((G)=>({role:G.role,content:G.content})),Q=n1.countTokens(K,X.model),U=X.maxContextTokens??W.maxContextTokens,q=(Q/U*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
1623
+ `+"使用 `/agents help` 查看可用命令";return W.sendMessage(X),{success:!1,error:`Unknown subcommand: ${J}`}}};async function m3($,Z){let J=I(Z);try{let W=t(),X=N$();if(!W||!X)return{success:!1,error:"配置未初始化"};let Y=i().session,V=Y.messages,B=Y.sessionId;if(!V||V.length===0)return J.sendMessage("[WARN] 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let K=V.map((G)=>({role:G.role,content:G.content})),Q=n1.countTokens(K,X.model),U=X.maxContextTokens??W.maxContextTokens,q=(Q/U*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
1624
1624
  • 消息数量: ${K.length}
1625
1625
  • Token 数量: ${Q.toLocaleString()}
1626
1626
  • Token 限制: ${U.toLocaleString()}
@@ -1642,11 +1642,11 @@ IMPORTANT - Use the correct year in search queries:
1642
1642
  • 压缩后: ${H.postTokens.toLocaleString()} tokens
1643
1643
 
1644
1644
  由于压缩过程出现错误,已使用简单截断策略。
1645
- 错误信息: ${H.error}`),{success:!1,message:"compact_fallback",error:H.error,data:{compactedMessages:H.compactedMessages,boundaryMessage:H.boundaryMessage,summaryMessage:H.summaryMessage,preTokens:H.preTokens,postTokens:H.postTokens}}}catch(W){let X=W instanceof Error?W.message:String(W);return J.sendMessage(`[FAIL] **压缩失败**: ${X}`),{success:!1,error:X}}}var g3={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:u3},Z2=g3;function W2($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let W=Math.floor(J/60);if(W<24)return`${W}h ago`;return`${Math.floor(W/24)}d ago`}async function m3($){let Z=F$.getInstance(),J=L$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
1645
+ 错误信息: ${H.error}`),{success:!1,message:"compact_fallback",error:H.error,data:{compactedMessages:H.compactedMessages,boundaryMessage:H.boundaryMessage,summaryMessage:H.summaryMessage,preTokens:H.preTokens,postTokens:H.postTokens}}}catch(W){let X=W instanceof Error?W.message:String(W);return J.sendMessage(`[FAIL] **压缩失败**: ${X}`),{success:!1,error:X}}}var c3={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:m3},Z2=c3;function W2($){let Z=Math.floor((Date.now()-$.getTime())/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;let W=Math.floor(J/60);if(W<24)return`${W}h ago`;return`${Math.floor(W/24)}d ago`}async function l3($){let Z=O$.getInstance(),J=E$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
1646
1646
 
1647
1647
  [WARN] 暂无配置的 MCP 服务器
1648
1648
 
1649
- 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$.sendMessage("正在检查 MCP 服务器状态...");let W=Object.entries(J).map(async([X,Y])=>{try{let V=Z.getServerStatus(X);if(!V)await Z.registerServer(X,Y),V=Z.getServerStatus(X);else if(V.status==="disconnected")await Z.connectServer(X);return{name:X,config:Y,serverInfo:Z.getServerStatus(X)}}catch(V){return{name:X,config:Y,serverInfo:null,error:V}}});await Promise.all(W),c3($,Z.getAllServers())}function c3($,Z){let J=`**MCP 服务器状态**
1649
+ 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$.sendMessage("正在检查 MCP 服务器状态...");let W=Object.entries(J).map(async([X,Y])=>{try{let V=Z.getServerStatus(X);if(!V)await Z.registerServer(X,Y),V=Z.getServerStatus(X);else if(V.status==="disconnected")await Z.connectServer(X);return{name:X,config:Y,serverInfo:Z.getServerStatus(X)}}catch(V){return{name:X,config:Y,serverInfo:null,error:V}}});await Promise.all(W),i3($,Z.getAllServers())}function i3($,Z){let J=`**MCP 服务器状态**
1650
1650
 
1651
1651
  `,W=0,X=0,Y=0;for(let[V,B]of Z){let{config:K,status:Q,connectedAt:U,lastError:q,tools:H}=B,G=Q==="connected"?"[OK]":"[FAIL]",O=Q==="connected"?"Connected":"Disconnected";if(Q==="connected")W++,Y+=H.length;else X++;if(J+=`**${V}**
1652
1652
  `,J+=` 状态: ${G} ${O}
@@ -1661,10 +1661,10 @@ IMPORTANT - Use the correct year in search queries:
1661
1661
  `,J+=`- 服务器: ${Z.size} 个 (${W} 连接, ${X} 断开)
1662
1662
  `,J+=`- 可用工具: ${Y} 个
1663
1663
 
1664
- `,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function l3($,Z){let J=F$.getInstance(),X=L$()[Z];if(!X){$.sendMessage(`服务器 "${Z}" 不存在
1664
+ `,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function a3($,Z){let J=O$.getInstance(),X=E$()[Z];if(!X){$.sendMessage(`服务器 "${Z}" 不存在
1665
1665
 
1666
- 使用 \`/mcp\` 查看所有可用服务器`);return}try{let Y=J.getServerStatus(Z);if(!Y)$.sendMessage(`正在连接 ${Z}...`),await J.registerServer(Z,X),Y=J.getServerStatus(Z);else if(Y.status==="disconnected")$.sendMessage(`正在重新连接 ${Z}...`),await J.connectServer(Z),Y=J.getServerStatus(Z);if(Y)i3($,Z,Y);else J2($,Z,X)}catch(Y){J2($,Z,X),$.sendMessage(`
1667
- [WARN] 连接失败: ${Y instanceof Error?Y.message:"未知错误"}`)}}function i3($,Z,J){let{config:W,status:X,connectedAt:Y,lastError:V,tools:B}=J,K=X==="connected"?"[OK]":"[FAIL]",Q=X==="connected"?"Connected":"Disconnected",U=`**${Z}**
1666
+ 使用 \`/mcp\` 查看所有可用服务器`);return}try{let Y=J.getServerStatus(Z);if(!Y)$.sendMessage(`正在连接 ${Z}...`),await J.registerServer(Z,X),Y=J.getServerStatus(Z);else if(Y.status==="disconnected")$.sendMessage(`正在重新连接 ${Z}...`),await J.connectServer(Z),Y=J.getServerStatus(Z);if(Y)n3($,Z,Y);else J2($,Z,X)}catch(Y){J2($,Z,X),$.sendMessage(`
1667
+ [WARN] 连接失败: ${Y instanceof Error?Y.message:"未知错误"}`)}}function n3($,Z,J){let{config:W,status:X,connectedAt:Y,lastError:V,tools:B}=J,K=X==="connected"?"[OK]":"[FAIL]",Q=X==="connected"?"Connected":"Disconnected",U=`**${Z}**
1668
1668
 
1669
1669
  `;if(U+=`**连接状态:**
1670
1670
  `,U+=` ${K} ${Q}`,Y&&X==="connected")U+=` (连接于 ${W2(Y)})`;if(U+=`
@@ -1699,7 +1699,7 @@ IMPORTANT - Use the correct year in search queries:
1699
1699
  `,J.headers&&Object.keys(J.headers).length>0)W+=` Headers: ${Object.keys(J.headers).join(", ")}
1700
1700
  `;if(J.timeout)W+=` 超时: ${J.timeout}ms
1701
1701
  `;W+=`
1702
- 服务器将在 Agent 启动时自动连接`,$.sendMessage(W)}async function a3($){let Z=F$.getInstance(),J=L$();if(Object.keys(J).length===0){$.sendMessage(`**可用的 MCP 工具**
1702
+ 服务器将在 Agent 启动时自动连接`,$.sendMessage(W)}async function r3($){let Z=O$.getInstance(),J=E$();if(Object.keys(J).length===0){$.sendMessage(`**可用的 MCP 工具**
1703
1703
 
1704
1704
  [WARN] 暂无配置的 MCP 服务器
1705
1705
 
@@ -1712,7 +1712,7 @@ IMPORTANT - Use the correct year in search queries:
1712
1712
 
1713
1713
  `;continue}V+=U.length;for(let q of U){if(Y+=` • ${q.name}`,q.description){let H=q.description.length>60?q.description.substring(0,57)+"...":q.description;Y+=` - ${H}`}Y+=`
1714
1714
  `}Y+=`
1715
- `}Y+=`**总计:** ${V} 个工具可用`,$.sendMessage(Y)}var n3={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($,Z){let J=I(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await m3(J),{success:!0,message:"MCP 服务器概览已显示"};let W=$[0];if(console.log("[MCP Command] Subcommand:",W),W==="tools")return await a3(J),{success:!0,message:"MCP 工具列表已显示"};return await l3(J,W),{success:!0,message:`服务器 "${W}" 详情已显示`}}catch(W){return{success:!1,error:`显示 MCP 信息失败: ${W instanceof Error?W.message:"未知错误"}`}}}},X2=n3;import{spawn as r3}from"node:child_process";import*as Y2 from"node:path";function s3($){return new Promise((Z)=>{let J=process.env.EDITOR||process.env.VISUAL||"vi",W=r3(J,[$],{stdio:"inherit"});W.on("close",(X)=>{Z(X===0)}),W.on("error",()=>{Z(!1)})})}var o3={name:"memory",description:"Manage project auto memory",fullDescription:"查看和管理项目的 Auto Memory(跨会话持久记忆)",usage:"/memory [list|show|edit|clear]",aliases:["mem"],async handler($,Z){let J=I(Z),W=N(),X=new T$(W);switch($[0]||"list"){case"list":{let V=await X.listTopics();if(V.length===0)J.sendMessage(`暂无记忆文件。Agent 在工作过程中会自动记录有价值的项目知识。
1715
+ `}Y+=`**总计:** ${V} 个工具可用`,$.sendMessage(Y)}var s3={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($,Z){let J=I(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await l3(J),{success:!0,message:"MCP 服务器概览已显示"};let W=$[0];if(console.log("[MCP Command] Subcommand:",W),W==="tools")return await r3(J),{success:!0,message:"MCP 工具列表已显示"};return await a3(J,W),{success:!0,message:`服务器 "${W}" 详情已显示`}}catch(W){return{success:!1,error:`显示 MCP 信息失败: ${W instanceof Error?W.message:"未知错误"}`}}}},X2=s3;import{spawn as o3}from"node:child_process";import*as Y2 from"node:path";function t3($){return new Promise((Z)=>{let J=process.env.EDITOR||process.env.VISUAL||"vi",W=o3(J,[$],{stdio:"inherit"});W.on("close",(X)=>{Z(X===0)}),W.on("error",()=>{Z(!1)})})}var e3={name:"memory",description:"Manage project auto memory",fullDescription:"查看和管理项目的 Auto Memory(跨会话持久记忆)",usage:"/memory [list|show|edit|clear]",aliases:["mem"],async handler($,Z){let J=I(Z),W=N(),X=new M$(W);switch($[0]||"list"){case"list":{let V=await X.listTopics();if(V.length===0)J.sendMessage(`暂无记忆文件。Agent 在工作过程中会自动记录有价值的项目知识。
1716
1716
 
1717
1717
  `+`记忆目录: ${X.getMemoryDir()}`);else{let B=V.map((K)=>{let Q=(K.size/1024).toFixed(1),U=K.lastModified.toLocaleDateString("zh-CN");return`${K.name==="MEMORY"?"[INDEX]":"[FILE]"} **${K.name}.md** — ${Q}KB, ${U}`}).join(`
1718
1718
  `);J.sendMessage(`**项目记忆文件:**
@@ -1721,7 +1721,7 @@ ${B}
1721
1721
 
1722
1722
  `+"使用 `/memory edit [topic]` 编辑,`/memory show [topic]` 查看\n"+`${X.getMemoryDir()}`)}return{success:!0,message:"记忆列表已显示"}}case"show":{let V=$[1]||"MEMORY",B=await X.readTopic(V);if(B===null)J.sendMessage(`记忆文件 "${V}.md" 不存在`);else J.sendMessage(`**${V}.md:**
1723
1723
 
1724
- ${B}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",B=Y2.join(X.getMemoryDir(),`${V}.md`);if(await X.initialize(),await X.readTopic(V)===null)await X.writeTopic(V,"","overwrite");let Q=process.env.EDITOR||process.env.VISUAL||"vi";if(J.sendMessage(`正在用 ${Q} 打开 ${V}.md ...`),await s3(B))J.sendMessage(`[OK] ${V}.md 编辑完成`);else J.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
1724
+ ${B}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",B=Y2.join(X.getMemoryDir(),`${V}.md`);if(await X.initialize(),await X.readTopic(V)===null)await X.writeTopic(V,"","overwrite");let Q=process.env.EDITOR||process.env.VISUAL||"vi";if(J.sendMessage(`正在用 ${Q} 打开 ${V}.md ...`),await t3(B))J.sendMessage(`[OK] ${V}.md 编辑完成`);else J.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
1725
1725
  ${B}
1726
1726
 
1727
1727
  `+"设置 EDITOR 环境变量来指定编辑器(如 export EDITOR=code)");return{success:!0,message:"编辑完成"}}case"clear":{let V=await X.clearAll();return J.sendMessage(`已清除 ${V} 个记忆文件`),{success:!0,message:`已清除 ${V} 个记忆文件`}}default:return J.sendMessage(`**Auto Memory 命令:**
@@ -1729,14 +1729,14 @@ ${B}
1729
1729
  `+`/memory list — 列出所有记忆文件
1730
1730
  `+`/memory show [topic] — 查看记忆内容(默认 MEMORY)
1731
1731
  `+`/memory edit [topic] — 用编辑器打开记忆文件(默认 MEMORY)
1732
- `+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},V2=o3;async function t3($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var e3={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:t3},r1=e3;import{readdir as B2,readFile as K2,rm as $J}from"node:fs/promises";import*as s1 from"node:path";var C8=M("Service");class o0{static toUISafeMessages($){let Z=Date.now(),J=$.length,W=[];return $.forEach((X,Y)=>{if(X.role!=="user"&&X.role!=="assistant")return;let V;if(typeof X.content==="string")V=X.content;else if(Array.isArray(X.content))V=X.content.map((Q)=>Q.type==="text"?Q.text:"[Image]").join("");else V="";let B=V.trim();if(!B)return;let K=W[W.length-1];if(K&&K.role===X.role&&K.content===B)return;W.push({id:`restored-${Z}-${Y}`,role:X.role,content:B,timestamp:Z-(J-Y)*1000,metadata:X.metadata&&typeof X.metadata==="object"?X.metadata:void 0})}),W}static async listSessions(){let $=[],Z=s1.join(b$(),"projects");try{let J=await B2(Z,{withFileTypes:!0});for(let W of J){if(!W.isDirectory())continue;let X=s1.join(Z,W.name),Y=i8(W.name),B=(await B2(X)).filter((K)=>K.endsWith(".jsonl"));for(let K of B){let Q=s1.join(X,K),U=K.replace(".jsonl","");try{let q=await this.extractMetadata(Q,U,Y);$.push(q)}catch(q){C8.warn(`[SessionService] 跳过损坏的会话文件: ${Q}`,q)}}}return $.sort((W,X)=>new Date(X.lastMessageTime).getTime()-new Date(W.lastMessageTime).getTime()),$}catch(J){return C8.error("[SessionService] 列出会话失败:",J),[]}}static async extractMetadata($,Z,J){let X=(await K2($,"utf-8")).trim().split(`
1733
- `).filter((q)=>q.trim());if(X.length===0)throw Error("空的 JSONL 文件");let Y=X.map((q)=>JSON.parse(q)),V=Y[0],B=Y[Y.length-1],K=Y.find((q)=>q.type==="session_created"),Q=Y.filter((q)=>q.type==="message_created"&&["user","assistant"].includes(q.data.role)).length,U=Y.some((q)=>q.type==="part_created"&&q.data.partType==="tool_result"&&typeof q.data.payload.error==="string");return{sessionId:Z,projectPath:J,gitBranch:K?.gitBranch??V.gitBranch,parentId:K?.data.parentId,relationType:K?.data.relationType,status:K?.data.status,agentType:K?.data.agentType,model:K?.data.model,messageCount:Q,firstMessageTime:V.timestamp,lastMessageTime:B.timestamp,hasErrors:U,filePath:$}}static async loadSession($,Z){try{if(Z){let X=this.getSessionFilePath(Z,$);return await this.loadSessionFromFile(X)}let W=(await this.listSessions()).find((X)=>X.sessionId===$);if(!W)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(W.filePath)}catch(J){throw C8.error(`[SessionService] 加载会话失败 (${$}):`,J),J}}static async deleteSession($){let J=(await this.listSessions()).filter((W)=>W.sessionId===$);if(J.length===0)return 0;return await Promise.all(J.map((W)=>$J(W.filePath,{force:!0}))),J.length}static async loadSessionFromFile($){let W=(await K2($,"utf-8")).trim().split(`
1734
- `).filter((X)=>X.trim()).map((X)=>JSON.parse(X));return this.convertJSONLToMessages(W)}static convertJSONLToMessages($){let Z=[],J=new Map,W=new Map;for(let X of $){if(X.type==="message_created"){let Y={role:X.data.role,content:""};J.set(X.data.messageId,Y),W.set(X.data.messageId,[]),Z.push(Y)}if(X.type==="part_created"){if(X.data.partType==="text"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=W.get(X.data.messageId);if(B)B.push({type:"text",text:V.text??""}),Y.content=Q2(B);else Y.content=V.text??""}}if(X.data.partType==="image"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=W.get(X.data.messageId);if(B&&V.dataUrl)B.push({type:"image_url",image_url:{url:V.dataUrl}}),Y.content=Q2(B)}}if(X.data.partType==="tool_result"){let Y=X.data.payload,V=typeof Y.error==="string"?`Error: ${Y.error}`:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output??""),B=Y;Z.push({role:"tool",content:V,tool_call_id:Y.toolCallId,name:Y.toolName,metadata:B})}if(X.data.partType==="summary"){let Y=X.data.payload,V=X.data.payload;Z.push({role:"system",content:Y.text??"",metadata:V})}if(X.data.partType==="subtask_ref"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=Y.metadata??{};Y.metadata={...B,subtaskRef:V}}}}}return Z}static getSessionFilePath($,Z){return W$($,Z)}}function Q2($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}var ZJ={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){let J=I(Z),W=A().restoreSession;if($.length>0){let X=$[0];try{let Y=await o0.loadSession(X);if(Y.length===0)return J.sendMessage(`[FAIL] 会话 \`${X}\` 为空或无法加载`),{success:!1,error:"会话为空"};let V=o0.toUISafeMessages(Y);return W(X,V,Y),J.sendMessage(`[OK] 已恢复会话 \`${X}\`
1732
+ `+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},V2=e3;async function $J($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var ZJ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:$J},r1=ZJ;import{readdir as B2,readFile as K2,rm as JJ}from"node:fs/promises";import*as s1 from"node:path";var C8=M("Service");class o0{static toUISafeMessages($){let Z=Date.now(),J=$.length,W=[];return $.forEach((X,Y)=>{if(X.role!=="user"&&X.role!=="assistant")return;let V;if(typeof X.content==="string")V=X.content;else if(Array.isArray(X.content))V=X.content.map((Q)=>Q.type==="text"?Q.text:"[Image]").join("");else V="";let B=V.trim();if(!B)return;let K=W[W.length-1];if(K&&K.role===X.role&&K.content===B)return;W.push({id:`restored-${Z}-${Y}`,role:X.role,content:B,timestamp:Z-(J-Y)*1000,metadata:X.metadata&&typeof X.metadata==="object"?X.metadata:void 0})}),W}static async listSessions(){let $=[],Z=s1.join(T$(),"projects");try{let J=await B2(Z,{withFileTypes:!0});for(let W of J){if(!W.isDirectory())continue;let X=s1.join(Z,W.name),Y=i8(W.name),B=(await B2(X)).filter((K)=>K.endsWith(".jsonl"));for(let K of B){let Q=s1.join(X,K),U=K.replace(".jsonl","");try{let q=await this.extractMetadata(Q,U,Y);$.push(q)}catch(q){C8.warn(`[SessionService] 跳过损坏的会话文件: ${Q}`,q)}}}return $.sort((W,X)=>new Date(X.lastMessageTime).getTime()-new Date(W.lastMessageTime).getTime()),$}catch(J){return C8.error("[SessionService] 列出会话失败:",J),[]}}static async extractMetadata($,Z,J){let X=(await K2($,"utf-8")).trim().split(`
1733
+ `).filter((q)=>q.trim());if(X.length===0)throw Error("空的 JSONL 文件");let Y=X.map((q)=>JSON.parse(q)),V=Y[0],B=Y[Y.length-1],K=Y.find((q)=>q.type==="session_created"),Q=Y.filter((q)=>q.type==="message_created"&&["user","assistant"].includes(q.data.role)).length,U=Y.some((q)=>q.type==="part_created"&&q.data.partType==="tool_result"&&typeof q.data.payload.error==="string");return{sessionId:Z,projectPath:J,gitBranch:K?.gitBranch??V.gitBranch,parentId:K?.data.parentId,relationType:K?.data.relationType,status:K?.data.status,agentType:K?.data.agentType,model:K?.data.model,messageCount:Q,firstMessageTime:V.timestamp,lastMessageTime:B.timestamp,hasErrors:U,filePath:$}}static async loadSession($,Z){try{if(Z){let X=this.getSessionFilePath(Z,$);return await this.loadSessionFromFile(X)}let W=(await this.listSessions()).find((X)=>X.sessionId===$);if(!W)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(W.filePath)}catch(J){throw C8.error(`[SessionService] 加载会话失败 (${$}):`,J),J}}static async deleteSession($){let J=(await this.listSessions()).filter((W)=>W.sessionId===$);if(J.length===0)return 0;return await Promise.all(J.map((W)=>JJ(W.filePath,{force:!0}))),J.length}static async loadSessionFromFile($){let W=(await K2($,"utf-8")).trim().split(`
1734
+ `).filter((X)=>X.trim()).map((X)=>JSON.parse(X));return this.convertJSONLToMessages(W)}static convertJSONLToMessages($){let Z=[],J=new Map,W=new Map;for(let X of $){if(X.type==="message_created"){let Y={role:X.data.role,content:""};J.set(X.data.messageId,Y),W.set(X.data.messageId,[]),Z.push(Y)}if(X.type==="part_created"){if(X.data.partType==="text"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=W.get(X.data.messageId);if(B)B.push({type:"text",text:V.text??""}),Y.content=Q2(B);else Y.content=V.text??""}}if(X.data.partType==="image"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=W.get(X.data.messageId);if(B&&V.dataUrl)B.push({type:"image_url",image_url:{url:V.dataUrl}}),Y.content=Q2(B)}}if(X.data.partType==="tool_result"){let Y=X.data.payload,V=typeof Y.error==="string"?`Error: ${Y.error}`:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output??""),B=Y;Z.push({role:"tool",content:V,tool_call_id:Y.toolCallId,name:Y.toolName,metadata:B})}if(X.data.partType==="summary"){let Y=X.data.payload,V=X.data.payload;Z.push({role:"system",content:Y.text??"",metadata:V})}if(X.data.partType==="subtask_ref"){let Y=J.get(X.data.messageId);if(Y){let V=X.data.payload,B=Y.metadata??{};Y.metadata={...B,subtaskRef:V}}}}}return Z}static getSessionFilePath($,Z){return W$($,Z)}}function Q2($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}var WJ={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){let J=I(Z),W=A().restoreSession;if($.length>0){let X=$[0];try{let Y=await o0.loadSession(X);if(Y.length===0)return J.sendMessage(`[FAIL] 会话 \`${X}\` 为空或无法加载`),{success:!1,error:"会话为空"};let V=o0.toUISafeMessages(Y);return W(X,V,Y),J.sendMessage(`[OK] 已恢复会话 \`${X}\`
1735
1735
 
1736
- 共 ${V.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:X,messageCount:V.length}}}catch(Y){let V=Y instanceof Error?Y.message:"未知错误";return J.sendMessage(`[FAIL] 加载会话失败: ${V}`),{success:!1,error:`加载会话失败: ${V}`}}}try{let X=await o0.listSessions();if(X.length===0)return J.sendMessage("**没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:X}}}catch(X){let Y=X instanceof Error?X.message:"未知错误";return J.sendMessage(`获取会话列表失败: ${Y}`),{success:!1,error:`获取会话列表失败: ${Y}`}}}},U2=ZJ;import{promises as o1}from"node:fs";import q2 from"node:path";async function JJ($){let Z=q2.join(b$(),"file-history",$),J=[];try{let W=await o1.readdir(Z);for(let X of W){let Y=X.match(/^(.+)@v(\d+)$/);if(!Y)continue;let V=q2.join(Z,X),B=await o1.stat(V);J.push({filePath:Y[1],version:parseInt(Y[2],10),snapshotPath:V,mtime:B.mtime})}}catch{}return J.sort((W,X)=>X.mtime.getTime()-W.mtime.getTime())}var WJ={name:"rewind",description:"Revert files to their state before the last edit",fullDescription:"回退文件到编辑前的快照状态。不带参数列出可回退的文件,带文件路径则执行回退。",usage:"/rewind [file_path]",aliases:["undo"],async handler($,Z){let J=I(Z),X=i().session?.sessionId;if(!X)return J.sendMessage("无活跃会话,无法查找快照。"),{success:!1,message:"No active session"};let Y=await JJ(X);if(Y.length===0)return J.sendMessage("当前会话没有可回退的文件快照。"),{success:!0,message:"No snapshots available"};if($.length===0){let Q=new Map;for(let q of Y)if(!Q.has(q.filePath))Q.set(q.filePath,{version:q.version,mtime:q.mtime});let U=`**可回退的文件快照:**
1736
+ 共 ${V.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:X,messageCount:V.length}}}catch(Y){let V=Y instanceof Error?Y.message:"未知错误";return J.sendMessage(`[FAIL] 加载会话失败: ${V}`),{success:!1,error:`加载会话失败: ${V}`}}}try{let X=await o0.listSessions();if(X.length===0)return J.sendMessage("**没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:X}}}catch(X){let Y=X instanceof Error?X.message:"未知错误";return J.sendMessage(`获取会话列表失败: ${Y}`),{success:!1,error:`获取会话列表失败: ${Y}`}}}},U2=WJ;import{promises as o1}from"node:fs";import q2 from"node:path";async function XJ($){let Z=q2.join(T$(),"file-history",$),J=[];try{let W=await o1.readdir(Z);for(let X of W){let Y=X.match(/^(.+)@v(\d+)$/);if(!Y)continue;let V=q2.join(Z,X),B=await o1.stat(V);J.push({filePath:Y[1],version:parseInt(Y[2],10),snapshotPath:V,mtime:B.mtime})}}catch{}return J.sort((W,X)=>X.mtime.getTime()-W.mtime.getTime())}var YJ={name:"rewind",description:"Revert files to their state before the last edit",fullDescription:"回退文件到编辑前的快照状态。不带参数列出可回退的文件,带文件路径则执行回退。",usage:"/rewind [file_path]",aliases:["undo"],async handler($,Z){let J=I(Z),X=i().session?.sessionId;if(!X)return J.sendMessage("无活跃会话,无法查找快照。"),{success:!1,message:"No active session"};let Y=await XJ(X);if(Y.length===0)return J.sendMessage("当前会话没有可回退的文件快照。"),{success:!0,message:"No snapshots available"};if($.length===0){let Q=new Map;for(let q of Y)if(!Q.has(q.filePath))Q.set(q.filePath,{version:q.version,mtime:q.mtime});let U=`**可回退的文件快照:**
1737
1737
 
1738
1738
  `;for(let[q,H]of Q)U+=`- \`${q}\` (v${H.version}, ${H.mtime.toLocaleTimeString()})
1739
- `;return U+="\n使用 `/rewind <file_path>` 回退指定文件。",J.sendMessage(U),{success:!0,message:`${Q.size} snapshots available`}}let V=$[0],B=Y.filter((Q)=>{return Q.filePath===V||V.endsWith(Q.filePath)||Q.filePath.endsWith(V)});if(B.length===0)return J.sendMessage(`未找到文件 "${V}" 的快照。`),{success:!1,message:"Snapshot not found"};let K=B[0];try{let Q=await o1.readFile(K.snapshotPath,"utf-8");return await o1.writeFile(V,Q,"utf-8"),J.sendMessage(`已回退 \`${V}\` 到 v${K.version} (${K.mtime.toLocaleTimeString()})`),{success:!0,message:`Reverted ${V}`}}catch(Q){return J.sendMessage(`回退失败: ${Q.message}`),{success:!1,error:Q.message}}}},H2=WJ;var XJ={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=I(Z),W=`**可用的 Slash Commands:**
1739
+ `;return U+="\n使用 `/rewind <file_path>` 回退指定文件。",J.sendMessage(U),{success:!0,message:`${Q.size} snapshots available`}}let V=$[0],B=Y.filter((Q)=>{return Q.filePath===V||V.endsWith(Q.filePath)||Q.filePath.endsWith(V)});if(B.length===0)return J.sendMessage(`未找到文件 "${V}" 的快照。`),{success:!1,message:"Snapshot not found"};let K=B[0];try{let Q=await o1.readFile(K.snapshotPath,"utf-8");return await o1.writeFile(V,Q,"utf-8"),J.sendMessage(`已回退 \`${V}\` 到 v${K.version} (${K.mtime.toLocaleTimeString()})`),{success:!0,message:`Reverted ${V}`}}catch(Q){return J.sendMessage(`回退失败: ${Q.message}`),{success:!1,error:Q.message}}}},H2=YJ;var VJ={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=I(Z),W=`**可用的 Slash Commands:**
1740
1740
 
1741
1741
  **/init** - 分析当前项目并生成 BLADE.md 配置文件
1742
1742
  **/git** - Git 仓库查询和 AI 辅助 (status/log/diff/review/commit)
@@ -1766,7 +1766,7 @@ ${B}
1766
1766
  - 在命令前加上 \`/\` 即可执行 slash command
1767
1767
  - 普通消息会发送给 AI 助手处理
1768
1768
  - 按 Ctrl+C 退出程序
1769
- - 按 Ctrl+L 快速清屏`,J.sendMessage(W),{success:!0,message:"帮助信息已显示",content:W}}},YJ={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},VJ={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let J=I(Z),X=`**Blade Code v${M1()}**
1769
+ - 按 Ctrl+L 快速清屏`,J.sendMessage(W),{success:!0,message:"帮助信息已显示",content:W}}},BJ={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},KJ={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let J=I(Z),X=`**Blade Code v${M1()}**
1770
1770
 
1771
1771
  **构建信息:**
1772
1772
  - Node.js: ${process.version}
@@ -1777,7 +1777,7 @@ ${B}
1777
1777
  - 智能 AI 对话
1778
1778
  - 项目自动分析
1779
1779
  - 自定义系统提示
1780
- - 多工具集成支持`;return J.sendMessage(X),{success:!0,message:"版本信息已显示"}}},BJ={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=I(Z),{cwd:W}=Z;try{let X=F2.join(W,"BLADE.md"),Y=await G2.access(X).then(()=>!0).catch(()=>!1),V=F2.join(W,"package.json"),B="未知项目",K="未知类型";try{let O=await G2.readFile(V,"utf-8"),F=JSON.parse(O);B=F.name||"未知项目";let z={...F.dependencies,...F.devDependencies};if(z.react)K="React 项目";else if(z.vue)K="Vue 项目";else if(z.next)K="Next.js 项目";else if(z.express)K="Express 项目";else K="Node.js 项目"}catch{}let Q=t(),U=j$(),H=i().session.tokenUsage,G=`**当前状态**
1780
+ - 多工具集成支持`;return J.sendMessage(X),{success:!0,message:"版本信息已显示"}}},QJ={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=I(Z),{cwd:W}=Z;try{let X=F2.join(W,"BLADE.md"),Y=await G2.access(X).then(()=>!0).catch(()=>!1),V=F2.join(W,"package.json"),B="未知项目",K="未知类型";try{let O=await G2.readFile(V,"utf-8"),F=JSON.parse(O);B=F.name||"未知项目";let z={...F.dependencies,...F.devDependencies};if(z.react)K="React 项目";else if(z.vue)K="Vue 项目";else if(z.next)K="Next.js 项目";else if(z.express)K="Express 项目";else K="Node.js 项目"}catch{}let Q=t(),U=N$(),H=i().session.tokenUsage,G=`**当前状态**
1781
1781
 
1782
1782
  **项目信息:**
1783
1783
  - 名称: ${B}
@@ -1802,7 +1802,7 @@ ${B}
1802
1802
  - 工作目录: ${N()} (process.cwd: ${process.cwd()})
1803
1803
  - Node.js: ${process.version}
1804
1804
 
1805
- ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(G),{success:!0,message:"状态信息已显示"}}catch(X){return{success:!1,error:`获取状态信息失败: ${X instanceof Error?X.message:"未知错误"}`}}}},KJ={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},QJ={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=I(Z),W=t(),X=j$(),V=i().session.messages||[],B=V.map((z)=>({role:z.role,content:z.content})),K=X?.model||"gpt-4",Q=B.length>0?n1.countTokens(B,K):0,U=X?.maxContextTokens??W?.maxContextTokens??128000,q=U>0?(Q/U*100).toFixed(1):"0",H=(100-parseFloat(q)).toFixed(1),G=parseFloat(q),O;if(G<50)O="[OK] 正常";else if(G<80)O="[WARN] 中等";else O="[CRITICAL] 高负载";let F=`**上下文使用情况**
1805
+ ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(G),{success:!0,message:"状态信息已显示"}}catch(X){return{success:!1,error:`获取状态信息失败: ${X instanceof Error?X.message:"未知错误"}`}}}},UJ={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},qJ={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=I(Z),W=t(),X=N$(),V=i().session.messages||[],B=V.map((z)=>({role:z.role,content:z.content})),K=X?.model||"gpt-4",Q=B.length>0?n1.countTokens(B,K):0,U=X?.maxContextTokens??W?.maxContextTokens??128000,q=U>0?(Q/U*100).toFixed(1):"0",H=(100-parseFloat(q)).toFixed(1),G=parseFloat(q),O;if(G<50)O="[OK] 正常";else if(G<80)O="[WARN] 中等";else O="[CRITICAL] 高负载";let F=`**上下文使用情况**
1806
1806
 
1807
1807
  **当前会话:**
1808
1808
  - 消息数量: ${V.length}
@@ -1816,7 +1816,7 @@ ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
1816
1816
 
1817
1817
  **状态:** ${O}
1818
1818
 
1819
- 使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(F),{success:!0,message:"上下文信息已显示"}}},UJ={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,Z){let J=I(Z),X=i().session.tokenUsage,Y=j$(),V=X.estimatedCostUsd>0?`$${X.estimatedCostUsd<0.01?X.estimatedCostUsd.toFixed(6):X.estimatedCostUsd.toFixed(4)}`:"N/A (unknown model pricing)",B=X.cacheReadTokens>0||X.cacheWriteTokens>0?`
1819
+ 使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(F),{success:!0,message:"上下文信息已显示"}}},HJ={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,Z){let J=I(Z),X=i().session.tokenUsage,Y=N$(),V=X.estimatedCostUsd>0?`$${X.estimatedCostUsd<0.01?X.estimatedCostUsd.toFixed(6):X.estimatedCostUsd.toFixed(4)}`:"N/A (unknown model pricing)",B=X.cacheReadTokens>0||X.cacheWriteTokens>0?`
1820
1820
  - Cache read: ${X.cacheReadTokens.toLocaleString()} tokens
1821
1821
  - Cache write: ${X.cacheWriteTokens.toLocaleString()} tokens`:"",K=`**Session Cost Summary**
1822
1822
 
@@ -1827,10 +1827,10 @@ ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
1827
1827
  - **Total input: ${X.totalInputTokens.toLocaleString()} tokens**
1828
1828
  - **Total output: ${X.totalOutputTokens.toLocaleString()} tokens**${B}
1829
1829
  - Context remaining: ${X.maxContextTokens>0?Math.round((1-X.inputTokens/X.maxContextTokens)*100):"?"}%
1830
- - **Estimated cost: ${V}**`;return J.sendMessage(K),{success:!0,message:"Cost summary displayed"}}},qJ={name:"doctor",description:"Diagnose API connectivity and configuration health",fullDescription:"诊断 API 连通性和配置健康状况",usage:"/doctor",aliases:[],async handler($,Z){let J=I(Z),X=t()?.models??[];if(X.length===0)return J.sendMessage("❌ 没有配置任何模型。请先运行 `/init` 或编辑 `~/.blade/config.json`"),{success:!1,message:"No models configured"};let Y=[`**API Connectivity Diagnosis**
1830
+ - **Estimated cost: ${V}**`;return J.sendMessage(K),{success:!0,message:"Cost summary displayed"}}},GJ={name:"doctor",description:"Diagnose API connectivity and configuration health",fullDescription:"诊断 API 连通性和配置健康状况",usage:"/doctor",aliases:[],async handler($,Z){let J=I(Z),X=t()?.models??[];if(X.length===0)return J.sendMessage("❌ 没有配置任何模型。请先运行 `/init` 或编辑 `~/.blade/config.json`"),{success:!1,message:"No models configured"};let Y=[`**API Connectivity Diagnosis**
1831
1831
  `];for(let V of X){let B=Date.now();try{let{createChatServiceAsync:K}=await import("./chunk-zh3ndtvg.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()-B,H=!!U.content;Y.push(`✅ **${V.name}** (${V.model}) — ${q}ms${H?"":" ⚠️ empty response"}`)}catch(K){let Q=Date.now()-B,U=K instanceof Error?K.message.slice(0,80):"Unknown error";Y.push(`❌ **${V.name}** (${V.model}) — ${Q}ms — ${U}`)}}return J.sendMessage(Y.join(`
1832
- `)),{success:!0,message:"Doctor diagnosis complete"}}},O2={help:XJ,clear:YJ,version:VJ,status:BJ,exit:KJ,context:QJ,cost:UJ,doctor:qJ,permissions:r1,resume:U2,rewind:H2,compact:Z2,mcp:X2,memory:V2,agents:e9};import{execFile as z2,spawn as HJ}from"child_process";import{promisify as GJ}from"util";var BO=GJ(z2);async function t0($,Z){return new Promise((J)=>{z2("git",Z,{cwd:$,maxBuffer:10485760,encoding:"utf8"},(W,X,Y)=>{let V=W==null?0:typeof W.code==="number"?W.code:1;J({code:V,stdout:X||"",stderr:Y||""})})})}async function FJ($,Z){let{code:J}=await t0($,Z);return J===0}async function R$($,Z){let{stdout:J}=await t0($,Z);return J.trim()}async function I8($){return FJ($,["rev-parse","--is-inside-work-tree"])}async function t1($){return(await R$($,["status","--porcelain"])).length>0}async function KO($){return R$($,["branch","--show-current"])}async function e1($,Z=10){return R$($,["log","-n",String(Z),"--pretty=format:%s"])}async function S8($){let{code:Z,stderr:J}=await t0($,["add","."]);if(Z!==0){let W=J||"Unknown error";if(W.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${W}`)}}async function w2($,Z,J=!1,W){let X=["commit","-m",Z];if(J)X.push("--no-verify");if(!W){let{code:Y,stderr:V}=await t0($,X);if(Y!==0)throw Error(V||"Commit failed");return}return new Promise((Y,V)=>{let B=HJ("git",X,{cwd:$}),K="",Q=(H,G,O)=>{let z=(O+H.toString()).split(`
1833
- `),w=z.pop()||"";for(let L of z)if(L.trim())W(L,G);return w},U="",q="";B.stdout?.on("data",(H)=>{U=Q(H,"stdout",U)}),B.stderr?.on("data",(H)=>{K+=H.toString(),q=Q(H,"stderr",q)}),B.on("error",(H)=>{V(H)}),B.on("close",(H)=>{if(U.trim())W(U,"stdout");if(q.trim())W(q,"stderr");if(H===0)Y();else V(Error(K||"Commit failed"))})})}async function j2($){let{cwd:Z}=$;if(!await I8(Z))return null;let[J,W,X,Y,V]=await Promise.all([R$(Z,["branch","--show-current"]),R$(Z,["rev-parse","--abbrev-ref","origin/HEAD"]).then((K)=>K.replace("origin/","")).catch(()=>"main"),R$(Z,["status","--short"]),R$(Z,["log","--oneline","-n","5"]),R$(Z,["config","user.email"])]),B=V?await R$(Z,["log","--author",V,"--oneline","-n","5"]):"";return{branch:J,mainBranch:W,status:X,log:Y,author:V,authorLog:B}}function N2($){if(!$)return null;return`
1832
+ `)),{success:!0,message:"Doctor diagnosis complete"}}},O2={help:VJ,clear:BJ,version:KJ,status:QJ,exit:UJ,context:qJ,cost:HJ,doctor:GJ,permissions:r1,resume:U2,rewind:H2,compact:Z2,mcp:X2,memory:V2,agents:e9};import{execFile as z2,spawn as FJ}from"child_process";import{promisify as OJ}from"util";var UO=OJ(z2);async function t0($,Z){return new Promise((J)=>{z2("git",Z,{cwd:$,maxBuffer:10485760,encoding:"utf8"},(W,X,Y)=>{let V=W==null?0:typeof W.code==="number"?W.code:1;J({code:V,stdout:X||"",stderr:Y||""})})})}async function zJ($,Z){let{code:J}=await t0($,Z);return J===0}async function k$($,Z){let{stdout:J}=await t0($,Z);return J.trim()}async function I8($){return zJ($,["rev-parse","--is-inside-work-tree"])}async function t1($){return(await k$($,["status","--porcelain"])).length>0}async function qO($){return k$($,["branch","--show-current"])}async function e1($,Z=10){return k$($,["log","-n",String(Z),"--pretty=format:%s"])}async function S8($){let{code:Z,stderr:J}=await t0($,["add","."]);if(Z!==0){let W=J||"Unknown error";if(W.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${W}`)}}async function w2($,Z,J=!1,W){let X=["commit","-m",Z];if(J)X.push("--no-verify");if(!W){let{code:Y,stderr:V}=await t0($,X);if(Y!==0)throw Error(V||"Commit failed");return}return new Promise((Y,V)=>{let B=FJ("git",X,{cwd:$}),K="",Q=(H,G,O)=>{let z=(O+H.toString()).split(`
1833
+ `),w=z.pop()||"";for(let L of z)if(L.trim())W(L,G);return w},U="",q="";B.stdout?.on("data",(H)=>{U=Q(H,"stdout",U)}),B.stderr?.on("data",(H)=>{K+=H.toString(),q=Q(H,"stderr",q)}),B.on("error",(H)=>{V(H)}),B.on("close",(H)=>{if(U.trim())W(U,"stdout");if(q.trim())W(q,"stderr");if(H===0)Y();else V(Error(K||"Commit failed"))})})}async function j2($){let{cwd:Z}=$;if(!await I8(Z))return null;let[J,W,X,Y,V]=await Promise.all([k$(Z,["branch","--show-current"]),k$(Z,["rev-parse","--abbrev-ref","origin/HEAD"]).then((K)=>K.replace("origin/","")).catch(()=>"main"),k$(Z,["status","--short"]),k$(Z,["log","--oneline","-n","5"]),k$(Z,["config","user.email"])]),B=V?await k$(Z,["log","--author",V,"--oneline","-n","5"]):"";return{branch:J,mainBranch:W,status:X,log:Y,author:V,authorLog:B}}function N2($){if(!$)return null;return`
1834
1834
  Git repository status (snapshot at conversation start):
1835
1835
  Current branch: ${$.branch}
1836
1836
  Main branch (target for PRs): ${$.mainBranch}
@@ -1843,14 +1843,14 @@ ${$.log||"(no commits)"}
1843
1843
 
1844
1844
  Your recent commits:
1845
1845
  ${$.authorLog||"(no recent commits)"}
1846
- `.trim()}async function e0($){return R$($,["diff","--cached","--name-status"])}async function $1($){let J=["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:W,stdout:X,stderr:Y}=await t0($,J);if(W!==0){let B=Y||"Unknown error";if(B.includes("bad revision"))throw Error("Failed to get staged diff: Invalid Git revision or corrupt repository");if(B.includes("fatal: not a git repository"))throw Error("Not a Git repository");throw Error(`Failed to get staged diff: ${B}`)}let V=102400;if(X.length>V)return X.substring(0,V)+`
1846
+ `.trim()}async function e0($){return k$($,["diff","--cached","--name-status"])}async function $1($){let J=["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:W,stdout:X,stderr:Y}=await t0($,J);if(W!==0){let B=Y||"Unknown error";if(B.includes("bad revision"))throw Error("Failed to get staged diff: Invalid Git revision or corrupt repository");if(B.includes("fatal: not a git repository"))throw Error("Not a Git repository");throw Error(`Failed to get staged diff: ${B}`)}let V=102400;if(X.length>V)return X.substring(0,V)+`
1847
1847
 
1848
- [Diff truncated due to size. Total diff size: `+(X.length/1024).toFixed(2)+"KB]";return X}var OJ={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($,Z){let{cwd:J}=Z,W=$[0]?.toLowerCase();if(!await I8(J))return{success:!1,error:"当前目录不在 Git 仓库中"};try{switch(W){case"status":case"s":return D2(Z);case"log":case"l":return zJ(Z,$[1]);case"diff":case"d":return wJ(Z);case"review":case"r":return jJ(Z);case"commit":case"c":return DJ(Z);case"pre-commit":case"pc":return NJ(Z);default:return D2(Z)}}catch(X){return{success:!1,error:`Git 命令失败: ${X instanceof Error?X.message:"未知错误"}`}}}};async function D2($){let Z=I($),J=await j2({cwd:$.cwd});if(!J)return{success:!1,error:"无法获取 Git 状态"};let W=N2(J);if(W)Z.sendMessage(`\`\`\`
1848
+ [Diff truncated due to size. Total diff size: `+(X.length/1024).toFixed(2)+"KB]";return X}var wJ={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($,Z){let{cwd:J}=Z,W=$[0]?.toLowerCase();if(!await I8(J))return{success:!1,error:"当前目录不在 Git 仓库中"};try{switch(W){case"status":case"s":return D2(Z);case"log":case"l":return jJ(Z,$[1]);case"diff":case"d":return NJ(Z);case"review":case"r":return DJ(Z);case"commit":case"c":return EJ(Z);case"pre-commit":case"pc":return LJ(Z);default:return D2(Z)}}catch(X){return{success:!1,error:`Git 命令失败: ${X instanceof Error?X.message:"未知错误"}`}}}};async function D2($){let Z=I($),J=await j2({cwd:$.cwd});if(!J)return{success:!1,error:"无法获取 Git 状态"};let W=N2(J);if(W)Z.sendMessage(`\`\`\`
1849
1849
  ${W}
1850
- \`\`\``);else Z.sendMessage("无法获取 Git 状态信息");return{success:!0}}async function zJ($,Z){let J=I($),W=Math.min(Math.max(parseInt(Z||"5",10)||5,1),50),X=await e1($.cwd,W);if(!X)J.sendMessage("暂无提交记录");else J.sendMessage(`**最近 ${W} 条提交:**
1850
+ \`\`\``);else Z.sendMessage("无法获取 Git 状态信息");return{success:!0}}async function jJ($,Z){let J=I($),W=Math.min(Math.max(parseInt(Z||"5",10)||5,1),50),X=await e1($.cwd,W);if(!X)J.sendMessage("暂无提交记录");else J.sendMessage(`**最近 ${W} 条提交:**
1851
1851
  \`\`\`
1852
1852
  ${X}
1853
- \`\`\``);return{success:!0}}async function wJ($){let Z=I($),{cwd:J}=$,W=await e0(J);if(!W)return Z.sendMessage("暂存区为空,没有待提交的改动"),{success:!0};let X=await $1(J),Y=`**暂存文件:**
1853
+ \`\`\``);return{success:!0}}async function NJ($){let Z=I($),{cwd:J}=$,W=await e0(J);if(!W)return Z.sendMessage("暂存区为空,没有待提交的改动"),{success:!0};let X=await $1(J),Y=`**暂存文件:**
1854
1854
  \`\`\`
1855
1855
  ${W}
1856
1856
  \`\`\`
@@ -1858,7 +1858,7 @@ ${W}
1858
1858
  **Diff:**
1859
1859
  \`\`\`diff
1860
1860
  ${X||"(无差异)"}
1861
- \`\`\``;return Z.sendMessage(Y),{success:!0}}async function jJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动,无需 Review"),{success:!0};Z.sendMessage("正在分析代码改动...");let X=await e0(J),Y=await $1(J);if(!Y&&!X)return Z.sendMessage("请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let V=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let B=i().session.sessionId,K=`请对以下 Git 改动进行 Code Review。
1861
+ \`\`\``;return Z.sendMessage(Y),{success:!0}}async function DJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动,无需 Review"),{success:!0};Z.sendMessage("正在分析代码改动...");let X=await e0(J),Y=await $1(J);if(!Y&&!X)return Z.sendMessage("请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let V=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let B=i().session.sessionId,K=`请对以下 Git 改动进行 Code Review。
1862
1862
 
1863
1863
  **暂存文件:**
1864
1864
  ${X||"(无)"}
@@ -1874,7 +1874,7 @@ ${Y||"(无差异)"}
1874
1874
  3. **潜在问题**:指出可能的 bug、安全问题或性能问题
1875
1875
  4. **改进建议**:具体的代码改进建议
1876
1876
 
1877
- 如果改动很好,也请说明优点。保持简洁专业。`,U=(await N$(V.chatStream(K,{messages:[],userId:"cli-user",sessionId:B||"git-review",workspaceRoot:J,signal:W}))).finalMessage||"";return Z.sendMessage(U),{success:!0}}async function NJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await e0(J),Y=await $1(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await e1(J,5),B=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=i().session.sessionId,Q=L2(X,Y,V),H=((await N$(B.chatStream(Q,{messages:[],userId:"cli-user",sessionId:K||"git-pre-commit",workspaceRoot:J,signal:W}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return Z.sendMessage(`**生成的 Commit Message:**
1877
+ 如果改动很好,也请说明优点。保持简洁专业。`,U=(await D$(V.chatStream(K,{messages:[],userId:"cli-user",sessionId:B||"git-review",workspaceRoot:J,signal:W}))).finalMessage||"";return Z.sendMessage(U),{success:!0}}async function LJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await e0(J),Y=await $1(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await e1(J,5),B=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=i().session.sessionId,Q=L2(X,Y,V),H=((await D$(B.chatStream(Q,{messages:[],userId:"cli-user",sessionId:K||"git-pre-commit",workspaceRoot:J,signal:W}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();return Z.sendMessage(`**生成的 Commit Message:**
1878
1878
  \`\`\`
1879
1879
  ${H}
1880
1880
  \`\`\`
@@ -1883,7 +1883,7 @@ ${H}
1883
1883
  \`\`\`bash
1884
1884
  git commit -m "${H.split(`
1885
1885
  `)[0]}"
1886
- \`\`\``),{success:!0}}async function DJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await e0(J),Y=await $1(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await e1(J,5),B=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=i().session.sessionId,Q=L2(X,Y,V),H=((await N$(B.chatStream(Q,{messages:[],userId:"cli-user",sessionId:K||"git-commit",workspaceRoot:J,signal:W}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();Z.sendMessage(`**生成的 Commit Message:**
1886
+ \`\`\``),{success:!0}}async function EJ($){let Z=I($),{cwd:J,signal:W}=$;if(!await t1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await e0(J),Y=await $1(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await e1(J,5),B=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=i().session.sessionId,Q=L2(X,Y,V),H=((await D$(B.chatStream(Q,{messages:[],userId:"cli-user",sessionId:K||"git-commit",workspaceRoot:J,signal:W}))).finalMessage||"").replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();Z.sendMessage(`**生成的 Commit Message:**
1887
1887
  \`\`\`
1888
1888
  ${H}
1889
1889
  \`\`\``);try{await w2(J,H),Z.sendMessage("[OK] 提交成功!")}catch(G){let O=G instanceof Error?G.message:"未知错误";return Z.sendMessage(`[FAIL] 提交失败: ${O}`),{success:!1,error:O}}return{success:!0}}function L2($,Z,J){let W=J&&J.trim().length>0;return`请根据以下 Git 改动生成一条 commit message。
@@ -1907,7 +1907,7 @@ ${J}
1907
1907
  1. ${W?"严格模仿历史提交的语言和格式风格":"使用英文,遵循 Conventional Commits 格式(feat:, fix:, docs:, refactor:, chore: 等)"}
1908
1908
  2. 第一行简明扼要,不超过 72 字符
1909
1909
  3. 如有必要,可添加空行后的详细说明
1910
- 4. 只输出 commit message 内容,不要其他解释或代码块标记`}var E2=OJ;var LJ={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
1910
+ 4. 只输出 commit message 内容,不要其他解释或代码块标记`}var E2=wJ;var _J={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
1911
1911
 
1912
1912
  子命令:
1913
1913
  /hooks - 打开交互式 hooks 管理界面(添加新 hook)
@@ -1915,16 +1915,16 @@ ${J}
1915
1915
  /hooks status - 显示 hooks 启用状态和统计
1916
1916
  /hooks enable - 启用当前会话的 hooks
1917
1917
  /hooks disable - 禁用当前会话的 hooks
1918
- /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($,Z)=>{let J=$[0]?.toLowerCase()||"",W=X$.getInstance();switch(J){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return EJ(W);case"enable":return W.enable(),A().addAssistantMessage("[OK] Hooks 已启用(当前会话)"),{success:!0,message:"Hooks enabled"};case"disable":return W.disable(),A().addAssistantMessage("Hooks 已禁用(当前会话)"),{success:!0,message:"Hooks disabled"};case"list":return _J(W);default:return A().addAssistantMessage(`未知子命令: ${J}
1919
- 使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function EJ($){let Z=$.isEnabled(),J=$.getConfig(),W={};for(let Y of Object.values(P8)){let V=J[Y];if(V&&Array.isArray(V)){let B=V.reduce((K,Q)=>K+(Q.hooks?.length||0),0);if(B>0)W[Y]=B}}let X=["## Hooks 状态","",`**状态**: ${Z?"[OK] 启用":"禁用"}`,""];if(Object.keys(W).length>0){X.push("**已配置的 Hooks**:"),X.push("");for(let[Y,V]of Object.entries(W))X.push(`- ${Y}: ${V} 个 hook`)}else X.push("*没有配置任何 hooks*");return X.push(""),X.push("---"),X.push("使用 `/hooks list` 查看详细配置"),X.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),A().addAssistantMessage(X.join(`
1920
- `)),{success:!0,message:"Hooks status displayed"}}function _J($){let Z=$.getConfig(),J=["## Hooks 配置详情",""],W=!1;for(let X of Object.values(P8)){let Y=Z[X];if(!Y||!Array.isArray(Y)||Y.length===0)continue;W=!0,J.push(`### ${X}`),J.push("");for(let V=0;V<Y.length;V++){let B=Y[V],K=B.name||`Matcher ${V+1}`,Q=B.matcher,U="所有";if(Q){let q=[];if(Q.tools){let H=Array.isArray(Q.tools)?Q.tools.join(", "):Q.tools;q.push(`工具: ${H}`)}if(Q.paths){let H=Array.isArray(Q.paths)?Q.paths.join(", "):Q.paths;q.push(`路径: ${H}`)}if(Q.commands){let H=Array.isArray(Q.commands)?Q.commands.join(", "):Q.commands;q.push(`命令: ${H}`)}if(q.length>0)U=q.join("; ")}J.push(`**${K}** (匹配: ${U})`);for(let q of B.hooks||[])if(q.type==="command")J.push(` - \`${q.command}\``);else if(q.type==="prompt"){let H=q.prompt.slice(0,50)+(q.prompt.length>50?"...":"");J.push(` - [prompt] ${H}`)}J.push("")}}if(!W)J.push("*没有配置任何 hooks*"),J.push(""),J.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return A().addAssistantMessage(J.join(`
1921
- `)),{success:!0,message:"Hooks config listed"}}var _2=LJ;import{existsSync as TJ,readFileSync as MJ}from"fs";import{homedir as vJ}from"os";import{join as CJ}from"path";import{exec as AJ}from"child_process";import{promisify as RJ}from"util";var A2=RJ(AJ);class y8{static async detectIde(){let $=process.env.TERM_PROGRAM,Z=process.env.VSCODE_INJECTION,J=process.env.VSCODE_IPC_HOOK;if($==="vscode"||Z||J)return await this.detectVsCode();let W=await this.detectVsCode();if(W)return W;return null}static async detectVsCode(){try{let{stdout:$}=await A2("code --version"),J=$.trim().split(`
1918
+ /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($,Z)=>{let J=$[0]?.toLowerCase()||"",W=X$.getInstance();switch(J){case"":case"add":return{success:!0,message:"show_hooks_manager",data:{action:"show_hooks_manager"}};case"status":return AJ(W);case"enable":return W.enable(),A().addAssistantMessage("[OK] Hooks 已启用(当前会话)"),{success:!0,message:"Hooks enabled"};case"disable":return W.disable(),A().addAssistantMessage("Hooks 已禁用(当前会话)"),{success:!0,message:"Hooks disabled"};case"list":return RJ(W);default:return A().addAssistantMessage(`未知子命令: ${J}
1919
+ 使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function AJ($){let Z=$.isEnabled(),J=$.getConfig(),W={};for(let Y of Object.values(P8)){let V=J[Y];if(V&&Array.isArray(V)){let B=V.reduce((K,Q)=>K+(Q.hooks?.length||0),0);if(B>0)W[Y]=B}}let X=["## Hooks 状态","",`**状态**: ${Z?"[OK] 启用":"禁用"}`,""];if(Object.keys(W).length>0){X.push("**已配置的 Hooks**:"),X.push("");for(let[Y,V]of Object.entries(W))X.push(`- ${Y}: ${V} 个 hook`)}else X.push("*没有配置任何 hooks*");return X.push(""),X.push("---"),X.push("使用 `/hooks list` 查看详细配置"),X.push("使用 `/hooks enable` 或 `/hooks disable` 切换状态"),A().addAssistantMessage(X.join(`
1920
+ `)),{success:!0,message:"Hooks status displayed"}}function RJ($){let Z=$.getConfig(),J=["## Hooks 配置详情",""],W=!1;for(let X of Object.values(P8)){let Y=Z[X];if(!Y||!Array.isArray(Y)||Y.length===0)continue;W=!0,J.push(`### ${X}`),J.push("");for(let V=0;V<Y.length;V++){let B=Y[V],K=B.name||`Matcher ${V+1}`,Q=B.matcher,U="所有";if(Q){let q=[];if(Q.tools){let H=Array.isArray(Q.tools)?Q.tools.join(", "):Q.tools;q.push(`工具: ${H}`)}if(Q.paths){let H=Array.isArray(Q.paths)?Q.paths.join(", "):Q.paths;q.push(`路径: ${H}`)}if(Q.commands){let H=Array.isArray(Q.commands)?Q.commands.join(", "):Q.commands;q.push(`命令: ${H}`)}if(q.length>0)U=q.join("; ")}J.push(`**${K}** (匹配: ${U})`);for(let q of B.hooks||[])if(q.type==="command")J.push(` - \`${q.command}\``);else if(q.type==="prompt"){let H=q.prompt.slice(0,50)+(q.prompt.length>50?"...":"");J.push(` - [prompt] ${H}`)}J.push("")}}if(!W)J.push("*没有配置任何 hooks*"),J.push(""),J.push("在 `.blade/settings.local.json` 或 `~/.blade/settings.json` 中配置 hooks。");return A().addAssistantMessage(J.join(`
1921
+ `)),{success:!0,message:"Hooks config listed"}}var _2=_J;import{existsSync as vJ,readFileSync as CJ}from"fs";import{homedir as IJ}from"os";import{join as SJ}from"path";import{exec as kJ}from"child_process";import{promisify as bJ}from"util";var A2=bJ(kJ);class y8{static async detectIde(){let $=process.env.TERM_PROGRAM,Z=process.env.VSCODE_INJECTION,J=process.env.VSCODE_IPC_HOOK;if($==="vscode"||Z||J)return await this.detectVsCode();let W=await this.detectVsCode();if(W)return W;return null}static async detectVsCode(){try{let{stdout:$}=await A2("code --version"),J=$.trim().split(`
1922
1922
  `)[0]||"unknown",W=[];try{let{stdout:X}=await A2("code --list-extensions");W=X.trim().split(`
1923
- `).filter(Boolean)}catch{}return{name:"VS Code",version:J,extensions:W}}catch{return null}}static isRunningInIdeTerminal(){let $=process.env.TERM_PROGRAM,Z=process.env.VSCODE_INJECTION,J=process.env.VSCODE_IPC_HOOK;return $==="vscode"||!!Z||!!J}}import{exec as kJ}from"child_process";import{promisify as bJ}from"util";var $5=bJ(kJ);class Z1{static async getInstalledIdes(){let $=[],Z=await this.checkVsCode();if(Z)$.push(Z);let J=await this.checkVsCodeInsiders();if(J)$.push(J);let W=await this.checkCursor();if(W)$.push(W);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 Z;switch($){case"vscode":Z="code --install-extension blade-code.blade-code";break;case"vscode-insiders":Z="code-insiders --install-extension blade-code.blade-code";break;case"cursor":Z="cursor --install-extension blade-code.blade-code";break;default:return{success:!1,message:"不支持的 IDE: "+$}}try{return await $5(Z),{success:!0,message:"扩展安装成功"}}catch(J){return{success:!1,message:"安装失败: "+(J instanceof Error?J.message:"未知错误")}}}static async checkVsCode(){try{let{stdout:$}=await $5("code --version");return{id:"vscode",name:"VS Code",version:$.trim().split(`
1923
+ `).filter(Boolean)}catch{}return{name:"VS Code",version:J,extensions:W}}catch{return null}}static isRunningInIdeTerminal(){let $=process.env.TERM_PROGRAM,Z=process.env.VSCODE_INJECTION,J=process.env.VSCODE_IPC_HOOK;return $==="vscode"||!!Z||!!J}}import{exec as TJ}from"child_process";import{promisify as MJ}from"util";var $5=MJ(TJ);class Z1{static async getInstalledIdes(){let $=[],Z=await this.checkVsCode();if(Z)$.push(Z);let J=await this.checkVsCodeInsiders();if(J)$.push(J);let W=await this.checkCursor();if(W)$.push(W);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 Z;switch($){case"vscode":Z="code --install-extension blade-code.blade-code";break;case"vscode-insiders":Z="code-insiders --install-extension blade-code.blade-code";break;case"cursor":Z="cursor --install-extension blade-code.blade-code";break;default:return{success:!1,message:"不支持的 IDE: "+$}}try{return await $5(Z),{success:!0,message:"扩展安装成功"}}catch(J){return{success:!1,message:"安装失败: "+(J instanceof Error?J.message:"未知错误")}}}static async checkVsCode(){try{let{stdout:$}=await $5("code --version");return{id:"vscode",name:"VS Code",version:$.trim().split(`
1924
1924
  `)[0]||"unknown"}}catch{return null}}static async checkVsCodeInsiders(){try{let{stdout:$}=await $5("code-insiders --version");return{id:"vscode-insiders",name:"VS Code Insiders",version:$.trim().split(`
1925
1925
  `)[0]||"unknown"}}catch{return null}}static async checkCursor(){try{let{stdout:$}=await $5("cursor --version");return{id:"cursor",name:"Cursor",version:$.trim().split(`
1926
- `)[0]||"unknown"}}catch{return null}}}var R2=CJ(vJ(),".blade","ide-port");var T0="disconnected",x8=null,f8=null;function IJ(){switch(T0){case"connected":return{type:"info",content:`[OK] 已连接到 ${x8||"IDE"} (端口: ${f8})`};case"connecting":return{type:"info",content:"正在连接..."};default:return{type:"error",content:"未连接到 IDE"}}}function k2(){try{if(TJ(R2)){let $=MJ(R2,"utf-8");return JSON.parse($)}}catch{}return null}function b2(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let Z=k2();if(Z)return Z.port;return null}async function SJ(){let $=[],Z=IJ();$.push(Z.content),$.push(""),$.push("已安装的 IDE:");let J=await Z1.getInstalledIdes();if(J.length===0)$.push(" (未检测到支持的 IDE)");else for(let V of J)$.push(` • ${V.name} ${V.version}`);$.push("");let W=await y8.detectIde();if(W){if($.push(`当前环境: ${W.name} ${W.version}`),W.extensions.length>0)$.push(` 已安装扩展: ${W.extensions.length} 个`)}let X=b2(),Y=k2();if(X){if($.push(`IDE 端口: ${X}`),Y&&Y.workspaceFolders.length>0)$.push(` 工作区: ${Y.workspaceFolders[0]}`)}else $.push(""),$.push("提示: 在 VS Code 中安装 Blade Code 插件后,运行 /ide connect 连接");return $.join(`
1927
- `)}async function PJ(){let $=b2();if(!$)return`未检测到 IDE 端口
1926
+ `)[0]||"unknown"}}catch{return null}}}var R2=SJ(IJ(),".blade","ide-port");var M0="disconnected",x8=null,f8=null;function PJ(){switch(M0){case"connected":return{type:"info",content:`[OK] 已连接到 ${x8||"IDE"} (端口: ${f8})`};case"connecting":return{type:"info",content:"正在连接..."};default:return{type:"error",content:"未连接到 IDE"}}}function k2(){try{if(vJ(R2)){let $=CJ(R2,"utf-8");return JSON.parse($)}}catch{}return null}function b2(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let Z=k2();if(Z)return Z.port;return null}async function yJ(){let $=[],Z=PJ();$.push(Z.content),$.push(""),$.push("已安装的 IDE:");let J=await Z1.getInstalledIdes();if(J.length===0)$.push(" (未检测到支持的 IDE)");else for(let V of J)$.push(` • ${V.name} ${V.version}`);$.push("");let W=await y8.detectIde();if(W){if($.push(`当前环境: ${W.name} ${W.version}`),W.extensions.length>0)$.push(` 已安装扩展: ${W.extensions.length} 个`)}let X=b2(),Y=k2();if(X){if($.push(`IDE 端口: ${X}`),Y&&Y.workspaceFolders.length>0)$.push(` 工作区: ${Y.workspaceFolders[0]}`)}else $.push(""),$.push("提示: 在 VS Code 中安装 Blade Code 插件后,运行 /ide connect 连接");return $.join(`
1927
+ `)}async function xJ(){let $=b2();if(!$)return`未检测到 IDE 端口
1928
1928
 
1929
1929
  请确保:
1930
1930
  1. 已在 VS Code 中安装 Blade Code 插件
@@ -1932,25 +1932,25 @@ ${J}
1932
1932
  3. 在 VS Code 终端中运行 blade
1933
1933
 
1934
1934
  或手动设置端口:
1935
- export BLADE_IDE_PORT=9527`;T0="connecting";try{let J=new(await import("ws")).default(`ws://127.0.0.1:${$}`);return await new Promise((W,X)=>{let Y=setTimeout(()=>{J.close(),X(Error("连接超时"))},5000);J.on("open",()=>{clearTimeout(Y),T0="connected",f8=$,x8="VS Code",J.close(),W()}),J.on("error",(V)=>{clearTimeout(Y),X(V)})}),`[OK] 成功连接到 IDE (端口: ${$})
1935
+ export BLADE_IDE_PORT=9527`;M0="connecting";try{let J=new(await import("ws")).default(`ws://127.0.0.1:${$}`);return await new Promise((W,X)=>{let Y=setTimeout(()=>{J.close(),X(Error("连接超时"))},5000);J.on("open",()=>{clearTimeout(Y),M0="connected",f8=$,x8="VS Code",J.close(),W()}),J.on("error",(V)=>{clearTimeout(Y),X(V)})}),`[OK] 成功连接到 IDE (端口: ${$})
1936
1936
 
1937
1937
  现在可以使用以下功能:
1938
1938
  • 在 IDE 中打开文件
1939
1939
  • 获取当前选中的代码
1940
- • 查看打开的编辑器列表`}catch(Z){return T0="disconnected",`连接失败: ${Z instanceof Error?Z.message:"未知错误"}
1940
+ • 查看打开的编辑器列表`}catch(Z){return M0="disconnected",`连接失败: ${Z instanceof Error?Z.message:"未知错误"}
1941
1941
 
1942
1942
  请检查:
1943
1943
  1. VS Code 插件是否正在运行
1944
1944
  2. 端口 ${$} 是否正确
1945
- 3. 防火墙设置`}}async function yJ(){let $=[];if($.push("安装 Blade Code VS Code 插件"),$.push(""),!await Z1.isIdeInstalled("vscode"))return $.push("未检测到 VS Code"),$.push(""),$.push("请先安装 VS Code:"),$.push(" https://code.visualstudio.com/"),$.join(`
1945
+ 3. 防火墙设置`}}async function fJ(){let $=[];if($.push("安装 Blade Code VS Code 插件"),$.push(""),!await Z1.isIdeInstalled("vscode"))return $.push("未检测到 VS Code"),$.push(""),$.push("请先安装 VS Code:"),$.push(" https://code.visualstudio.com/"),$.join(`
1946
1946
  `);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(`
1947
- `)}async function xJ(){if(T0==="disconnected")return"[WARN] 当前未连接到任何 IDE";return T0="disconnected",x8=null,f8=null,"[OK] 已断开与 IDE 的连接"}var fJ={name:"ide",aliases:[],description:"Manage IDE integrations and show status",usage:"/ide [status|connect|install|disconnect]",category:"system",async handler($,Z){let J=($[0]||"").toLowerCase(),W;switch(J){case"":case"status":W=await SJ();break;case"connect":W=await PJ();break;case"install":W=await yJ();break;case"disconnect":W=await xJ();break;default:W=`未知的子命令: ${J}
1947
+ `)}async function hJ(){if(M0==="disconnected")return"[WARN] 当前未连接到任何 IDE";return M0="disconnected",x8=null,f8=null,"[OK] 已断开与 IDE 的连接"}var pJ={name:"ide",aliases:[],description:"Manage IDE integrations and show status",usage:"/ide [status|connect|install|disconnect]",category:"system",async handler($,Z){let J=($[0]||"").toLowerCase(),W;switch(J){case"":case"status":W=await yJ();break;case"connect":W=await xJ();break;case"install":W=await fJ();break;case"disconnect":W=await hJ();break;default:W=`未知的子命令: ${J}
1948
1948
 
1949
1949
  可用命令:
1950
1950
  /ide status - 显示连接状态
1951
1951
  /ide connect - 连接到 IDE
1952
1952
  /ide install - 安装 VS Code 插件
1953
- /ide disconnect - 断开连接`}return{success:!0,message:W}}},T2=fJ;import{promises as J1}from"fs";import*as M2 from"path";var M0=M("Agent"),hJ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:J,signal:W}=Z,X=I(Z),Y=(O)=>{X.sendMessage(`${O}`)},V=i().session.sessionId,B=M2.join(J,"BLADE.md"),K=!1,Q=!1;try{if(K=(await J1.stat(B)).isFile(),K)Q=(await J1.readFile(B,"utf-8")).trim().length===0}catch{K=!1}if(K&&!Q){X.sendMessage("[WARN] BLADE.md 已存在。"),X.sendMessage("正在分析现有文件并提供改进建议...");let O=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let F=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1953
+ /ide disconnect - 断开连接`}return{success:!0,message:W}}},T2=pJ;import{promises as J1}from"fs";import*as M2 from"path";var v0=M("Agent"),dJ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:J,signal:W}=Z,X=I(Z),Y=(O)=>{X.sendMessage(`${O}`)},V=i().session.sessionId,B=M2.join(J,"BLADE.md"),K=!1,Q=!1;try{if(K=(await J1.stat(B)).isFile(),K)Q=(await J1.readFile(B,"utf-8")).trim().length===0}catch{K=!1}if(K&&!Q){X.sendMessage("[WARN] BLADE.md 已存在。"),X.sendMessage("正在分析现有文件并提供改进建议...");let O=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let F=`Please analyze the existing BLADE.md file and provide improvement suggestions.
1954
1954
 
1955
1955
  **Important**:
1956
1956
  - After each step, briefly describe what you found before proceeding
@@ -1989,7 +1989,7 @@ ${J}
1989
1989
  - 具体的改进建议(附带示例)
1990
1990
  - 如果需要重大修改,提供完整的改进版本内容
1991
1991
 
1992
- **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;M0.info(`[/init] Starting agent.chatStream, signal.aborted: ${W?.aborted}`);let w=(await N$(O.chatStream(F,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:J,signal:W}),async(L)=>{switch(L.kind){case"tool_start":{let E=L.toolCall;if(!("function"in E))return;try{let j=JSON.parse(E.function.arguments),b=N8(E.function.name,j);Y(b)}catch{}break}case"tool_result":{if(!("function"in L.toolCall))return;let j=L.result.metadata?.summary;if(j)Y(j);break}default:break}})).finalMessage||"";if(M0.info(`[/init] agent.chatStream completed, signal.aborted: ${W?.aborted}`),W?.aborted)return M0.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return X.sendMessage(w),{success:!0,message:"[OK] 分析完成"}}if(Q)X.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");X.sendMessage("正在分析项目结构...");let U=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let q=`Please analyze this codebase and generate BLADE.md content.
1992
+ **Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;v0.info(`[/init] Starting agent.chatStream, signal.aborted: ${W?.aborted}`);let w=(await D$(O.chatStream(F,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:J,signal:W}),async(L)=>{switch(L.kind){case"tool_start":{let E=L.toolCall;if(!("function"in E))return;try{let j=JSON.parse(E.function.arguments),b=N8(E.function.name,j);Y(b)}catch{}break}case"tool_result":{if(!("function"in L.toolCall))return;let j=L.result.metadata?.summary;if(j)Y(j);break}default:break}})).finalMessage||"";if(v0.info(`[/init] agent.chatStream completed, signal.aborted: ${W?.aborted}`),W?.aborted)return v0.info("[/init] Returning cancelled after agent.chat"),{success:!1,message:"操作已取消"};return X.sendMessage(w),{success:!0,message:"[OK] 分析完成"}}if(Q)X.sendMessage("[WARN] 检测到空的 BLADE.md 文件,将重新生成...");X.sendMessage("正在分析项目结构...");let U=await V$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let q=`Please analyze this codebase and generate BLADE.md content.
1993
1993
 
1994
1994
  **Important**: After each step, briefly describe what you found before proceeding.
1995
1995
 
@@ -2035,7 +2035,7 @@ ${J}
2035
2035
  - Focus on non-obvious insights
2036
2036
  - Be concise but comprehensive for complex projects
2037
2037
 
2038
- **Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;M0.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${W?.aborted}`);let G=(await N$(U.chatStream(q,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:J,signal:W}),async(O)=>{switch(O.kind){case"tool_start":{let F=O.toolCall;if(!("function"in F))return;try{let z=JSON.parse(F.function.arguments),w=N8(F.function.name,z);Y(w)}catch{}break}case"tool_result":{if(!("function"in O.toolCall))return;let z=O.result?.metadata;if(z?.summary){if(typeof z.summary==="string")Y(z.summary)}break}default:break}})).finalMessage||"";if(M0.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${W?.aborted}`),W?.aborted)return M0.info("[/init] Returning cancelled after agent.chat (new BLADE.md)"),{success:!1,message:"操作已取消"};if(!G||G.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return X.sendMessage("正在写入 BLADE.md..."),await J1.writeFile(B,G,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(J){return{success:!1,error:`初始化失败: ${J instanceof Error?J.message:"未知错误"}`}}}},v2=hJ;var pJ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
2038
+ **Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;v0.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${W?.aborted}`);let G=(await D$(U.chatStream(q,{messages:[],userId:"cli-user",sessionId:V||"init-session",workspaceRoot:J,signal:W}),async(O)=>{switch(O.kind){case"tool_start":{let F=O.toolCall;if(!("function"in F))return;try{let z=JSON.parse(F.function.arguments),w=N8(F.function.name,z);Y(w)}catch{}break}case"tool_result":{if(!("function"in O.toolCall))return;let z=O.result?.metadata;if(z?.summary){if(typeof z.summary==="string")Y(z.summary)}break}default:break}})).finalMessage||"";if(v0.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${W?.aborted}`),W?.aborted)return v0.info("[/init] Returning cancelled after agent.chat (new BLADE.md)"),{success:!1,message:"操作已取消"};if(!G||G.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return X.sendMessage("正在写入 BLADE.md..."),await J1.writeFile(B,G,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(J){return{success:!1,error:`初始化失败: ${J instanceof Error?J.message:"未知错误"}`}}}},v2=dJ;var uJ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
2039
2039
  管理和切换模型配置
2040
2040
 
2041
2041
  子命令:
@@ -2049,11 +2049,11 @@ ${J}
2049
2049
  /model add # 添加新模型
2050
2050
  /model remove 千问 # 删除名称包含"千问"的模型
2051
2051
  /model once claude-sonnet 帮我总结这段代码
2052
- `,async handler($,Z){let J=$[0];if(!J){if(l$().length===0)return{success:!1,message:`没有可用的模型配置
2052
+ `,async handler($,Z){let J=$[0];if(!J){if(i$().length===0)return{success:!1,message:`没有可用的模型配置
2053
2053
 
2054
2054
  使用 /model add 添加模型`};return{success:!0,message:"show_model_selector",data:{action:"show_model_selector"}}}switch(J){case"add":return{success:!0,message:"show_model_add_wizard",data:{action:"show_model_add_wizard",mode:"add"}};case"remove":{let W=$.slice(1).join(" ");if(!W)return{success:!1,message:`请指定要删除的模型名称
2055
- 用法: /model remove <名称>`};let Y=l$().find((V)=>V.name.toLowerCase().includes(W.toLowerCase()));if(!Y)return{success:!1,message:`未找到匹配的模型配置: ${W}`};try{return await x$().removeModel(Y.id),{success:!0,message:`[OK] 已删除模型配置: ${Y.name}`}}catch(V){return{success:!1,message:`${V.message}`}}}case"once":{let W=$[1],X=$.slice(2).join(" ").trim();if(!W||!X)return{success:!1,message:"用法: /model once <模型> <内容>"};let Y=l$(),V=Y.find((B)=>B.id===W)||Y.find((B)=>B.name.toLowerCase().includes(W.toLowerCase()));if(!V)return{success:!1,message:`未找到匹配的模型配置: ${W}`};return{success:!0,data:{action:"invoke_once_model",modelId:V.id,prompt:X}}}default:return{success:!1,message:`未知的子命令: ${J}
2056
- 使用 /model 查看可用操作`}}}},C2=pJ;var dJ={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
2055
+ 用法: /model remove <名称>`};let Y=i$().find((V)=>V.name.toLowerCase().includes(W.toLowerCase()));if(!Y)return{success:!1,message:`未找到匹配的模型配置: ${W}`};try{return await f$().removeModel(Y.id),{success:!0,message:`[OK] 已删除模型配置: ${Y.name}`}}catch(V){return{success:!1,message:`${V.message}`}}}case"once":{let W=$[1],X=$.slice(2).join(" ").trim();if(!W||!X)return{success:!1,message:"用法: /model once <模型> <内容>"};let Y=i$(),V=Y.find((B)=>B.id===W)||Y.find((B)=>B.name.toLowerCase().includes(W.toLowerCase()));if(!V)return{success:!1,message:`未找到匹配的模型配置: ${W}`};return{success:!0,data:{action:"invoke_once_model",modelId:V.id,prompt:X}}}default:return{success:!1,message:`未知的子命令: ${J}
2056
+ 使用 /model 查看可用操作`}}}},C2=uJ;var gJ={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
2057
2057
 
2058
2058
  子命令:
2059
2059
  /plugins - 打开插件管理界面
@@ -2065,25 +2065,25 @@ ${J}
2065
2065
  /plugins enable <name> - 启用插件
2066
2066
  /plugins disable <name> - 禁用插件
2067
2067
  /plugins refresh - 刷新插件列表
2068
- /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($,Z)=>{let J=$[0]?.toLowerCase()||"",W=I$();switch(J){case"":return await lJ(W),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return uJ(W);case"info":return gJ(W,$[1]);case"install":case"add":return rJ($[1]);case"uninstall":case"remove":case"rm":return sJ($[1]);case"update":case"upgrade":return oJ($[1]);case"enable":return mJ(W,$[1]);case"disable":return cJ(W,$[1]);case"refresh":return iJ(W);case"stats":return aJ(W);default:return A().addAssistantMessage(`未知子命令: ${J}
2069
- 使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function uJ($){if($.getAll().length===0)return A().addAssistantMessage(`没有已加载的插件。
2068
+ /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($,Z)=>{let J=$[0]?.toLowerCase()||"",W=S$();switch(J){case"":return await aJ(W),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return mJ(W);case"info":return cJ(W,$[1]);case"install":case"add":return oJ($[1]);case"uninstall":case"remove":case"rm":return tJ($[1]);case"update":case"upgrade":return eJ($[1]);case"enable":return lJ(W,$[1]);case"disable":return iJ(W,$[1]);case"refresh":return nJ(W);case"stats":return rJ(W);default:return A().addAssistantMessage(`未知子命令: ${J}
2069
+ 使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function mJ($){if($.getAll().length===0)return A().addAssistantMessage(`没有已加载的插件。
2070
2070
 
2071
2071
  `+"使用 `--plugin-dir <path>` 参数加载插件,或将插件放置在:\n"+"- `~/.blade/plugins/` - 用户级插件\n"+"- `.blade/plugins/` - 项目级插件"),{success:!0,message:"No plugins loaded"};let J=["## 已加载的插件",""],W=$.getBySource();if(W.cli.length>0){J.push("### CLI 指定");for(let X of W.cli){let Y=X.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${X.manifest.name}** v${X.manifest.version}${Y}`),J.push(` ${X.manifest.description}`)}J.push("")}if(W.project.length>0){J.push("### 项目级");for(let X of W.project){let Y=X.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${X.manifest.name}** v${X.manifest.version}${Y}`),J.push(` ${X.manifest.description}`)}J.push("")}if(W.user.length>0){J.push("### 用户级");for(let X of W.user){let Y=X.status==="inactive"?" [PAUSED]":" [OK]";J.push(`- **${X.manifest.name}** v${X.manifest.version}${Y}`),J.push(` ${X.manifest.description}`)}}return A().addAssistantMessage(J.join(`
2072
- `)),{success:!0,message:"Plugins listed"}}function gJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins info <name>`"),{success:!1,error:"Plugin name required"};let J=$.get(Z);if(!J)return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};let W=[`## ${J.manifest.name}`,"",`**版本**: ${J.manifest.version}`,`**描述**: ${J.manifest.description}`,`**状态**: ${J.status==="active"?"[OK] 启用":"禁用"}`,`**来源**: ${nJ(J.source)}`,`**路径**: \`${J.basePath}\``,""];if(J.manifest.author)W.push(`**作者**: ${J.manifest.author.name}`);if(J.manifest.license)W.push(`**许可证**: ${J.manifest.license}`);if(J.manifest.repository)W.push(`**仓库**: ${J.manifest.repository}`);if(J.commands.length>0){W.push(""),W.push(`### 命令 (${J.commands.length})`);for(let X of J.commands){let Y=X.config.argumentHint?` ${X.config.argumentHint}`:"",V=X.config.description?` - ${X.config.description}`:"";W.push(`- \`/${X.namespacedName}${Y}\`${V}`)}}if(J.skills.length>0){W.push(""),W.push(`### 技能 (${J.skills.length})`);for(let X of J.skills)W.push(`- \`${X.namespacedName}\` - ${X.metadata.description}`)}if(J.agents.length>0){W.push(""),W.push(`### 代理 (${J.agents.length})`);for(let X of J.agents)W.push(`- \`${X.namespacedName}\` - ${X.config.description}`)}if(J.mcpServers){let X=Object.keys(J.mcpServers).length;W.push(""),W.push(`### MCP 服务器 (${X})`);for(let Y of Object.keys(J.mcpServers))W.push(`- \`${Y}\``)}if(J.hooks)W.push(""),W.push("### Hooks"),W.push("插件已配置 hooks");return A().addAssistantMessage(W.join(`
2073
- `)),{success:!0,message:"Plugin info displayed"}}function mJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(Z))return A().addAssistantMessage(`[OK] 已启用插件: ${Z}`),{success:!0,message:`Plugin ${Z} enabled`};if(!$.get(Z))return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return A().addAssistantMessage(`插件 ${Z} 已经是启用状态`),{success:!0,message:`Plugin ${Z} already enabled`}}function cJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(Z))return A().addAssistantMessage(`已禁用插件: ${Z}`),{success:!0,message:`Plugin ${Z} disabled`};if(!$.get(Z))return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return A().addAssistantMessage(`插件 ${Z} 已经是禁用状态`),{success:!0,message:`Plugin ${Z} already disabled`}}async function lJ($){a1(),await $.refresh(),await i1()}async function iJ($){try{a1();let Z=await $.refresh(),J=await i1(),W=["[OK] 已刷新插件列表","",`- 加载了 ${Z.plugins.length} 个插件`,`- 集成了 ${J.totalCommands} 个命令, ${J.totalSkills} 个技能, ${J.totalAgents} 个代理`];if(Z.errors.length>0){W.push(`- ${Z.errors.length} 个加载错误`),W.push(""),W.push("### 错误");for(let X of Z.errors)W.push(`- \`${X.path}\`: ${X.error}`)}if(J.errors.length>0){W.push(""),W.push("### 集成错误");for(let X of J.errors)W.push(`- ${X}`)}return A().addAssistantMessage(W.join(`
2074
- `)),{success:!0,message:"Plugins refreshed"}}catch(Z){let J=Z instanceof Error?Z.message:String(Z);return A().addAssistantMessage(`刷新失败: ${J}`),{success:!1,error:J}}}function aJ($){let Z=$.getStats(),J=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${Z.total} |`,`| 启用 | ${Z.active} |`,`| 禁用 | ${Z.inactive} |`,`| 命令 | ${Z.commands} |`,`| 技能 | ${Z.skills} |`,`| 代理 | ${Z.agents} |`];return A().addAssistantMessage(J.join(`
2075
- `)),{success:!0,message:"Stats displayed"}}function nJ($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function rJ($){if(!$)return A().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
2072
+ `)),{success:!0,message:"Plugins listed"}}function cJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins info <name>`"),{success:!1,error:"Plugin name required"};let J=$.get(Z);if(!J)return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};let W=[`## ${J.manifest.name}`,"",`**版本**: ${J.manifest.version}`,`**描述**: ${J.manifest.description}`,`**状态**: ${J.status==="active"?"[OK] 启用":"禁用"}`,`**来源**: ${sJ(J.source)}`,`**路径**: \`${J.basePath}\``,""];if(J.manifest.author)W.push(`**作者**: ${J.manifest.author.name}`);if(J.manifest.license)W.push(`**许可证**: ${J.manifest.license}`);if(J.manifest.repository)W.push(`**仓库**: ${J.manifest.repository}`);if(J.commands.length>0){W.push(""),W.push(`### 命令 (${J.commands.length})`);for(let X of J.commands){let Y=X.config.argumentHint?` ${X.config.argumentHint}`:"",V=X.config.description?` - ${X.config.description}`:"";W.push(`- \`/${X.namespacedName}${Y}\`${V}`)}}if(J.skills.length>0){W.push(""),W.push(`### 技能 (${J.skills.length})`);for(let X of J.skills)W.push(`- \`${X.namespacedName}\` - ${X.metadata.description}`)}if(J.agents.length>0){W.push(""),W.push(`### 代理 (${J.agents.length})`);for(let X of J.agents)W.push(`- \`${X.namespacedName}\` - ${X.config.description}`)}if(J.mcpServers){let X=Object.keys(J.mcpServers).length;W.push(""),W.push(`### MCP 服务器 (${X})`);for(let Y of Object.keys(J.mcpServers))W.push(`- \`${Y}\``)}if(J.hooks)W.push(""),W.push("### Hooks"),W.push("插件已配置 hooks");return A().addAssistantMessage(W.join(`
2073
+ `)),{success:!0,message:"Plugin info displayed"}}function lJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins enable <name>`"),{success:!1,error:"Plugin name required"};if($.enable(Z))return A().addAssistantMessage(`[OK] 已启用插件: ${Z}`),{success:!0,message:`Plugin ${Z} enabled`};if(!$.get(Z))return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return A().addAssistantMessage(`插件 ${Z} 已经是启用状态`),{success:!0,message:`Plugin ${Z} already enabled`}}function iJ($,Z){if(!Z)return A().addAssistantMessage("请指定插件名称: `/plugins disable <name>`"),{success:!1,error:"Plugin name required"};if($.disable(Z))return A().addAssistantMessage(`已禁用插件: ${Z}`),{success:!0,message:`Plugin ${Z} disabled`};if(!$.get(Z))return A().addAssistantMessage(`未找到插件: ${Z}`),{success:!1,error:`Plugin not found: ${Z}`};return A().addAssistantMessage(`插件 ${Z} 已经是禁用状态`),{success:!0,message:`Plugin ${Z} already disabled`}}async function aJ($){a1(),await $.refresh(),await i1()}async function nJ($){try{a1();let Z=await $.refresh(),J=await i1(),W=["[OK] 已刷新插件列表","",`- 加载了 ${Z.plugins.length} 个插件`,`- 集成了 ${J.totalCommands} 个命令, ${J.totalSkills} 个技能, ${J.totalAgents} 个代理`];if(Z.errors.length>0){W.push(`- ${Z.errors.length} 个加载错误`),W.push(""),W.push("### 错误");for(let X of Z.errors)W.push(`- \`${X.path}\`: ${X.error}`)}if(J.errors.length>0){W.push(""),W.push("### 集成错误");for(let X of J.errors)W.push(`- ${X}`)}return A().addAssistantMessage(W.join(`
2074
+ `)),{success:!0,message:"Plugins refreshed"}}catch(Z){let J=Z instanceof Error?Z.message:String(Z);return A().addAssistantMessage(`刷新失败: ${J}`),{success:!1,error:J}}}function rJ($){let Z=$.getStats(),J=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${Z.total} |`,`| 启用 | ${Z.active} |`,`| 禁用 | ${Z.inactive} |`,`| 命令 | ${Z.commands} |`,`| 技能 | ${Z.skills} |`,`| 代理 | ${Z.agents} |`];return A().addAssistantMessage(J.join(`
2075
+ `)),{success:!0,message:"Stats displayed"}}function sJ($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function oJ($){if(!$)return A().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
2076
2076
  `+"- GitHub 简写: `user/repo`\n"+"- 完整 URL: `https://github.com/user/repo`"),{success:!1,error:"Plugin URL required"};A().addAssistantMessage(`正在安装插件: ${$}...`);let J=await s0().install($);if(J.success){let W=["[OK] 插件安装成功!","",`**名称**: ${J.pluginName}`,`**路径**: \`${J.pluginPath}\``];if(J.manifest)W.push(`**版本**: ${J.manifest.version}`),W.push(`**描述**: ${J.manifest.description}`);return W.push(""),W.push("使用 `/plugins refresh` 加载新安装的插件。"),A().addAssistantMessage(W.join(`
2077
- `)),{success:!0,message:`Installed ${J.pluginName}`}}return A().addAssistantMessage(`安装失败: ${J.error}`),{success:!1,error:J.error}}async function sJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins uninstall <name>`"),{success:!1,error:"Plugin name required"};let J=await s0().uninstall($);if(J.success)return A().addAssistantMessage(`[OK] 已卸载插件: ${J.pluginName}
2077
+ `)),{success:!0,message:`Installed ${J.pluginName}`}}return A().addAssistantMessage(`安装失败: ${J.error}`),{success:!1,error:J.error}}async function tJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins uninstall <name>`"),{success:!1,error:"Plugin name required"};let J=await s0().uninstall($);if(J.success)return A().addAssistantMessage(`[OK] 已卸载插件: ${J.pluginName}
2078
2078
 
2079
- `+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${J.pluginName}`};return A().addAssistantMessage(`卸载失败: ${J.error}`),{success:!1,error:J.error}}async function oJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins update <name>`"),{success:!1,error:"Plugin name required"};A().addAssistantMessage(`正在更新插件: ${$}...`);let J=await s0().update($);if(J.success){let W=["[OK] 插件更新成功!","",`**名称**: ${J.pluginName}`];if(J.manifest)W.push(`**版本**: ${J.manifest.version}`);return W.push(""),W.push("使用 `/plugins refresh` 重新加载插件。"),A().addAssistantMessage(W.join(`
2080
- `)),{success:!0,message:`Updated ${J.pluginName}`}}return A().addAssistantMessage(`更新失败: ${J.error}`),{success:!1,error:J.error}}var I2=dJ;var tJ={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await Q$().refresh(),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let W=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return A().addAssistantMessage(W),{success:!1,error:W}}}},S2=tJ;function Z5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function P2($){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 y2($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function eJ($,Z){let J=I(Z),W=$[0],X=n.getInstance(),Y=c.getInstance();if(W==="clean"){let H=Y.cleanupExpiredSessions(0);return J.sendMessage(`已清理 ${H} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${H} agent sessions`}}let V=[`**后台任务列表**
2079
+ `+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${J.pluginName}`};return A().addAssistantMessage(`卸载失败: ${J.error}`),{success:!1,error:J.error}}async function eJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins update <name>`"),{success:!1,error:"Plugin name required"};A().addAssistantMessage(`正在更新插件: ${$}...`);let J=await s0().update($);if(J.success){let W=["[OK] 插件更新成功!","",`**名称**: ${J.pluginName}`];if(J.manifest)W.push(`**版本**: ${J.manifest.version}`);return W.push(""),W.push("使用 `/plugins refresh` 重新加载插件。"),A().addAssistantMessage(W.join(`
2080
+ `)),{success:!0,message:`Updated ${J.pluginName}`}}return A().addAssistantMessage(`更新失败: ${J.error}`),{success:!1,error:J.error}}var I2=gJ;var $W={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await Q$().refresh(),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let W=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return A().addAssistantMessage(W),{success:!1,error:W}}}},S2=$W;function Z5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function P2($){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 y2($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function ZW($,Z){let J=I(Z),W=$[0],X=n.getInstance(),Y=c.getInstance();if(W==="clean"){let H=Y.cleanupExpiredSessions(0);return J.sendMessage(`已清理 ${H} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${H} agent sessions`}}let V=[`**后台任务列表**
2081
2081
  `],B=X.processes,K=Array.from(B?.values()||[]);if(K.length>0){V.push(`### Shells
2082
2082
  `),V.push("| ID | 状态 | 命令 | PID | 运行时间 |"),V.push("|:---|:-----|:-----|:----|:---------|");for(let H of K){let G=H.endTime?Z5(H.endTime-H.startTime):Z5(Date.now()-H.startTime),O=P2(H.status);V.push(`| \`${H.id.slice(0,12)}...\` | ${O} ${H.status} | \`${y2(H.command,30)}\` | ${H.pid||"-"} | ${G} |`)}V.push("")}let Q=Y.listAll();if(Q.length>0){V.push(`### Agents
2083
2083
  `),V.push("| ID | 状态 | 类型 | 描述 | 运行时间 |"),V.push("|:---|:-----|:-----|:-----|:---------|");for(let H of Q){let G=H.completedAt?Z5(H.completedAt-H.createdAt):Z5(Date.now()-H.createdAt),O=P2(H.status);V.push(`| \`${H.id.slice(0,12)}...\` | ${O} ${H.status} | ${H.subagentType} | ${y2(H.description,25)} | ${G} |`)}V.push("")}let U=K.filter((H)=>H.status==="running").length,q=Y.getRunningCount();if(K.length===0&&Q.length===0)V.push(`*暂无后台任务*
2084
2084
  `);else V.push(`**统计**: ${K.length} shells (${U} 运行中), ${Q.length} agents (${q} 运行中)`);return V.push(`
2085
2085
  ---`),V.push("**命令**:"),V.push("- `/tasks` - 列出所有后台任务"),V.push("- `/tasks clean` - 清理已完成的 Agent 会话"),J.sendMessage(V.join(`
2086
- `)),{success:!0,message:`Listed ${K.length} shells and ${Q.length} agents`}}var $W={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
2086
+ `)),{success:!0,message:`Listed ${K.length} shells and ${Q.length} agents`}}var JW={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
2087
2087
 
2088
2088
  **功能**:
2089
2089
  - 列出所有后台 shell 进程
@@ -2092,8 +2092,8 @@ ${J}
2092
2092
 
2093
2093
  **使用示例**:
2094
2094
  - \`/tasks\` - 显示所有后台任务
2095
- - \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:eJ},x2=$W;async function ZW($,Z){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var JW={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:ZW},f2=JW;var W1={...O2,init:v2,theme:f2,permissions:r1,model:C2,git:E2,ide:T2,skills:S2,hooks:_2,tasks:x2,plugins:I2};function Oz($){return $.trim().startsWith("/")}function XW($){let Z=$.trim();if(!Z.startsWith("/"))throw Error("不是有效的 slash command");let J=Z.slice(1).split(/\s+/),W=J[0]||"",X=J.slice(1);return{command:W,args:X}}function YW($){if(W1[$])return W1[$];for(let Z of Object.values(W1))if(Z.aliases?.includes($))return Z;return}function h2($){let Z=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
2095
+ - \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:ZW},x2=JW;async function WW($,Z){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var XW={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:WW},f2=XW;var W1={...O2,init:v2,theme:f2,permissions:r1,model:C2,git:E2,ide:T2,skills:S2,hooks:_2,tasks:x2,plugins:I2};function jz($){return $.trim().startsWith("/")}function VW($){let Z=$.trim();if(!Z.startsWith("/"))throw Error("不是有效的 slash command");let J=Z.slice(1).split(/\s+/),W=J[0]||"",X=J.slice(1);return{command:W,args:X}}function BW($){if(W1[$])return W1[$];for(let Z of Object.values(W1))if(Z.aliases?.includes($))return Z;return}function h2($){let Z=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
2096
2096
 
2097
- **When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,W)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function VW($){return Q$().getUserInvocableSkills().find((W)=>W.name===$)}async function BW(){await D0()}async function zz($){return await d.getInstance().initialize($)}async function wz($,Z){try{let{command:J,args:W}=XW($),X=YW(J);if(X)return await X.handler(W,Z);let Y=d.getInstance();if(Y.hasCommand(J)){let Q=Y.getCommand(J);if(Q){let U=Z.workspaceRoot||N(),q=await Y.executeCommand(J,{args:W,workspaceRoot:U,signal:Z.signal});if(q)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:q,config:Q.config}}}}let B=I$().findCommand(J);if(B){let Q=Z.workspaceRoot||N(),U=await Y.executePluginCommand(B.namespacedName,{args:W,workspaceRoot:Q,signal:Z.signal});if(U)return{success:!0,message:`执行插件命令: /${B.namespacedName}`,data:{action:"invoke_plugin_command",commandName:B.namespacedName,pluginName:B.pluginName,processedContent:U,config:B.config}}}await BW();let K=VW(J);if(K)return await h2(K).handler(W,Z);return{success:!1,error:`未知命令: /${J}
2098
- 使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function jz(){let $=Object.values(W1),J=d.getInstance().getAllCommands().map((B)=>({name:B.name,description:B.config.description||B.content.slice(0,50),usage:B.config.argumentHint?`/${B.name} ${B.config.argumentHint}`:`/${B.name}`,category:"custom",handler:async()=>({success:!0})})),X=I$().getAllCommands().map((B)=>({name:B.namespacedName,description:B.config.description||B.content.slice(0,50),usage:B.config.argumentHint?`/${B.namespacedName} ${B.config.argumentHint}`:`/${B.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),V=Q$().getUserInvocableSkills().map(h2);return[...$,...J,...X,...V]}function Nz($){let Z=($.startsWith("/")?$.slice(1):$).trim(),J=Object.values(W1).map((G)=>({name:G.name,description:G.description,aliases:G.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),W=d.getInstance(),X=W.getAllCommands().map((G)=>({name:G.name,description:G.config.description||G.content.slice(0,50),aliases:[],label:W.getCommandLabel(G),argumentHint:G.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),V=I$().getAllCommands().map((G)=>({name:G.namespacedName,description:G.config.description||G.content.slice(0,50),aliases:[G.originalName],label:`(plugin: ${G.pluginName})`,argumentHint:G.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),K=Q$().getUserInvocableSkills().map((G)=>({name:G.name,description:G.description,aliases:[],label:"(skill)",argumentHint:G.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),Q=[...J,...X,...V,...K];if(!Z)return Q.map((G)=>({command:`/${G.name}`,description:G.label?`${G.description} ${G.label}`:G.description,argumentHint:G.argumentHint,matchScore:50}));return new WW(Q,{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(Z).map((G)=>{let O=G.score??1,F=Math.round((1-O)*100),z=G.item;return{command:`/${z.name}`,description:z.label?`${z.description} ${z.label}`:z.description,argumentHint:z.argumentHint,matchScore:F}}).filter((G)=>(G.matchScore||0)>=40)}
2099
- export{XX as y,w0 as z,R as A,W0 as B,h7 as C,n as D,b1 as E,P as F,y1 as G,U0 as H,N8 as I,O9 as J,z9 as K,N9 as L,V$ as M,I$ as N,i1 as O,o0 as P,I8 as Q,KO as R,Oz as S,zz as T,wz as U,jz as V,Nz as W};
2097
+ **When to use:** ${$.whenToUse}`:""}`,usage:Z,category:"skill",examples:[Z],handler:async(J,W)=>{return{success:!0,message:`Invoking skill: ${$.name}`,data:{action:"invoke_skill",skillName:$.name,skillArgs:J.join(" ")}}}}}function KW($){return Q$().getUserInvocableSkills().find((W)=>W.name===$)}async function QW(){await L0()}async function Nz($){return await d.getInstance().initialize($)}async function Dz($,Z){try{let{command:J,args:W}=VW($),X=BW(J);if(X)return await X.handler(W,Z);let Y=d.getInstance();if(Y.hasCommand(J)){let Q=Y.getCommand(J);if(Q){let U=Z.workspaceRoot||N(),q=await Y.executeCommand(J,{args:W,workspaceRoot:U,signal:Z.signal});if(q)return{success:!0,message:`执行自定义命令: /${J}`,data:{action:"invoke_custom_command",commandName:J,processedContent:q,config:Q.config}}}}let B=S$().findCommand(J);if(B){let Q=Z.workspaceRoot||N(),U=await Y.executePluginCommand(B.namespacedName,{args:W,workspaceRoot:Q,signal:Z.signal});if(U)return{success:!0,message:`执行插件命令: /${B.namespacedName}`,data:{action:"invoke_plugin_command",commandName:B.namespacedName,pluginName:B.pluginName,processedContent:U,config:B.config}}}await QW();let K=KW(J);if(K)return await h2(K).handler(W,Z);return{success:!1,error:`未知命令: /${J}
2098
+ 使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function Lz(){let $=Object.values(W1),J=d.getInstance().getAllCommands().map((B)=>({name:B.name,description:B.config.description||B.content.slice(0,50),usage:B.config.argumentHint?`/${B.name} ${B.config.argumentHint}`:`/${B.name}`,category:"custom",handler:async()=>({success:!0})})),X=S$().getAllCommands().map((B)=>({name:B.namespacedName,description:B.config.description||B.content.slice(0,50),usage:B.config.argumentHint?`/${B.namespacedName} ${B.config.argumentHint}`:`/${B.namespacedName}`,category:"plugin",handler:async()=>({success:!0})})),V=Q$().getUserInvocableSkills().map(h2);return[...$,...J,...X,...V]}function Ez($){let Z=($.startsWith("/")?$.slice(1):$).trim(),J=Object.values(W1).map((G)=>({name:G.name,description:G.description,aliases:G.aliases||[],label:void 0,argumentHint:void 0,isCustom:!1,isSkill:!1,isPlugin:!1})),W=d.getInstance(),X=W.getAllCommands().map((G)=>({name:G.name,description:G.config.description||G.content.slice(0,50),aliases:[],label:W.getCommandLabel(G),argumentHint:G.config.argumentHint,isCustom:!0,isSkill:!1,isPlugin:!1})),V=S$().getAllCommands().map((G)=>({name:G.namespacedName,description:G.config.description||G.content.slice(0,50),aliases:[G.originalName],label:`(plugin: ${G.pluginName})`,argumentHint:G.config.argumentHint,isCustom:!1,isSkill:!1,isPlugin:!0})),K=Q$().getUserInvocableSkills().map((G)=>({name:G.name,description:G.description,aliases:[],label:"(skill)",argumentHint:G.argumentHint,isCustom:!1,isSkill:!0,isPlugin:!1})),Q=[...J,...X,...V,...K];if(!Z)return Q.map((G)=>({command:`/${G.name}`,description:G.label?`${G.description} ${G.label}`:G.description,argumentHint:G.argumentHint,matchScore:50}));return new YW(Q,{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(Z).map((G)=>{let O=G.score??1,F=Math.round((1-O)*100),z=G.item;return{command:`/${z.name}`,description:z.label?`${z.description} ${z.label}`:z.description,argumentHint:z.argumentHint,matchScore:F}}).filter((G)=>(G.matchScore||0)>=40)}
2099
+ export{VX as y,j0 as z,R as A,X0 as B,h7 as C,n as D,b1 as E,P as F,y1 as G,q0 as H,N8 as I,O9 as J,z9 as K,N9 as L,V$ as M,S$ as N,i1 as O,o0 as P,I8 as Q,qO as R,jz as S,Nz as T,Dz as U,Lz as V,Ez as W};