blade-code 0.4.3 → 0.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blade.js +2 -2
- package/dist/{chunk-tf0m57f5.js → chunk-2e3pajfb.js} +1 -1
- package/dist/{chunk-p0n9ggyv.js → chunk-2ymnexz1.js} +1 -1
- package/dist/{chunk-1dvhq0mn.js → chunk-45f363j6.js} +1 -1
- package/dist/{chunk-ehcjnwnr.js → chunk-9syksrkj.js} +1 -1
- package/dist/{chunk-hhnst8br.js → chunk-9tgyev1k.js} +1 -1
- package/dist/chunk-b67w51zf.js +1 -0
- package/dist/chunk-c6ts8bd9.js +26 -0
- package/dist/{chunk-420vamtq.js → chunk-cfbp6h36.js} +1 -1
- package/dist/{chunk-5zkcs06z.js → chunk-d1hwbcne.js} +1 -1
- package/dist/{chunk-hbv7nxdh.js → chunk-g8e0gb93.js} +1 -1
- package/dist/{chunk-7g20yr9m.js → chunk-gsbd4yph.js} +1 -1
- package/dist/chunk-hhgbhadg.js +76 -0
- package/dist/{chunk-qbm9qrtg.js → chunk-hj714bc0.js} +127 -104
- package/dist/{chunk-njy55zd2.js → chunk-kdpafv9g.js} +1 -1
- package/dist/{chunk-q4hrt6r4.js → chunk-ksd0cxtf.js} +1 -1
- package/dist/{chunk-hwkdy2ez.js → chunk-ksh07whh.js} +1 -1
- package/dist/{chunk-52k9k0w8.js → chunk-mjgch1nt.js} +1 -1
- package/dist/{chunk-zs7xeymy.js → chunk-n466beq9.js} +1 -1
- package/dist/{chunk-094ekgv6.js → chunk-nhp35rk0.js} +2 -2
- package/dist/chunk-pkmw32r0.js +8 -0
- package/dist/chunk-pmtfesmc.js +1 -0
- package/dist/{chunk-phzbecpx.js → chunk-r7dz28wh.js} +1 -1
- package/dist/{chunk-jz59sjzb.js → chunk-r8wmg3fc.js} +1 -1
- package/dist/{chunk-c7e33j6k.js → chunk-rjfq5mqt.js} +1 -1
- package/dist/chunk-v19vaykx.js +157 -0
- package/dist/{chunk-8jwqy5d0.js → chunk-v1c9xwen.js} +1 -1
- package/dist/{chunk-80jc465v.js → chunk-vnpzrswh.js} +1 -1
- package/dist/{chunk-vwn39c84.js → chunk-xcpjsrem.js} +1 -1
- package/dist/{chunk-zszvkp6z.js → chunk-xh33jnv4.js} +1 -1
- package/dist/{chunk-gm59f5pe.js → chunk-zp8pmxw9.js} +1 -1
- package/package.json +2 -2
- package/dist/chunk-5mtjqqav.js +0 -8
- package/dist/chunk-76emdpxa.js +0 -76
- package/dist/chunk-h3ccyfqj.js +0 -1
- package/dist/chunk-hwhz4m2c.js +0 -157
- package/dist/chunk-y5g06jmk.js +0 -24
- package/dist/chunk-yjs7nvr5.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{X as D,Y as F$}from"./chunk-
|
|
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 W5 from"node:fs";import W1 from"node:os";import
|
|
1
|
+
import{X as D,Y as F$}from"./chunk-kdpafv9g.js";import{Z as K4}from"./chunk-esnkk33h.js";import{ba as T1}from"./chunk-r7dz28wh.js";import{ga as m}from"./chunk-v1c9xwen.js";import{Aa as v1,Ba as m$,Ca as j$,Da as m0,Ea as L$,Fa as C1,Ga as y$,ra as l4,sa as r,ua as c0,va as Z$,wa as A,za as W$}from"./chunk-hhgbhadg.js";import{Ia as M1}from"./chunk-c6ts8bd9.js";import{Ma as n9,Na as K$,Oa as N0,Pa as P$,Sa as N$,db as a1,eb as e9,hb as K9}from"./chunk-9syksrkj.js";import{ib as H9,jb as G9,kb as K8,lb as X9}from"./chunk-yddnm9n2.js";import{mb as P8,nb as X$}from"./chunk-nhp35rk0.js";import{rb as I1}from"./chunk-pkmw32r0.js";import{tb as l8,xb as N}from"./chunk-7ycmx7c2.js";import{Bb as M,Cb as I}from"./chunk-set7v1rf.js";import{Db as F0}from"./chunk-j2ag7hh6.js";import{spawn as d2}from"child_process";import{randomUUID as u2}from"crypto";class a{static instance=null;processes=new Map;static getInstance(){if(!a.instance)a.instance=new a;return a.instance}startBackgroundProcess($){let Z=`bash_${u2()}`,J={};for(let[Y,V]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(V!==void 0)J[Y]=V;let W=d2("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 W5 from"node:fs";import W1 from"node:os";import k$ from"node:path";import g2 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
|
|
|
@@ -157,17 +157,17 @@ You are a software architect specializing in implementation planning.
|
|
|
157
157
|
**Risks**:
|
|
158
158
|
- [Potential issue and mitigation]
|
|
159
159
|
|
|
160
|
-
Be thorough but concise. Focus on actionable steps.`},{name:"statusline-setup",description:"Use this agent to configure the user's Claude Code status line setting.",tools:["Read","Edit"]},
|
|
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 X5=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(!W5.existsSync($))return;let J=W5.readdirSync($);for(let W of J){if(!W.endsWith(".md"))continue;let X=
|
|
162
|
+
`)}`}loadFromDirectory($,Z){if(!W5.existsSync($))return;let J=W5.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){X5.warn(`Failed to load subagent config from ${X}:`,Y)}}}parseConfigFile($,Z){let W=W5.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=g2.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(W1.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(W1.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 X5.debug(`Loaded ${X} subagents from standard locations`),X}loadBuiltinAgents(){for(let $ of J5)this.subagents.set($.name,{...$,model:$.model||"inherit",source:"builtin"});X5.debug(`Loaded ${J5.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(W1.homedir(),".claude","agents");return k$.join(N(),".claude","agents")}static getBladeAgentsDir($){if($==="user")return k$.join(W1.homedir(),".blade","agents");return k$.join(N(),".blade","agents")}}var P=new m8;import*as p9 from"os";import*as d9 from"path";import m2 from"fs/promises";import c2 from"path";var c8=M("General");async function X1($){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=c2.resolve(l8(),Z),V=await m2.readFile(Y,"utf-8"),B=JSON.parse(V);J=B.mcpServers||B}let X={...L$(),...J};Z$().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 e2 from"path";import*as u from"node:fs/promises";import*as o$ from"node:path";import{execSync as l2}from"node:child_process";import*as Y5 from"node:os";import*as n$ from"node:path";function i2($){return n$.resolve($).replace(/[/\\]/g,"-").replace(/:/g,"_")}function i8($){let Z=$.replace(/_/g,":");if(Z.startsWith("-"))Z="/"+Z.slice(1);return Z.replace(/-/g,"/")}function r$($){let Z=Y5.homedir(),J=i2($);return n$.join(Z,".blade","projects",J)}function J$($,Z){return n$.join(r$($),`${Z}.jsonl`)}function a8($){try{return l2("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function s$(){return n$.join(Y5.homedir(),".blade")}async function n8(){let{readdir:$}=await import("node:fs/promises");try{let Z=n$.join(s$(),"projects");return(await $(Z,{withFileTypes:!0})).filter((W)=>W.isDirectory()).map((W)=>W.name)}catch{return[]}}var r8={enabled:!0,maxIndexLines:200};var a2="memory",s8="MEMORY.md";class b${memoryDir;config;initialized=!1;constructor($,Z,J){if(J)this.memoryDir=J;else{let W=r$($);this.memoryDir=o$.join(W,a2)}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 $=o$.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
|
-
<!-- ${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
|
|
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
|
|
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=o$.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
|
|
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=o$.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=o$.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=o$.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
|
|
@@ -487,15 +487,15 @@ You are in Spec Mode (${r[$]} 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 $6=/<available_skills>\s*<\/available_skills>/;async function t$($={}){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=Y1(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 X6(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
|
|
490
|
+
</spec-mode-reminder>`}var $6=/<available_skills>\s*<\/available_skills>/;async function t$($={}){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=Y1(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 X6(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 b$(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
|
|
|
494
494
|
---
|
|
495
495
|
|
|
496
|
-
`);return z=Z6(z),z=W6(z,Q),{prompt:z,sources:q}}function Z6($){let J=
|
|
496
|
+
`);return z=Z6(z),z=W6(z,Q),{prompt:z,sources:q}}function Z6($){let J=K$().generateAvailableSkillsList();if(!J)return $;return $.replace($6,`<available_skills>
|
|
497
497
|
${J}
|
|
498
|
-
</available_skills>`)}var J6={"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 W6($,Z){let J=Z||"zh-CN",W=J6[J]||J,X=`IMPORTANT: Always respond in ${W}. All your responses must be in ${W}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",X)}async function X6($){let Z=e2.join($,"BLADE.md");try{return(await B4.readFile(Z,"utf-8")).trim()||null}catch{return null}}import U4 from"fast-glob";import*as O0 from"fs/promises";import*as q4 from"path";function
|
|
498
|
+
</available_skills>`)}var J6={"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 W6($,Z){let J=Z||"zh-CN",W=J6[J]||J,X=`IMPORTANT: Always respond in ${W}. All your responses must be in ${W}.`;return $.replace("{{LANGUAGE_INSTRUCTION}}",X)}async function X6($){let Z=e2.join($,"BLADE.md");try{return(await B4.readFile(Z,"utf-8")).trim()||null}catch{return null}}import U4 from"fast-glob";import*as O0 from"fs/promises";import*as q4 from"path";function aW($){return $.endsWith("/")||$.endsWith("\\")}function C0($){return $.replace(/\\/g,"/").split("/").filter(Boolean)}import*as B1 from"fs/promises";import*as s from"path";var Q4=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class e$ extends Error{code;constructor($,Z){super($);this.code=Z;this.name="PathSecurityError"}}class K1{static normalize($,Z){let J=s.isAbsolute($)?$:s.resolve(Z,$),W=s.normalize(J),X=s.normalize(Z);if(!W.startsWith(X))throw new e$(`Path outside workspace: ${$} (resolved to ${W}, workspace: ${X})`,"PATH_OUTSIDE_WORKSPACE");return W}static checkRestricted($){let Z=$.split(s.sep);for(let J of Q4)if(Z.includes(J))throw new e$(`Access denied: "${J}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new e$(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,Z){this.checkTraversal($);let J=this.normalize($,Z);this.checkRestricted(J);try{await B1.access(J)}catch(W){throw new e$(`Path not found: ${$}`,"PATH_NOT_FOUND")}return J}static async resolveSymlink($,Z){try{let J=await B1.realpath($),W=s.normalize(Z);if(!J.startsWith(W))throw new e$(`Symlink points outside workspace: ${$} -> ${J}`,"SYMLINK_OUTSIDE_WORKSPACE");return J}catch(J){if(J instanceof e$)throw J;return $}}static getRelativePath($,Z){return s.relative(Z,$)}static isWithinWorkspace($,Z){let J=s.normalize($),W=s.normalize(Z);return J.startsWith(W)}static isRestricted($){let Z=$.split(s.sep);return Q4.some((J)=>Z.includes(J))}}class Q1{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 U1($){return $ instanceof Map}class I0{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(!Q1.hasAtMentions($))return[];let Z=Q1.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 K1.validatePath($.path,this.options.cwd),J=await K1.resolveSymlink(Z,this.options.cwd);if((await O0.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 O0.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 O0.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(`
|
|
@@ -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 f9 from"os";import*as h9 from"path";import{basename as B6,extname as K6}from"path";import{z as H1}from"zod";import{spawn as V6}from"child_process";import*as z$ from"fs/promises";class I${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 V5=new I$;function z0(){return V5}function q1($){V5=$}function H4(){V5=new I$}var B$=M("Agent");class B5{connection;sessionId;capabilities;fallback;constructor($,Z,J,W=new I$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=W}async readTextFile($){if(!this.capabilities.readTextFile)return B$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return B$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return B$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return B$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{B$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){return B$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${J}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return B$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),B$.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 B$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=Y6(J);return B$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return B$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return B$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return B$.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 Y6($){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 L$=M("Agent");class K5{async execute($,Z){return new Promise((J)=>{let W=process.platform==="win32"?"cmd.exe":"/bin/bash",X=process.platform==="win32"?["/c",$]:["-c",$],Y=V6(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 K5){this.connection=$;this.sessionId=Z;this.fallback=J}async execute($,Z){try{L$.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(()=>L$.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 L$.debug(`[AcpTerminal] Command timed out, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command timed out"};case"aborted":return L$.debug(`[AcpTerminal] Command aborted, killing: ${$}`),Y(!0),{success:!1,stdout:K,stderr:"",exitCode:null,error:"Command was aborted"}}}catch(J){return L$.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 B5($,Z,J.fs):new I$;if(J?.fs)L$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let Y=new G4($,Z);L$.debug(`[AcpServiceContext:${Z}] Using ACP terminal service`),R.sessions.set(Z,{fileSystemService:X,terminalService:Y,connection:$,clientCapabilities:J||null,cwd:W}),R.currentSessionId=Z,q1(X),L$.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)q1(J.fileSystemService)}}L$.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)q1(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 I$}getTerminalService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.terminalService}return new K5}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){L$.warn("[AcpServiceContext] Failed to send tool update:",B)}}}function F4(){return R.getInstance().getTerminalService()}function S$(){return R.getInstance().isAcpMode()}import{isAbsolute as O4}from"path";import{z as u}from"zod";var P={filePath:($)=>u.string().min(1,"File path is required").refine((Z)=>O4(Z),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>u.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Z=300000,J=30000)=>u.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:($)=>u.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>u.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>u.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>u.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:()=>u.string().min(1,"Working directory is required").refine(($)=>O4($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>u.record(u.string(),u.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Z)=>{let J=u.enum($);return Z?J.default(Z):J},flag:($)=>u.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>u.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>u.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:($)=>u.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>u.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>u.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>u.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)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 f9 from"os";import*as h9 from"path";import{basename as B6,extname as K6}from"path";import{z as H1}from"zod";import{spawn as V6}from"child_process";import*as z$ from"fs/promises";class I${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 V5=new I$;function z0(){return V5}function q1($){V5=$}function H4(){V5=new I$}var Q$=M("Agent");class B5{connection;sessionId;capabilities;fallback;constructor($,Z,J,W=new I$){this.connection=$;this.sessionId=Z;this.capabilities=J;this.fallback=W}async readTextFile($){if(!this.capabilities.readTextFile)return Q$.debug(`[AcpFileSystem] readTextFile fallback: ${$}`),this.fallback.readTextFile($);try{return Q$.debug(`[AcpFileSystem] readTextFile via ACP: ${$}`),(await this.connection.readTextFile({path:$,sessionId:this.sessionId})).content}catch(Z){return Q$.warn(`[AcpFileSystem] readTextFile ACP failed, fallback: ${Z}`),this.fallback.readTextFile($)}}async writeTextFile($,Z){if(!this.capabilities.writeTextFile)return Q$.debug(`[AcpFileSystem] writeTextFile fallback: ${$}`),this.fallback.writeTextFile($,Z);try{Q$.debug(`[AcpFileSystem] writeTextFile via ACP: ${$}`),await this.connection.writeTextFile({path:$,content:Z,sessionId:this.sessionId})}catch(J){return Q$.warn(`[AcpFileSystem] writeTextFile ACP failed, fallback: ${J}`),this.fallback.writeTextFile($,Z)}}async exists($){if(!this.capabilities.readTextFile)return Q$.debug(`[AcpFileSystem] exists fallback to local: ${$}`),this.fallback.exists($);try{return await this.connection.readTextFile({path:$,sessionId:this.sessionId}),Q$.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 Q$.debug(`[AcpFileSystem] exists(${$}): false (ACP: not found)`),!1;let Y=Y6(J);return Q$.warn(`[AcpFileSystem] exists(${$}): assuming exists due to ${Y} error`,{error:String(Z),errorType:Y,filePath:$}),!0}}async readBinaryFile($){return Q$.debug(`[AcpFileSystem] readBinaryFile fallback: ${$}`),this.fallback.readBinaryFile($)}async stat($){return Q$.debug(`[AcpFileSystem] stat fallback: ${$}`),this.fallback.stat($)}async mkdir($,Z){return Q$.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 Y6($){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 K5{async execute($,Z){return new Promise((J)=>{let W=process.platform==="win32"?"cmd.exe":"/bin/bash",X=process.platform==="win32"?["/c",$]:["-c",$],Y=V6(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 K5){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 B5($,Z,J.fs):new I$;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,q1(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)q1(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)q1(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 I$}getTerminalService(){if(R.currentSessionId){let $=R.sessions.get(R.currentSessionId);if($)return $.terminalService}return new K5}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 S$(){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
|
|
541
|
+
`)}return null}import*as D4 from"node:crypto";import{promises as _$}from"node:fs";import*as $0 from"node:path";class S0{sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let Z=s$();this.snapshotDir=$0.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=$0.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=$0.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=$0.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=$0.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=$0.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 U5=D({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:H1.object({file_path:y.filePath({description:"Absolute path of the file to edit"}),old_string:H1.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:H1.string().describe("Replacement string (can be empty)"),replace_all:H1.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=z0(),q=S$(),H;try{if(q)V?.("通过 IDE 读取文件...");H=await U.readTextFile(J)}catch(v){let $$=v;if($$.code==="ENOENT"||$$.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=P$.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 $$=await v.checkExternalModification(J);if($$.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
543
|
Details: ${$$.message}`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:$$.message}}}}if(B&&K)try{let v=new S0({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=Q6(H,W);if(!G.matched){let v=q6(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=U6(H,O);if(F.length>1&&!Y){let v=H.split(`
|
|
544
|
-
`),$$=0,M0=[];for(let
|
|
545
|
-
`),error:{type:"validation_error",message:"old_string is not unique",details:{matches:M0.map((
|
|
544
|
+
`),$$=0,M0=[];for(let B$=0;B$<v.length;B$++){let $5=v[B$],p8=$$,d8=$$+$5.length;for(let Z5 of F)if(Z5>=p8&&Z5<d8){let x2=Math.max(0,B$-1),f2=Math.min(v.length-1,B$+1),h2=v.slice(x2,f2+1).map((p2)=>p2.trim()).join(" ").slice(0,80);M0.push({line:B$+1,column:Z5-p8+1,context:h2})}$$=d8+1}return{success:!1,llmContent:[`[WARN] EDIT PAUSED: old_string matches ${F.length} locations (must be unique).`,"","**Matches found at:**",...M0.map((B$,$5)=>` ${$5+1}. Line ${B$.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:M0.map((B$)=>({line:B$.line,column:B$.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 P$.getInstance().recordFileEdit(J,B,"edit");let L=await U.stat(J),E=w4(H,z,O,X,4),j=B6(J),b=w===1?`替换 1 处匹配到 ${j}`:`替换 ${w} 处匹配到 ${j}`,i={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:{file_path:J,replacements:w,total_matches:F.length},metadata:i}}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=K6($.file_path);return Z?`**/*${Z}`:"**/*"}});function L4($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function Q6($,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 U6($,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 q6($,Z,J){let W=$.split(`
|
|
546
546
|
`),X=W.length,Y=H6($,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(`
|
|
547
547
|
`),U=`String not found in file.
|
|
548
548
|
|
|
@@ -576,15 +576,15 @@ Common issues:
|
|
|
576
576
|
- 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 H6($,Z,J=3){let W=$.split(`
|
|
577
577
|
`),X=Z.split(`
|
|
578
578
|
`);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(`
|
|
579
|
-
`),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=G6(K,Q),q=Math.max(K.length,Q.length);return 1-U/q}function G6($,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 F6,extname as _4}from"path";import{z as O6}from"zod";var q5=D({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:O6.object({file_path:
|
|
580
|
-
`),b=W||0,i=X!==void 0?b+X:j.length,v=j.slice(b,i);F=v.map(($$,M0)=>{let h8=b+M0+1,
|
|
581
|
-
`),z.lines_read=v.length,z.total_lines=j.length,z.start_line=b+1,z.end_line=Math.min(i,j.length)}let w=F6(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 z6($){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 w6($){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 j6}from"fs";import{basename as N6,dirname as D6,extname as L6}from"path";import{z as H5}from"zod";var G5=D({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:H5.object({file_path:
|
|
579
|
+
`),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=G6(K,Q),q=Math.max(K.length,Q.length);return 1-U/q}function G6($,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 F6,extname as _4}from"path";import{z as O6}from"zod";var q5=D({name:"Read",displayName:"File Read",kind:"readonly",isConcurrencySafe:!0,schema:O6.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=z0(),U=S$();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 P$.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=z6(H),O=w6(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(`
|
|
580
|
+
`),b=W||0,i=X!==void 0?b+X:j.length,v=j.slice(b,i);F=v.map(($$,M0)=>{let h8=b+M0+1,B$=$$.length>2000?`${$$.substring(0,2000)}...`:$$;return`${h8.toString().padStart(6)}|${B$}`}).join(`
|
|
581
|
+
`),z.lines_read=v.length,z.total_lines=j.length,z.start_line=b+1,z.end_line=Math.min(i,j.length)}let w=F6(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 z6($){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 w6($){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 j6}from"fs";import{basename as N6,dirname as D6,extname as L6}from"path";import{z as H5}from"zod";var G5=D({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:H5.object({file_path:y.filePath({description:"Absolute file path to write"}),content:H5.string().describe("Content to write"),encoding:y.encoding(),create_directories:H5.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=z0(),q=S$();if(Y){let j=D6(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=P$.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.
|
|
582
582
|
|
|
583
583
|
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 S0({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 j6.writeFile(J,j)}if(B)await P$.getInstance().recordFileEdit(J,B,"write");if(typeof Q.throwIfAborted==="function")Q.throwIfAborted();let F=await U.stat(J),z=X==="utf8"?W.split(`
|
|
584
584
|
`).length:0,w=N6(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?E6(F.size):"unknown"} 到 ${w}`,kind:"edit",oldContent:G||"",newContent:X==="utf8"?W:void 0};return{success:!0,llmContent:{file_path:J,size:F?.size,modified:F?.mtime instanceof Date?F.mtime.toISOString():void 0},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=L6($.file_path);return Z?`**/*${Z}`:"**/*"}});function E6($){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 P0}from"zod";var k4=new Set(["temperature","maxContextTokens","maxOutputTokens","timeout","theme","uiTheme","language","fontSize","debug","autoSaveSessions","maxTurns","disableAllHooks","permissions","hooks","env","mcpServers"]),_6=new Set(["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"]),A6=P0.object({operation:P0.enum(["get","set","list"]).describe("操作类型: get(读取)/ set(设置)/ list(列举可配置项)"),key:P0.string().optional().describe("配置键名,支持点号嵌套(如 hooks.PreToolUse)。"+' get 时用 "*" 获取全部配置'),value:P0.unknown().optional().describe("要设置的值(仅 set 操作需要)"),scope:P0.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 R6($){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(`
|
|
585
|
-
`)}var F5=D({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:A6,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=
|
|
585
|
+
`)}var F5=D({name:"ConfigTool",displayName:"Config",kind:"execute",isConcurrencySafe:!1,schema:A6,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=W$();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(_6.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 y$().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:R6(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 O5=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 b$(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:
|
|
586
586
|
${V.map((Q)=>`- ${Q.name}.md (${Q.size} bytes, updated ${Q.lastModified.toISOString()})`).join(`
|
|
587
|
-
`)}`,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 G1}from"zod";var k6=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],z5=D({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:G1.object({topic:G1.string().describe('Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'),content:G1.string().describe("Content to write to the memory file"),mode:G1.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 k6)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
|
|
587
|
+
`)}`,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 G1}from"zod";var k6=[/password\s*[:=]/i,/token\s*[:=]/i,/secret\s*[:=]/i,/api[_-]?key\s*[:=]/i,/private[_-]?key/i],z5=D({name:"MemoryWrite",displayName:"Memory Write",kind:"write",isConcurrencySafe:!1,schema:G1.object({topic:G1.string().describe('Topic name to write to (e.g., "debugging", "patterns", "MEMORY" for the index). Without .md extension.'),content:G1.string().describe("Content to write to the memory file"),mode:G1.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 k6)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 b$(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 F1 from"fs/promises";import{z as w0}from"zod";var w5=D({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",isConcurrencySafe:!1,schema:w0.object({notebook_path:w0.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:w0.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:w0.string().describe("The new source for the cell"),cell_type:w0.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:w0.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 F1.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
588
|
`).map((H,G,O)=>G<O.length-1?H+`
|
|
589
589
|
`: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(`
|
|
590
590
|
`).map((G,O,F)=>O<F.length-1?G+`
|
|
@@ -713,16 +713,16 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
713
713
|
`+(W.feedback||"No specific feedback provided.")+`
|
|
714
714
|
|
|
715
715
|
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.
|
|
716
|
-
Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import h6 from"fast-glob";import{stat as p6}from"node:fs/promises";import{join as d6,resolve as
|
|
716
|
+
Proceeding with implementation.`,metadata:{approved:null,summary:"退出 Plan 模式(非交互)"}}}});import h6 from"fast-glob";import{stat as p6}from"node:fs/promises";import{join as d6,resolve as u6}from"path";import{z as z1}from"zod";import{existsSync as M6,readFileSync as v6}from"node:fs";import{readFile as C6}from"node:fs/promises";import{dirname as I6,join as C4}from"node:path";import S6 from"fast-glob";import{LRUCache as P6}from"lru-cache";import y0 from"picomatch";var Z0=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],y6=["*.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 x6($){if(!M6($))return{patterns:[],negatePatterns:[]};try{let Z=v6($,"utf-8"),J=[],W=[];for(let X of Z.split(`
|
|
717
717
|
`)){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 P6({max:100,ttl:30000,updateAgeOnGet:!0});async function f6($,Z){let J=[...Z0.map((K)=>`${K}/**`),...Z?.scanIgnore??[]],W=`${$}|${J.join(",")}`,X=v4.get(W);if(X)return X;let Y=await S6("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:J});Y.sort((K,Q)=>C0(K).length-C0(Q).length);let V=[];for(let K of Y){let Q=I6(K).replace(/\\/g,"/"),U=Q==="."?"":Q,H=(await C6(C4($,K),"utf-8")).split(`
|
|
718
|
-
`);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 O1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new O1({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:W=!0,gitignoreScanMode:X="root",customScanIgnore:Y=[],cacheTTL:V}=$;if(W&&X==="recursive"){let B=await f6(J,{scanIgnore:Y,cacheTTL:V});for(let K of B)if(Z.orderedRules.push({type:K.type,matcher:y0(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=[...Z0.map((K)=>`${K}/**`),...Z0,...y6];Y.push(...B);for(let K of B)this.orderedRules.push({type:"ignore",matcher:y0(K,{dot:!0})})}if(J){let B=C4(Z,".gitignore"),{patterns:K,negatePatterns:Q}=x6(B);for(let U of K)this.orderedRules.push({type:"ignore",matcher:y0(U,{dot:!0})}),Y.push(U);for(let U of Q)this.orderedRules.push({type:"negate",matcher:y0(U,{dot:!0})}),V.push(U)}Y.push(...X);for(let B of X)this.orderedRules.push({type:"ignore",matcher:y0(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 L5($){let Z=Error($);return Z.name="AbortError",Z}var E5=D({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:z1.object({pattern:
|
|
718
|
+
`);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 O1{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Z=new O1({...$,useGitignore:!1}),{cwd:J=N(),useGitignore:W=!0,gitignoreScanMode:X="root",customScanIgnore:Y=[],cacheTTL:V}=$;if(W&&X==="recursive"){let B=await f6(J,{scanIgnore:Y,cacheTTL:V});for(let K of B)if(Z.orderedRules.push({type:K.type,matcher:y0(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=[...Z0.map((K)=>`${K}/**`),...Z0,...y6];Y.push(...B);for(let K of B)this.orderedRules.push({type:"ignore",matcher:y0(K,{dot:!0})})}if(J){let B=C4(Z,".gitignore"),{patterns:K,negatePatterns:Q}=x6(B);for(let U of K)this.orderedRules.push({type:"ignore",matcher:y0(U,{dot:!0})}),Y.push(U);for(let U of Q)this.orderedRules.push({type:"negate",matcher:y0(U,{dot:!0})}),V.push(U)}Y.push(...X);for(let B of X)this.orderedRules.push({type:"ignore",matcher:y0(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 L5($){let Z=Error($);return Z.name="AbortError",Z}var E5=D({name:"Glob",displayName:"File Pattern Match",kind:"readonly",isConcurrencySafe:!0,schema:z1.object({pattern:y.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:z1.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:z1.boolean().default(!1).describe("Include directories in results"),case_sensitive:z1.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=u6(W);try{if(!(await p6(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 O1.create({cwd:Q,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:q,wasTruncated:H}=await g6(Q,J,{maxResults:X,includeDirectories:Y,caseSensitive:V,signal:K},U),G=m6(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}"`}:
|
|
719
719
|
|
|
720
720
|
`+G.map((w)=>`- ${w.relative_path}`).join(`
|
|
721
721
|
`)+`
|
|
722
722
|
|
|
723
|
-
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
|
|
723
|
+
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 g6($,Z,J,W){let X=W.getIgnorePatterns(),Y=[],V=!1;return await new Promise((B,K)=>{if(J.signal.aborted){K(L5("文件搜索被用户中止"));return}let Q=h6.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(L5("文件搜索被用户中止"));return}if(Y.length>=J.maxResults){G();return}let z=F.path.replace(/\\/g,"/"),w=d6($,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(L5("文件搜索被用户中止"))},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 m6($){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 A5,spawn as R5}from"child_process";import{existsSync as _5}from"fs";import{readdir as c6,readFile as l6}from"fs/promises";import{join as i6,relative as a6}from"path";import n6 from"picomatch";import{z as x$}from"zod";function r6(){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(_5(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=A5(Z,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(J)return J}catch{}let $=r6();if($&&_5($))return $;try{let Z=F0("@vscode/ripgrep");if(Z?.rgPath&&_5(Z.rgPath))return Z.rgPath}catch{}return null}async function s6($){try{return A5("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function o6(){try{return A5("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function t6($,Z,J,W){let X=I4();if(!X)throw Error("ripgrep not available");return new Promise((Y,V)=>{let B=R5(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 e6($,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=R5("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 $7($,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 Z0)X.push("--exclude-dir="+Y.replace(/^\./,""));return X.push("-e",$,Z),new Promise((Y,V)=>{let B=R5("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 Z7($,Z,J,W){let X=[],Y=new RegExp($,J.caseInsensitive?"gi":"g"),V=await J7(Z,W),B=0;for(let K of V){if(W.throwIfAborted(),S4(K))continue;if(J.glob&&!W7(K,J.glob))continue;try{(await l6(K,"utf-8")).split(`
|
|
724
724
|
`).forEach((q,H)=>{if(Y.test(q))X.push({file_path:a6(Z,K),line_number:H+1,content:q})}),B++}catch(Q){continue}}return{matches:X,totalFiles:B}}async function J7($,Z){let J=[];async function W(X){Z.throwIfAborted();try{let Y=await c6(X,{withFileTypes:!0});for(let V of Y){Z.throwIfAborted();let B=i6(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 Z0)if($.includes(Z))return!0;return!1}function W7($,Z){return n6(Z)($)}function X7($){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 Z0)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 Y7($,Z){if(!$.trim())return[];let J=$.trim().split(`
|
|
725
|
-
`),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=V7(X);if(Y)W.push(Y)}return W;default:return[]}}function V7($){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 k5=D({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:x$.object({pattern:P.pattern({description:"The regular expression pattern to search for in file contents"}),path:x$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:x$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:x$.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:x$.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":x$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":x$.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":P.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":P.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":P.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:P.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:P.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:x$.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=X7({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 t6(v,V,z,F),L="ripgrep"}catch{F?.("[WARN] ripgrep 失败,尝试降级策略..."),w=null}if(!w&&await s6(W))try{F?.("使用 git grep"),w=await e6(J,W,{caseInsensitive:B??!1,glob:X,contextLines:q},z),L="git-grep"}catch{F?.("[WARN] git grep 失败,继续尝试其他策略..."),w=null}if(!w&&o6())try{F?.("使用系统 grep"),w=await $7(J,W,{caseInsensitive:B??!1,contextLines:q},z),L="system-grep"}catch{F?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),w=null}if(!w)F?.("使用纯 JavaScript 搜索实现"),E=(await Z7(J,W,{caseInsensitive:B??!1,glob:X,multiline:O??!1},z)).matches,L="fallback",w={stdout:"",stderr:"",exitCode:0};else E=Y7(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 i={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:{...i,summary:`搜索失败: ${w.stderr}`},error:{type:"execution_error",message:w.stderr}};return{success:!0,llmContent:E,metadata:{...i,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 H7}from"child_process";import{randomUUID as G7}from"crypto";import{z as b5}from"zod";var B7=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"]),K7=/^(LD_.+|DYLD_.+|PATH)$/,P4=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function J0($){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(!B7.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(K7.test(V))break;Z=X}return Z}var Q7=[/^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 f$($){let Z=$,J=!0;while(J){J=!1;for(let W of Q7){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 w1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},W0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},h4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},U7={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},q7=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:w1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:w1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:W0,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:W0},{pattern:/^git\s+(log|diff|show)/i,config:h4},{pattern:/^(ls|dir|tree)\s+/i,config:W0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:W0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:W0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:w1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:w1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:W0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:W0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class x0{static getConfigForCommand($){for(let{pattern:Z,config:J,summaryTemplate:W}of q7)if(Z.test($))return{config:J,summaryTemplate:W};return{config:U7}}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(`
|
|
725
|
+
`),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=V7(X);if(Y)W.push(Y)}return W;default:return[]}}function V7($){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 k5=D({name:"Grep",displayName:"内容搜索",kind:"readonly",isConcurrencySafe:!0,schema:x$.object({pattern:y.pattern({description:"The regular expression pattern to search for in file contents"}),path:x$.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:x$.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:x$.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:x$.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":x$.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":x$.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:x$.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=X7({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 t6(v,V,z,F),L="ripgrep"}catch{F?.("[WARN] ripgrep 失败,尝试降级策略..."),w=null}if(!w&&await s6(W))try{F?.("使用 git grep"),w=await e6(J,W,{caseInsensitive:B??!1,glob:X,contextLines:q},z),L="git-grep"}catch{F?.("[WARN] git grep 失败,继续尝试其他策略..."),w=null}if(!w&&o6())try{F?.("使用系统 grep"),w=await $7(J,W,{caseInsensitive:B??!1,contextLines:q},z),L="system-grep"}catch{F?.("[WARN] 系统 grep 失败,使用纯 JavaScript 实现..."),w=null}if(!w)F?.("使用纯 JavaScript 搜索实现"),E=(await Z7(J,W,{caseInsensitive:B??!1,glob:X,multiline:O??!1},z)).matches,L="fallback",w={stdout:"",stderr:"",exitCode:0};else E=Y7(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 i={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:{...i,summary:`搜索失败: ${w.stderr}`},error:{type:"execution_error",message:w.stderr}};return{success:!0,llmContent:E,metadata:{...i,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 H7}from"child_process";import{randomUUID as G7}from"crypto";import{z as b5}from"zod";var B7=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"]),K7=/^(LD_.+|DYLD_.+|PATH)$/,P4=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function J0($){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(!B7.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(K7.test(V))break;Z=X}return Z}var Q7=[/^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 f$($){let Z=$,J=!0;while(J){J=!1;for(let W of Q7){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 w1={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},W0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},h4={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},U7={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},q7=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:w1,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:w1,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:W0,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:W0},{pattern:/^git\s+(log|diff|show)/i,config:h4},{pattern:/^(ls|dir|tree)\s+/i,config:W0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:W0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:W0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:w1,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:w1,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:W0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:W0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class x0{static getConfigForCommand($){for(let{pattern:Z,config:J,summaryTemplate:W}of q7)if(Z.test($))return{config:J,summaryTemplate:W};return{config:U7}}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(`
|
|
726
726
|
`),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(`
|
|
727
727
|
`);if(Q+=`
|
|
728
728
|
|
|
@@ -739,7 +739,7 @@ ${G}`}let U=Z.summarize&&J?J(Y,W):void 0;if(U)Q+=`
|
|
|
739
739
|
`).length} lines`);if(X.truncated)V.push(`stderr: ${X.originalLines} lines -> ${X.content.split(`
|
|
740
740
|
`).length} lines`);Y=`Output truncated: ${V.join(", ")}`}return{stdout:W.content,stderr:X.content,truncationInfo:Y}}static shouldTruncate($,Z){let{config:J}=this.getConfigForCommand(Z);return $.split(`
|
|
741
741
|
`).length>J.maxLines||$.length>J.maxChars}static getStats($){return{lines:$.split(`
|
|
742
|
-
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var T5=D({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,schema:b5.object({command:
|
|
742
|
+
`).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var T5=D({name:"Bash",displayName:"Bash Command",kind:"execute",isConcurrencySafe:!1,schema:b5.object({command:y.command({description:"Bash command to execute"}),timeout:y.timeout(1000,300000,30000),cwd:b5.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:y.environment(),run_in_background:b5.boolean().default(!1).describe("Run in background (suitable for long-running commands)")}),description:{short:"Execute bash commands in a persistent shell session with optional timeout",long:`Executes bash commands with proper handling and security measures.
|
|
743
743
|
|
|
744
744
|
IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
|
|
745
745
|
|
|
@@ -805,7 +805,7 @@ Dependencies: ${V?.length?V.join(", "):"None"}
|
|
|
805
805
|
|
|
806
806
|
Progress: ${q.completed}/${q.total} tasks (${q.percentage}%)
|
|
807
807
|
|
|
808
|
-
Use AddTask to add more tasks, or use /spec apply to start implementation.`,metadata:{taskId:U?.id,title:J,complexity:X,affectedFiles:Y,dependencies:V,totalTasks:q.total,summary:`添加任务: ${J}`}}}});import{z as v5}from"zod";var
|
|
808
|
+
Use AddTask to add more tasks, or use /spec apply to start implementation.`,metadata:{taskId:U?.id,title:J,complexity:X,affectedFiles:Y,dependencies:V,totalTasks:q.total,summary:`添加任务: ${J}`}}}});import{z as v5}from"zod";var u4=D({name:"EnterSpecMode",displayName:"Enter Spec Mode",kind:"readonly",isConcurrencySafe:!1,schema:v5.object({featureName:v5.string().min(1).describe("The name of the feature/change (used as directory name)"),description:v5.string().min(1).describe("Brief description of what this feature/change does")}),description:{short:"Enter Spec-Driven Development mode for complex features",long:`Use this tool to enter Spec mode when you need to implement a complex feature that benefits from structured planning.
|
|
809
809
|
|
|
810
810
|
## Spec-Driven Development (SDD)
|
|
811
811
|
|
|
@@ -901,7 +901,7 @@ Start by asking the user for more details about their requirements.`,metadata:{a
|
|
|
901
901
|
Proceed with the task using regular workflow. You can use Plan mode for lighter planning, or implement directly if the task is straightforward.`,metadata:{approved:!1,enterSpecMode:!1,summary:"Spec 模式被拒绝"}}}catch(X){return{success:!1,llmContent:`Confirmation error: ${X instanceof Error?X.message:"Unknown error"}`,error:{type:"execution_error",message:"Confirmation flow error"},metadata:{summary:"确认流程出错"}}}return{success:!0,llmContent:`Spec mode requested for "${J}" but no interactive confirmation available.
|
|
902
902
|
|
|
903
903
|
Proceeding with spec creation. Follow the structured workflow:
|
|
904
|
-
1. Requirements -> 2. Design -> 3. Tasks -> 4. Implementation`,metadata:{approved:null,enterSpecMode:!0,featureName:J,description:W,summary:`Spec 模式: ${J}(非交互)`}}}});import{z as C5}from"zod";var
|
|
904
|
+
1. Requirements -> 2. Design -> 3. Tasks -> 4. Implementation`,metadata:{approved:null,enterSpecMode:!0,featureName:J,description:W,summary:`Spec 模式: ${J}(非交互)`}}}});import{z as C5}from"zod";var g4=D({name:"ExitSpecMode",displayName:"Exit Spec Mode",kind:"readonly",isConcurrencySafe:!1,schema:C5.object({archive:C5.boolean().optional().default(!1).describe("If true, archive the spec (mark as done and move to archive)"),summary:C5.string().optional().describe("Optional summary of what was accomplished")}),description:{short:"Exit Spec mode and optionally archive the completed spec",long:`Use this tool to exit Spec-Driven Development mode.
|
|
905
905
|
|
|
906
906
|
## Options
|
|
907
907
|
|
|
@@ -1181,7 +1181,7 @@ Progress: ${Q.completed}/${Q.total} tasks (${Q.percentage}%)`+q,metadata:{taskId
|
|
|
1181
1181
|
- Before marking spec as done
|
|
1182
1182
|
- To get improvement suggestions
|
|
1183
1183
|
`},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**: ${r[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)=>r[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(`
|
|
1184
|
-
`),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=[
|
|
1184
|
+
`),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 D7=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.")}),L7=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(D7).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.')}),E7=A$.object({questions:A$.array(L7).min(1).max(4).describe("Questions to ask the user (1-4 questions)")}),S5=D({name:"AskUserQuestion",displayName:"Ask User Question",kind:"readonly",isConcurrencySafe:!1,schema:E7,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
1185
|
1. Gather user preferences or requirements
|
|
1186
1186
|
2. Clarify ambiguous instructions
|
|
1187
1187
|
3. Get decisions on implementation choices as you work
|
|
@@ -1211,7 +1211,7 @@ Important:
|
|
|
1211
1211
|
<available_skills>
|
|
1212
1212
|
|
|
1213
1213
|
</available_skills>
|
|
1214
|
-
`},async execute($,Z){let{skill:J}=$,W=
|
|
1214
|
+
`},async execute($,Z){let{skill:J}=$,W=K$();if(!W.has(J))return{success:!1,llmContent:`Skill "${J}" not found. Available skills: ${W.getAll().map((B)=>B.name).join(", ")||"none"}`,error:{type:"validation_error",message:`Skill "${J}" is not registered`},metadata:{summary:`Skill 未找到: ${J}`}};let X=await W.loadContent(J);if(!X)return{success:!1,llmContent:`Failed to load skill "${J}" content`,error:{type:"execution_error",message:`Could not read SKILL.md for "${J}"`},metadata:{summary:`加载 Skill 失败: ${J}`}};let Y=_7(X.metadata.name,X.instructions,X.metadata.basePath),V=typeof X.metadata.model==="string"&&X.metadata.model!=="inherit"&&X.metadata.model.trim()!==""?X.metadata.model:void 0;return{success:!0,llmContent:Y,metadata:{summary:`加载 Skill: ${J}`,skillName:J,basePath:X.metadata.basePath,version:X.metadata.version,allowedTools:X.metadata.allowedTools,modelId:V}}}});function _7($,Z,J){return`# Skill: ${$}
|
|
1215
1215
|
|
|
1216
1216
|
You are now operating in the "${$}" skill mode. Follow the instructions below to complete the task.
|
|
1217
1217
|
|
|
@@ -1226,7 +1226,7 @@ ${Z}
|
|
|
1226
1226
|
|
|
1227
1227
|
Remember: Follow the above instructions carefully to complete the user's request.`}import{z as d5}from"zod";import{execSync as A7}from"node:child_process";import t4 from"node:fs";import e4 from"node:path";class x5{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=A7(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"}
|
|
1228
1228
|
${Q}
|
|
1229
|
-
\`\`\``;X=X.replace(Y,q)}}catch{}}return X}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import h5 from"node:fs";import Z9 from"node:os";import
|
|
1229
|
+
\`\`\``;X=X.replace(Y,q)}}catch{}}return X}hasDynamicContent($){return{hasArgs:/\$ARGUMENTS|\$\d/.test($),hasBashEmbeds:/!`[^`]+`/.test($),hasFileRefs:/@[\w./-]+(?:\/[\w./-]+|\.[\w]+)/.test($)}}}import h5 from"node:fs";import Z9 from"node:os";import T$ from"node:path";import R7 from"node:fs";import $9 from"node:path";import k7 from"gray-matter";class f5{parse($,Z,J,W){try{let X=R7.readFileSync($,"utf-8"),{data:Y,content:V}=k7(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 p5{parser=new f5;async discover($){let Z=[],J=[],W=[],X=this.getSearchDirs($);for(let Y of X){if(!h5.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:T$.join(Z,".blade","commands"),source:"user",sourceDir:"blade"},{path:T$.join(Z,".claude","commands"),source:"user",sourceDir:"claude"},{path:T$.join($,".blade","commands"),source:"project",sourceDir:"blade"},{path:T$.join($,".claude","commands"),source:"project",sourceDir:"claude"}]}async scanDirectory($){let Z=[],J=async(W)=>{let X=await h5.promises.readdir(W,{withFileTypes:!0});for(let Y of X){let V=T$.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(!h5.existsSync(J.path))continue;if((await this.scanDirectory(J.path)).length>0)return!0}return!1}getCommandDirs($){let Z=Z9.homedir();return{projectBlade:T$.join($,".blade","commands"),projectClaude:T$.join($,".claude","commands"),userBlade:T$.join(Z,".blade","commands"),userClaude:T$.join(Z,".claude","commands")}}}class d{static instance;commands=new Map;pluginCommands=new Map;loader=new p5;executor=new x5;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
1230
|
|
|
1231
1231
|
`,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}
|
|
1232
1232
|
`;if(X+Q.length>$)break;W+=Q,X+=Q.length,Y++}if(Y<J)W+=`
|
|
@@ -1236,7 +1236,7 @@ ${Q}
|
|
|
1236
1236
|
|
|
1237
1237
|
<available_commands>
|
|
1238
1238
|
${Z}
|
|
1239
|
-
</available_commands>`}var
|
|
1239
|
+
</available_commands>`}var u5=D({name:"SlashCommand",displayName:"Slash Command",kind:"execute",isConcurrencySafe:!1,schema:d5.object({command:d5.string().describe('The command name without the leading slash, e.g., "review-pr" or "commit"'),arguments:d5.string().optional().describe('Arguments to pass to the command, e.g., "123" or "fix bug"')}),description:{short:"Execute a custom slash command within the main conversation",long:`Execute a custom slash command within the main conversation
|
|
1240
1240
|
|
|
1241
1241
|
How slash commands work:
|
|
1242
1242
|
When you use this tool, the command's content (from .blade/commands/ or .claude/commands/) will be processed and returned. The content may include:
|
|
@@ -1274,14 +1274,14 @@ ${Z}
|
|
|
1274
1274
|
|
|
1275
1275
|
---
|
|
1276
1276
|
|
|
1277
|
-
Remember: Follow the above instructions carefully to complete the user's request.`,W}import{z as
|
|
1277
|
+
Remember: Follow the above instructions carefully to complete the user's request.`,W}import{z as g5}from"zod";var m5=D({name:"ToolSearch",displayName:"Tool Search",kind:"readonly",isConcurrencySafe:!0,schema:g5.object({query:g5.string().describe('Search query. Use "select:Read,Edit,Grep" for exact selection, or keywords for fuzzy search.'),max_results:g5.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>
|
|
1278
1278
|
${Y.map(({declaration:B})=>`<function>${JSON.stringify(B)}</function>`).join(`
|
|
1279
1279
|
`)}
|
|
1280
|
-
</functions>`,metadata:{summary:`加载了 ${Y.length} 个工具 schema`}}}});import{nanoid as z9}from"nanoid";import{z as Q0}from"zod";import{nanoid as zZ}from"nanoid";import*as Q9 from"os";import*as U9 from"path";import{EventEmitter as BZ}from"events";import{nanoid as v7}from"nanoid";class c5{name="hook";hookManager;constructor(){this.hookManager=
|
|
1280
|
+
</functions>`,metadata:{summary:`加载了 ${Y.length} 个工具 schema`}}}});import{nanoid as z9}from"nanoid";import{z as Q0}from"zod";import{nanoid as zZ}from"nanoid";import*as Q9 from"os";import*as U9 from"path";import{EventEmitter as BZ}from"events";import{nanoid as v7}from"nanoid";class c5{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_${v7()}`;$._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=C7(X.decision,{reason:X.reason}),X.warning)console.warn(`[Hook Warning] ${X.warning}`)}catch(J){console.error("[HookStage] Error executing hooks:",J)}}}function C7($,Z){return{behavior:$,source:"hook",reason:Z.reason}}import{nanoid as I7}from"nanoid";function S7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}class l5{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_${I7()}`,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
1281
|
|
|
1282
1282
|
---
|
|
1283
1283
|
**Hook Context:**
|
|
1284
|
-
${Y.additionalContext}`}if(Y.modifiedOutput!==void 0){let V=Y.modifiedOutput;if(S7(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 i5=M("Execution");class p${static instance=null;locks=new Map;constructor(){}static getInstance(){if(!p$.instance)p$.instance=new p$;return p$.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){i5.debug(`获取文件锁: ${$}`);try{let J=await Z();return i5.debug(`释放文件锁: ${$}`),J}catch(J){throw i5.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(){p$.instance=null}}var P7={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class T${static instance=null;buckets;constructor($={}){let Z={...P7,...$};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(!T$.instance)T$.instance=new T$;return T$.instance}static resetInstance(){T$.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 f0{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import h0 from"picomatch";class X0{config;constructor($){this.config=$}check($){let Z=X0.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",W=J?String($.params.command).trim():"",X=null;if(J){let Q=J0(f$(W));if(Q!==W)X=`Bash(${Q})`}let Y=null;if(J){let Q=y4(f$(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(!h0.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(h0.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 h0.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(!h0.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 Q$=M("Execution");class a5{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 n5{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=J$.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":Q$.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(Q$.warn(`工具 "${Z.name}" 需要用户确认: ${B.title}`),Q$.warn(`详情: ${B.message}`),B.risks&&B.risks.length>0)Q$.warn(`风险: ${B.risks.join(", ")}`);let K=$.context.confirmationHandler;if(K){Q$.info(`[ConfirmationStage] Requesting confirmation for ${Z.name}`);let Q=await K.requestConfirmation(B);if(Q$.info(`[ConfirmationStage] Confirmation response: approved=${Q.approved}`),$.context.signal?.aborted){Q$.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(Q$.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")Q$.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode (non-interactive environment)");else{Q$.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=X0.abstractPattern(Z);Q$.debug(`保存权限规则: "${J}"`),await y$().appendLocalPermissionAllowRule(J,{immediate:!0});let W=K$();if(W?.permissions)Q$.debug("同步权限配置到 PermissionChecker:",W.permissions),this.permissionChecker.replaceConfig(W.permissions)}catch(J){Q$.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(`
|
|
1284
|
+
${Y.additionalContext}`}if(Y.modifiedOutput!==void 0){let V=Y.modifiedOutput;if(S7(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 i5=M("Execution");class p${static instance=null;locks=new Map;constructor(){}static getInstance(){if(!p$.instance)p$.instance=new p$;return p$.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){i5.debug(`获取文件锁: ${$}`);try{let J=await Z();return i5.debug(`释放文件锁: ${$}`),J}catch(J){throw i5.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(){p$.instance=null}}var P7={readonly:Number.POSITIVE_INFINITY,write:Number.POSITIVE_INFINITY,execute:3};class M${static instance=null;buckets;constructor($={}){let Z={...P7,...$};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(!M$.instance)M$.instance=new M$;return M$.instance}static resetInstance(){M$.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 f0{approvals=new Set;has($){return this.approvals.has($)}add($){this.approvals.add($)}clear(){this.approvals.clear()}}import h0 from"picomatch";class X0{config;constructor($){this.config=$}check($){let Z=X0.buildSignature($),J=$.toolName==="Bash"&&typeof $.params.command==="string",W=J?String($.params.command).trim():"",X=null;if(J){let Q=J0(f$(W));if(Q!==W)X=`Bash(${Q})`}let Y=null;if(J){let Q=y4(f$(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(!h0.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(h0.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 h0.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(!h0.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 U$=M("Execution");class a5{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 n5{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":U$.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(U$.warn(`工具 "${Z.name}" 需要用户确认: ${B.title}`),U$.warn(`详情: ${B.message}`),B.risks&&B.risks.length>0)U$.warn(`风险: ${B.risks.join(", ")}`);let K=$.context.confirmationHandler;if(K){U$.info(`[ConfirmationStage] Requesting confirmation for ${Z.name}`);let Q=await K.requestConfirmation(B);if(U$.info(`[ConfirmationStage] Confirmation response: approved=${Q.approved}`),$.context.signal?.aborted){U$.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(U$.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")U$.warn("[WARN] No ConfirmationHandler; auto-approving in YOLO mode (non-interactive environment)");else{U$.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=X0.abstractPattern(Z);U$.debug(`保存权限规则: "${J}"`),await y$().appendLocalPermissionAllowRule(J,{immediate:!0});let W=W$();if(W?.permissions)U$.debug("同步权限配置到 PermissionChecker:",W.permissions),this.permissionChecker.replaceConfig(W.permissions)}catch(J){U$.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
1285
|
`);if(B.length<=X)return V;return`${B.slice(0,X).join(`
|
|
1286
1286
|
`)}
|
|
1287
1287
|
... (还有 ${B.length-X} 行)`};return`**变更前:**
|
|
@@ -1302,9 +1302,9 @@ ${J}
|
|
|
1302
1302
|
${V}
|
|
1303
1303
|
\`\`\`
|
|
1304
1304
|
|
|
1305
|
-
... (还有 ${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 r5{name="execution";async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}try{let J=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);$.setResult(J)}catch(J){$.abort(`Tool execution failed: ${J.message}`)}}}class s5{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 p0 from"node:path";import{execFile as y7}from"node:child_process";import{existsSync as t5}from"node:fs";import d$ from"node:path";import{promisify as x7}from"node:util";var f7=x7(y7),o5=M("Execution");class
|
|
1306
|
-
${X}`.trim();return{hasErrors:Y!==0&&!V,rawOutput:B,timedOut:V,workspaceRoot:$}}}function h7($,Z){let J=d$.isAbsolute($)?$:d$.resolve(Z,$),W=d$.dirname(J),X=d$.parse(W).root;while(W!==X){if(t5(d$.join(W,"tsconfig.json")))return W;W=d$.dirname(W)}if(t5(d$.join(Z,"tsconfig.json")))return Z;return null}function p7($){let Z=d$.join($,"package.json");if(t5(Z))try{if(F0(Z)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function d7($,Z,J,W){try{let{stdout:X,stderr:Y}=await f7($,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 e5=M("Execution"),
|
|
1307
|
-
`),W=p0.basename(Z),X=p0.isAbsolute(Z)?Z:p0.resolve(Z);return J.filter((Y)=>Y.includes(W)||Y.includes(X))}class Z8{queue;name="auto-verify";constructor($=
|
|
1305
|
+
... (还有 ${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 r5{name="execution";async process($){let Z=$._internal.invocation;if(!Z){$.abort("Pre-execution stage failed; cannot run tool");return}try{let J=await Z.execute($.context.signal??new AbortController().signal,$.context.onProgress,$.context);$.setResult(J)}catch(J){$.abort(`Tool execution failed: ${J.message}`)}}}class s5{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 p0 from"node:path";import{execFile as y7}from"node:child_process";import{existsSync as t5}from"node:fs";import d$ from"node:path";import{promisify as x7}from"node:util";var f7=x7(y7),o5=M("Execution");class u${static instance=null;cacheMs;timeoutMs;runCommand;running=new Map;cache=new Map;constructor($={}){this.cacheMs=$.cacheMs??500,this.timeoutMs=$.timeoutMs??1e4,this.runCommand=$.runCommand??d7}static getInstance(){if(!u$.instance)u$.instance=new u$;return u$.instance}static resetInstance(){u$.instance=null}async verify($,Z){let J=h7($,Z);if(!J)return null;let W=Date.now(),X=this.cache.get(J);if(X&&W-X.at<this.cacheMs)return o5.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 o5.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}=p7($);o5.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}
|
|
1306
|
+
${X}`.trim();return{hasErrors:Y!==0&&!V,rawOutput:B,timedOut:V,workspaceRoot:$}}}function h7($,Z){let J=d$.isAbsolute($)?$:d$.resolve(Z,$),W=d$.dirname(J),X=d$.parse(W).root;while(W!==X){if(t5(d$.join(W,"tsconfig.json")))return W;W=d$.dirname(W)}if(t5(d$.join(Z,"tsconfig.json")))return Z;return null}function p7($){let Z=d$.join($,"package.json");if(t5(Z))try{if(F0(Z)?.scripts?.["type-check"])return{cmd:"bun",args:["run","type-check"]}}catch{}return{cmd:"npx",args:["tsc","--noEmit","--incremental","--tsBuildInfoFile",".blade-tsbuildinfo"]}}async function d7($,Z,J,W){try{let{stdout:X,stderr:Y}=await f7($,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 e5=M("Execution"),u7=new Set(["Edit","Write"]),$8=15;function g7($,Z){let J=$.split(`
|
|
1307
|
+
`),W=p0.basename(Z),X=p0.isAbsolute(Z)?Z:p0.resolve(Z);return J.filter((Y)=>Y.includes(W)||Y.includes(X))}class Z8{queue;name="auto-verify";constructor($=u$.getInstance()){this.queue=$}async process($){if(!u7.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{X=await this.queue.verify(J,W)}catch(U){e5.debug(`[AutoVerify] verify failed: ${U instanceof Error?U.message:String(U)}`);return}if(!X)return;if(X.timedOut){e5.info(`[AutoVerify] type-check timed out in ${X.workspaceRoot}`);return}if(!X.hasErrors||!X.rawOutput.trim())return;let Y=g7(X.rawOutput,J);if(Y.length===0)return;let V=Y.slice(0,$8),B=Y.length>$8?`
|
|
1308
1308
|
... (还有 ${Y.length-$8} 个错误)`:"",K=`
|
|
1309
1309
|
|
|
1310
1310
|
---
|
|
@@ -1320,34 +1320,34 @@ If access is required, add an explicit allow rule in permissions.`};if(Z.result=
|
|
|
1320
1320
|
${V.join(`
|
|
1321
1321
|
`)}
|
|
1322
1322
|
|
|
1323
|
-
Confirm to proceed?`};return Z}}function YZ($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}var VZ=M("Execution");class R1{name="resolve-decision";async process($){let{ruleDecision:Z,hookDecision:J}=$._internal,W=R1.resolve(Z,J);if($._internal.effectiveDecision=W,VZ.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 d0 extends BZ{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals;scheduler;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize||1000,this.sessionApprovals=Z.approvalStore||new f0,this.scheduler=Z.scheduler??(Z.concurrencyLimits?new
|
|
1323
|
+
Confirm to proceed?`};return Z}}function YZ($){return{behavior:$.result==="allow"?"allow":$.result==="deny"?"deny":"ask",source:"rule",reason:$.reason,matchedRule:$.matchedRule}}var VZ=M("Execution");class R1{name="resolve-decision";async process($){let{ruleDecision:Z,hookDecision:J}=$._internal,W=R1.resolve(Z,J);if($._internal.effectiveDecision=W,VZ.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 d0 extends BZ{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals;scheduler;constructor($,Z={}){super();this.registry=$;this.maxHistorySize=Z.maxHistorySize||1000,this.sessionApprovals=Z.approvalStore||new f0,this.scheduler=Z.scheduler??(Z.concurrencyLimits?new M$(Z.concurrencyLimits):M$.getInstance());let J=Z.permissionConfig||{allow:[],ask:[],deny:[]},W=Z.permissionMode??"default",X=new Q8(J,this.sessionApprovals,W);this.stages=[new a5(this.registry),new J8(Z.toolWhitelist,Z.toolBlacklist),X,new c5,new R1,new n5(this.sessionApprovals,X.getPermissionChecker()),new r5,new l5,new Z8,new s5]}async execute($,Z,J){let W=Date.now(),X=this.generateExecutionId(),Y=new X9($,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?()=>p$.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}
|
|
1324
1324
|
|
|
1325
1325
|
${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 KZ}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(`
|
|
1326
|
-
`)}reset(){this.loadedTools=new Set(U8),this.deferredTools.clear()}}class
|
|
1327
|
-
[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 Y0{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 Y0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new Y0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new Y0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new Y0({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 M$ from"node:fs/promises";import*as Y9 from"node:path";import*as b1 from"node:fs";import{createReadStream as HZ}from"node:fs";import*as o from"node:fs/promises";import*as z8 from"node:path";import{createInterface as GZ}from"node:readline";class U${filePath;constructor($){this.filePath=$}async append($){try{await o.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=JSON.stringify($)+`
|
|
1326
|
+
`)}reset(){this.loadedTools=new Set(U8),this.deferredTools.clear()}}class g$ extends KZ{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 g$.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 g$;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 QZ=[/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 UZ($){return QZ.some((Z)=>Z.test($))}function qZ($){if($.supportsThinking!==void 0)return{supportsThinking:$.supportsThinking,thinkingBudget:$.thinkingBudget};return{supportsThinking:UZ($.model),thinkingBudget:void 0}}function k1($){return qZ($).supportsThinking}import*as B9 from"crypto";import{nanoid as V9}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}
|
|
1327
|
+
[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 Y0{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 Y0({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new Y0({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new Y0({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new Y0({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 v$ from"node:fs/promises";import*as Y9 from"node:path";import*as b1 from"node:fs";import{createReadStream as HZ}from"node:fs";import*as o from"node:fs/promises";import*as z8 from"node:path";import{createInterface as GZ}from"node:readline";class q${filePath;constructor($){this.filePath=$}async append($){try{await o.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=JSON.stringify($)+`
|
|
1328
1328
|
`;await o.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,Z),Z}}async appendBatch($){try{await o.mkdir(z8.dirname(this.filePath),{recursive:!0,mode:493});let Z=$.map((J)=>JSON.stringify(J)).join(`
|
|
1329
1329
|
`)+`
|
|
1330
1330
|
`;await o.appendFile(this.filePath,Z,"utf-8")}catch(Z){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,Z),Z}}async readAll(){try{if(!b1.existsSync(this.filePath))return[];let Z=(await o.readFile(this.filePath,"utf-8")).split(`
|
|
1331
1331
|
`).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(!b1.existsSync(this.filePath)){Z();return}let W=HZ(this.filePath,"utf-8"),X=GZ({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(!b1.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await o.stat(this.filePath),J=(await o.readFile(this.filePath,"utf-8")).split(`
|
|
1332
|
-
`).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 o.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await o.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class w8{projectPath;maxSessions;version;constructor($=N(),Z=100,J=T1()){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=
|
|
1333
|
-
[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 $=r$(this.projectPath);return(await M$.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=Z$(this.projectPath,$),J=new U$(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=Z$(this.projectPath,$);await new U$(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=Z$(this.projectPath,J),Y=await new U$(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 $=r$(this.projectPath);await M$.mkdir($,{recursive:!0,mode:493});let Z=Y9.join($,".health-check");return await M$.writeFile(Z,"test","utf-8"),await M$.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return n8()}}function FZ($){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||s$();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 Y0(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 V9()}generateMessageId(){return V9()}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 B9.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 u0{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 W${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 u$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new d0($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?m0(Z):v$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){this.log(`${Z} ${$.name} (${$.model})`);let J=k1($),W=C1(),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 I1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:this.config.timeout,supportsThinking:X});let Y=this.executionEngine?.getContextManager();this.executionEngine=new u0(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=m0($);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 v1(),m$().length===0)throw Error(`没有可用的模型配置
|
|
1332
|
+
`).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 o.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await o.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class w8{projectPath;maxSessions;version;constructor($=N(),Z=100,J=T1()){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=J$(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 $=r$(this.projectPath);await v$.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,X,Y){try{let V=J$(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:FZ(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=J$(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=J$(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=J$(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=J$(this.projectPath,$),W=await new q$(Z).readAll();return W.length>0?W:null}catch{return null}}async loadSession($){try{let Z=J$(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=J$(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}
|
|
1333
|
+
[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 $=r$(this.projectPath);return(await v$.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Z=J$(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=J$(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=J$(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 $=r$(this.projectPath);await v$.mkdir($,{recursive:!0,mode:493});let Z=Y9.join($,".health-check");return await v$.writeFile(Z,"test","utf-8"),await v$.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return n8()}}function FZ($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}class u0{memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;get persistentStore(){return this.persistent}constructor($={}){let Z=$.storage?.persistentPath||s$();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 Y0(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 V9()}generateMessageId(){return V9()}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 B9.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 g0{chatService;contextManager;memoryAdapter;constructor($,Z){this.chatService=$,this.contextManager=Z||new u0,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 Y${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 g$,Z={...this.config.permissions,...this.runtimeOptions.permissions},J=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new d0($,{permissionConfig:Z,permissionMode:J,maxHistorySize:1000,toolWhitelist:this.runtimeOptions.toolWhitelist,toolBlacklist:this.runtimeOptions.toolBlacklist})}resolveModelConfig($){let Z=$&&$!=="inherit"?$:void 0,J=Z?m0(Z):j$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){this.log(`${Z} ${$.name} (${$.model})`);let J=k1($),W=C1(),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 I1({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 g0(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=m0($);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 v1(),m$().length===0)throw Error(`没有可用的模型配置
|
|
1334
1334
|
|
|
1335
1335
|
`+`请先使用以下命令添加模型:
|
|
1336
1336
|
`+` /model add
|
|
1337
1337
|
|
|
1338
1338
|
`+`或运行初始化向导:
|
|
1339
|
-
`+" /init");let J=
|
|
1339
|
+
`+" /init");let J=W$();if(!J)throw Error("配置未初始化,请确保应用已正确启动");M1.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 Y$(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=W$(),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 Y$($.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 I0({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 y$().setPermissionMode(Q);let q={...Z,permissionMode:Q},H=W;if(U){let G=`
|
|
1340
1340
|
|
|
1341
1341
|
<approved-plan>
|
|
1342
1342
|
${U}
|
|
1343
1343
|
</approved-plan>
|
|
1344
1344
|
|
|
1345
1345
|
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(`
|
|
1346
|
-
`),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-
|
|
1346
|
+
`),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-ksd0cxtf.js");return W(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){k.debug("Processing Plan mode message...");let{prompt:W}=await t$({projectPath:N(),mode:"plan",includeEnvironment:!0,language:this.config.language}),X;if(typeof $==="string")X=v0($);else{let Y=$.filter((V)=>V.type==="text");if(Y.length>0){let V=Y[0];X=$.map((B)=>B===V?{type:"text",text:v0(V.text)}:B)}else X=[{type:"text",text:v0("")},...$]}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=Y1(Y,V),K,Q=Y?.phase||"init";if(typeof $==="string")K=`${V1(Q)}
|
|
1347
1347
|
|
|
1348
1348
|
${$}`;else{let U=$.filter((q)=>q.type==="text");if(U.length>0){let q=U[0];K=$.map((H)=>H===q?{type:"text",text:`${V1(Q)}
|
|
1349
1349
|
|
|
1350
|
-
${q.text}`}:H)}else K=[{type:"text",text:V1(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 t$({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 K9(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 t$({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 S1({sessionId:"default",configDir:U9.join(Q9.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 X1(this.runtimeOptions.mcpConfig);let $=
|
|
1350
|
+
${q.text}`}:H)}else K=[{type:"text",text:V1(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 t$({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 K9(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 t$({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 S1({sessionId:"default",configDir:U9.join(Q9.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 X1(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 N0({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(`
|
|
1351
1351
|
`);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+=`
|
|
1352
1352
|
|
|
1353
1353
|
<system-reminder>
|
|
@@ -1370,7 +1370,7 @@ Warning: Some files could not be loaded:
|
|
|
1370
1370
|
|
|
1371
1371
|
Warning: Some files could not be loaded:
|
|
1372
1372
|
`,X+=W.join(`
|
|
1373
|
-
`);return X}}import c$ from"node:fs";import OZ from"node:os";import q9 from"node:path";var D0=M("Agent");class V0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=q9.join(OZ.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!V0.instance)V0.instance=new V0;return V0.instance}ensureDirectory(){if(!c$.existsSync(this.sessionsDir))c$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return q9.join(this.sessionsDir,`${Z}.json`)}saveSession($){try{let Z=this.getSessionPath($.id),J=JSON.stringify($,null,2);c$.writeFileSync(Z,J,"utf-8"),this.cache.set($.id,$),D0.debug(`Session saved: ${$.id}`)}catch(Z){D0.warn(`Failed to save session ${$.id}:`,Z)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!c$.existsSync(Z))return;let J=c$.readFileSync(Z,"utf-8"),W=JSON.parse(J);return this.cache.set($,W),W}catch(Z){D0.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(c$.existsSync(Z))c$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return D0.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=c$.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 D0.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)D0.info(`Cleaned up ${W} expired agent sessions`);return W}clearCache(){this.cache.clear()}}var B0=M("Agent");class c{static instance=null;runningAgents=new Map;sessionStore=V0.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)B0.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||zZ(),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)}),B0.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 P1.create({sessionId:$,modelId:q});let H=await W$.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 j$(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),B0.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}),B0.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){B0.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){B0.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"}),B0.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 wZ}from"nanoid";class j8{config;constructor($){this.config=$}async execute($){let Z=Date.now(),J=$.subagentSessionId??wZ();try{let W=this.buildSystemPrompt($),X=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,Y=await W$.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 j$(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 jZ}from"events";class L0 extends jZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!L0.instance)L0.instance=new L0;return L0.instance}publish($,Z,J){this.emit("event",{sessionId:$,type:Z,properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K0=L0.getInstance();import{basename as l$}from"node:path";function N8($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?l$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?l$(J):"file"}`}case"Read":{let J=Z.file_path;return`Reading ${J?l$(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=l$(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?l$(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?l$(W):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?l$(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 NZ($,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 DZ($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!H9(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(`
|
|
1373
|
+
`);return X}}import c$ from"node:fs";import OZ from"node:os";import q9 from"node:path";var D0=M("Agent");class V0{static instance=null;sessionsDir;cache=new Map;constructor(){this.sessionsDir=q9.join(OZ.homedir(),".blade","agents","sessions"),this.ensureDirectory()}static getInstance(){if(!V0.instance)V0.instance=new V0;return V0.instance}ensureDirectory(){if(!c$.existsSync(this.sessionsDir))c$.mkdirSync(this.sessionsDir,{recursive:!0,mode:493})}getSessionPath($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return q9.join(this.sessionsDir,`${Z}.json`)}saveSession($){try{let Z=this.getSessionPath($.id),J=JSON.stringify($,null,2);c$.writeFileSync(Z,J,"utf-8"),this.cache.set($.id,$),D0.debug(`Session saved: ${$.id}`)}catch(Z){D0.warn(`Failed to save session ${$.id}:`,Z)}}loadSession($){if(this.cache.has($))return this.cache.get($);try{let Z=this.getSessionPath($);if(!c$.existsSync(Z))return;let J=c$.readFileSync(Z,"utf-8"),W=JSON.parse(J);return this.cache.set($,W),W}catch(Z){D0.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(c$.existsSync(Z))c$.unlinkSync(Z);return this.cache.delete($),!0}catch(Z){return D0.warn(`Failed to delete session ${$}:`,Z),!1}}listSessions(){try{let $=c$.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 D0.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)D0.info(`Cleaned up ${W} expired agent sessions`);return W}clearCache(){this.cache.clear()}}var B0=M("Agent");class c{static instance=null;runningAgents=new Map;sessionStore=V0.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)B0.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||zZ(),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)}),B0.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 P1.create({sessionId:$,modelId:q});let H=await Y$.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),B0.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}),B0.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){B0.warn(`Cannot resume agent ${$}: session not found`);return}if(this.isRunning($)){B0.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"}),B0.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 wZ}from"nanoid";class j8{config;constructor($){this.config=$}async execute($){let Z=Date.now(),J=$.subagentSessionId??wZ();try{let W=this.buildSystemPrompt($),X=this.config.model&&this.config.model!=="inherit"?this.config.model:void 0,Y=await Y$.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 jZ}from"events";class L0 extends jZ{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!L0.instance)L0.instance=new L0;return L0.instance}publish($,Z,J){this.emit("event",{sessionId:$,type:Z,properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K0=L0.getInstance();import{basename as l$}from"node:path";function N8($,Z){switch($){case"Write":{let J=Z.file_path;return`Writing ${J?l$(J):"file"}`}case"Edit":{let J=Z.file_path;return`Editing ${J?l$(J):"file"}`}case"Read":{let J=Z.file_path;return`Reading ${J?l$(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=l$(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?l$(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?l$(W):"file";return`LSP ${J} in ${X}`}case"NotebookEdit":{let J=Z.notebook_path;return`Editing notebook: ${J?l$(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 NZ($,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 DZ($,Z){if(!Z?.success)return null;switch($){case"Glob":{if(!H9(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(`
|
|
1374
1374
|
`)}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=l$(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(`
|
|
1375
1375
|
`)}case"Read":{let J=Z.metadata?.content_preview||Z.llmContent;if(typeof J!=="string"||!J)return null;let W=J.split(`
|
|
1376
1376
|
`),X=W.length,Y=3;if(X<=Y+1)return J;return`${W.slice(0,Y).join(`
|
|
@@ -1392,14 +1392,14 @@ Warning: Some files could not be loaded:
|
|
|
1392
1392
|
... (+${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(`
|
|
1393
1393
|
`)}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 F9($,Z){let J=Z.success?"ok":Z.error?"fail":"warn",W=Z.metadata?.summary||(Z.success?"执行成功":"执行失败"),X=NZ($,Z)?DZ($,Z)||void 0:void 0;return{status:J,summary:W,detail:X}}function O9($){let Z={ok:"[OK]",fail:"[FAIL]",warn:"[WARN]"}[$.status];return $.detail?`${Z} ${$.summary}
|
|
1394
1394
|
${$.detail}`:`${Z} ${$.summary}`}function LZ($){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(`
|
|
1395
|
-
`)[0]}function EZ($){return
|
|
1395
|
+
`)[0]}function EZ($){return P.getAllNames().includes($)}function _Z(){let $=P.getAllNames();return $.length>0?$.join(", "):"none (registry not initialized)"}function AZ(){return`
|
|
1396
1396
|
## Task
|
|
1397
1397
|
|
|
1398
1398
|
Launch a new agent to handle complex, multi-step tasks autonomously.
|
|
1399
1399
|
|
|
1400
1400
|
The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
|
|
1401
1401
|
|
|
1402
|
-
${
|
|
1402
|
+
${P.getDescriptionsForPrompt()}
|
|
1403
1403
|
|
|
1404
1404
|
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
1405
1405
|
|
|
@@ -1423,7 +1423,7 @@ Usage notes:
|
|
|
1423
1423
|
- 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
|
|
1424
1424
|
- 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.
|
|
1425
1425
|
- 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.
|
|
1426
|
-
`.trim()}var D8=D({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:Q0.object({subagent_type:Q0.string().refine(EZ,($)=>({message:`Invalid subagent type: "${$}". Available: ${_Z()}`})).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 AZ()},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:z9();try{let q=
|
|
1426
|
+
`.trim()}var D8=D({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,isConcurrencySafe:!1,schema:Q0.object({subagent_type:Q0.string().refine(EZ,($)=>({message:`Invalid subagent type: "${$}". Available: ${_Z()}`})).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 AZ()},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:z9();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 kZ(V,X,H,W,Z);if(Y)return RZ(H,W,X,Z,U);K?.(`启动 ${J} subagent: ${W}`);let G=new j8(H),O=z9(8);c0.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(c0.getState().app.actions.updateSubagentTool(b),Q){if(K0.publish(Q,"subagent.update",{subagentSessionId:U,toolName:b}),"function"in j)K0.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;K0.publish(Q,"subagent.tool.result",{subagentSessionId:U,toolCallId:j.id,toolName:j.function.name,success:!E.result.error,summary:E.result.metadata?.summary,output:O9(F9(j.function.name,E.result)),metadata:E.result.metadata});break}case"content_delta":{if(Q)K0.publish(Q,"subagent.delta",{subagentSessionId:U,delta:E.delta});break}case"thinking_delta":{if(Q)K0.publish(Q,"subagent.thinking.delta",{subagentSessionId:U,delta:E.delta});break}case"stream_end":{if(Q)K0.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},i=Date.now();w=await G.execute(b),L+=Date.now()-i}if(j.warning)console.warn(`[Task] SubagentStop hook warning: ${j.warning}`)}catch(E){console.warn("[Task] SubagentStop hook execution failed:",E)}if(c0.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){c0.getState().app.actions.completeSubagentProgress(!1);let H=q,G=LZ(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 RZ($,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 kZ($,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 y1}from"zod";var L8=D({name:"TaskOutput",displayName:"Task Output",kind:"readonly",isConcurrencySafe:!0,schema:y1.object({task_id:y1.string().min(1).describe("The task ID to get output from"),block:y1.boolean().default(!0).describe("Whether to wait for completion"),timeout:y1.number().min(0).max(600000).default(30000).describe("Max wait time in ms")}),description:{short:"Retrieves output from a running or completed task",long:`
|
|
1427
1427
|
- Retrieves output from a running or completed task (background shell, agent, or remote session)
|
|
1428
1428
|
- Takes a task_id parameter identifying the task
|
|
1429
1429
|
- Returns the task output along with status information
|
|
@@ -1475,7 +1475,7 @@ Only mark a task completed when it is fully accomplished. If tests are failing,
|
|
|
1475
1475
|
|
|
1476
1476
|
Status progresses: pending -> in_progress -> completed
|
|
1477
1477
|
|
|
1478
|
-
Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function _8($){return[PZ($),yZ($),xZ($),fZ($)]}function PZ($){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:IZ},async execute(W,X){try{let Y=p1(X,Z,J),V=await Y.createTask(W),B=await Y.listTasks(),K=Y.getStats();return h1({llmContent:{task:q0(V),tasks:B.map(q0),stats:K},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:B,stats:K})}catch(Y){return d1(Y,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.subject,abstractPermissionRule:()=>"*"})}function yZ($){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 p1(X,Z,J).getTask(W.taskId);return{success:!0,llmContent:{task:V?q0(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${W.taskId} 不存在`}}}catch(Y){return d1(Y,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function xZ($){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:SZ},async execute(W,X){try{let Y=p1(X,Z,J),V=W.status;if(V==="deleted"){let H=await Y.deleteTask(W.taskId),G=await Y.listTasks(),O=Y.getStats();return h1({llmContent:{success:H,taskId:W.taskId,updatedFields:H?["deleted"]:[],error:H?void 0:"Task not found",tasks:G.map(q0),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 h1({llmContent:{success:B!==null,taskId:W.taskId,task:B?q0(B):null,updatedFields:K,error:B?void 0:"Task not found",statusChange:Q,tasks:U.map(q0),stats:q},summary:B?`更新任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:U,stats:q})}catch(Y){return d1(Y,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function fZ($){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=p1(X,Z,J),V=await Y.listTasks(),B=Y.getStats();return h1({llmContent:{tasks:V.map(q0),stats:B},summary:V.length===0?"暂无任务":`任务列表 (${B.completed}/${B.total} 完成)`,tasks:V,stats:B})}catch(Y){return d1(Y,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function p1($,Z,J){return U0.getInstance($.taskListId||$.sessionId||Z,J)}function h1($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function d1($,Z){let J=$;return{success:!1,llmContent:`Task operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function q0($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as N9 from"os";import*as D9 from"path";import{z as t}from"zod";import*as i$ from"fs/promises";import*as l0 from"path";class q${static instances=new Map;teamsDir;constructor($){this.teamsDir=l0.join($,"teams")}static getInstance($){if(!q$.instances.has($))q$.instances.set($,new q$($));return q$.instances.get($)}static sanitizeName($){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}getTeamFilePath($){return l0.join(this.teamsDir,q$.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 i$.readFile(this.getTeamFilePath($),"utf-8");return hZ(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 i$.mkdir(l0.dirname(Z),{recursive:!0,mode:493}),await i$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await i$.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=q$.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 hZ($){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 pZ=t.object({name:t.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:t.string().min(1).describe("Registered subagent type to launch for this teammate"),description:t.string().min(3).max(100).optional(),prompt:t.string().min(10).describe("Detailed assignment for this teammate")});function R8($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||D9.join(N9.homedir(),".blade");return[dZ({sessionId:Z,configDir:J}),gZ({configDir:J}),uZ({configDir:J})]}function dZ($){return D({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:t.object({team_name:t.string().min(1).describe("Name for the new agent team"),description:t.string().optional().describe("Team description or purpose"),agent_type:t.string().optional().describe("Optional role/type label for the team lead"),members:t.array(pZ).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:aZ(),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{mZ();let W=iZ(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)=>!S.getSubagent(H));if(X.length>0)return g1(`Invalid subagent type(s): ${[...new Set(X)].join(", ")}. Available: ${S.getAllNames().join(", ")||"none"}`,"创建团队失败");let Y=c.getInstance(),V=q$.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=S.getSubagent(H.subagent_type);if(!G)continue;let O=`${q$.sanitizeName(H.name)}@${B.name}`,F=cZ({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:_0(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 gZ($){return D({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:t.object({team_name:t.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=q$.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(_0)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(_0)}}}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:_0(X)},metadata:{summary:`Agent Team ${X.name}: ${L9(X)}`,team:_0(X)}}}catch(J){return k8(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function uZ($){return D({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:t.object({team_name:t.string().min(1).describe("Team name to delete"),kill_running:t.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=q$.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?_0(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 mZ(){if(S.getAllNames().length===0)S.loadFromStandardLocations()}function cZ($){return`
|
|
1478
|
+
Use deleted to permanently remove a task. Read the latest state with TaskGet before making risky updates.`;function _8($){return[PZ($),yZ($),xZ($),fZ($)]}function PZ($){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:IZ},async execute(W,X){try{let Y=p1(X,Z,J),V=await Y.createTask(W),B=await Y.listTasks(),K=Y.getStats();return h1({llmContent:{task:q0(V),tasks:B.map(q0),stats:K},summary:`创建任务 #${V.id}: ${V.subject}`,tasks:B,stats:K})}catch(Y){return d1(Y,"创建任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.subject,abstractPermissionRule:()=>"*"})}function yZ($){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 p1(X,Z,J).getTask(W.taskId);return{success:!0,llmContent:{task:V?q0(V):null},metadata:{summary:V?`读取任务 #${V.id}`:`任务 #${W.taskId} 不存在`}}}catch(Y){return d1(Y,"读取任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function xZ($){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:SZ},async execute(W,X){try{let Y=p1(X,Z,J),V=W.status;if(V==="deleted"){let H=await Y.deleteTask(W.taskId),G=await Y.listTasks(),O=Y.getStats();return h1({llmContent:{success:H,taskId:W.taskId,updatedFields:H?["deleted"]:[],error:H?void 0:"Task not found",tasks:G.map(q0),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 h1({llmContent:{success:B!==null,taskId:W.taskId,task:B?q0(B):null,updatedFields:K,error:B?void 0:"Task not found",statusChange:Q,tasks:U.map(q0),stats:q},summary:B?`更新任务 #${W.taskId}`:`任务 #${W.taskId} 不存在`,tasks:U,stats:q})}catch(Y){return d1(Y,"更新任务失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:(W)=>W.taskId,abstractPermissionRule:()=>"*"})}function fZ($){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=p1(X,Z,J),V=await Y.listTasks(),B=Y.getStats();return h1({llmContent:{tasks:V.map(q0),stats:B},summary:V.length===0?"暂无任务":`任务列表 (${B.completed}/${B.total} 完成)`,tasks:V,stats:B})}catch(Y){return d1(Y,"读取任务列表失败")}},version:"1.0.0",category:"Task tools",tags:["task","management","planning"],extractSignatureContent:()=>"*",abstractPermissionRule:()=>"*"})}function p1($,Z,J){return U0.getInstance($.taskListId||$.sessionId||Z,J)}function h1($){return{success:!0,llmContent:$.llmContent,metadata:{summary:$.summary,tasks:$.tasks,stats:$.stats}}}function d1($,Z){let J=$;return{success:!1,llmContent:`Task operation failed: ${J.message}`,error:{type:"execution_error",message:J.message,details:$},metadata:{summary:Z}}}function q0($){return{id:$.id,subject:$.subject,description:$.description,status:$.status,activeForm:$.activeForm,owner:$.owner,priority:$.priority,blocks:$.blocks,blockedBy:$.blockedBy,metadata:$.metadata}}import*as N9 from"os";import*as D9 from"path";import{z as t}from"zod";import*as i$ from"fs/promises";import*as l0 from"path";class H${static instances=new Map;teamsDir;constructor($){this.teamsDir=l0.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 l0.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 i$.readFile(this.getTeamFilePath($),"utf-8");return hZ(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 i$.mkdir(l0.dirname(Z),{recursive:!0,mode:493}),await i$.writeFile(Z,JSON.stringify({...$,teamFilePath:Z,updatedAt:Date.now()},null,2),"utf-8")}async listTeams(){try{let $=await i$.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 hZ($){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 pZ=t.object({name:t.string().min(1).describe("Human-readable teammate name, e.g. researcher or test-runner"),subagent_type:t.string().min(1).describe("Registered subagent type to launch for this teammate"),description:t.string().min(3).max(100).optional(),prompt:t.string().min(10).describe("Detailed assignment for this teammate")});function R8($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||D9.join(N9.homedir(),".blade");return[dZ({sessionId:Z,configDir:J}),uZ({configDir:J}),gZ({configDir:J})]}function dZ($){return D({name:"TeamCreate",displayName:"Team Create",kind:"readonly",isConcurrencySafe:!1,schema:t.object({team_name:t.string().min(1).describe("Name for the new agent team"),description:t.string().optional().describe("Team description or purpose"),agent_type:t.string().optional().describe("Optional role/type label for the team lead"),members:t.array(pZ).default([]).describe("Initial teammates to launch as background agents")}),description:{short:"Create an agent team and optionally launch teammate subagents",long:aZ(),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{mZ();let W=iZ(Z.members.map((H)=>H.name));if(W)return u1(`Duplicate teammate name: ${W}`,"创建团队失败");let X=Z.members.map((H)=>H.subagent_type).filter((H)=>!P.getSubagent(H));if(X.length>0)return u1(`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=cZ({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:_0(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 uZ($){return D({name:"TeamStatus",displayName:"Team Status",kind:"readonly",isConcurrencySafe:!0,schema:t.object({team_name:t.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(_0)},metadata:{summary:Y.length===0?"暂无 Agent Teams":`Agent Teams: ${Y.length}`,teams:Y.map(_0)}}}let W=await J.loadTeam(Z.team_name);if(!W)return u1(`Team not found: ${Z.team_name}`,"读取团队失败");let X=await A8(J,W);return{success:!0,llmContent:{team:_0(X)},metadata:{summary:`Agent Team ${X.name}: ${L9(X)}`,team:_0(X)}}}catch(J){return k8(J,"读取团队失败")}},version:"1.0.0",category:"Agent Team",tags:["team","status","agents"],extractSignatureContent:(Z)=>Z.team_name||"*",abstractPermissionRule:()=>"*"})}function gZ($){return D({name:"TeamDelete",displayName:"Team Delete",kind:"readonly",isConcurrencySafe:!1,schema:t.object({team_name:t.string().min(1).describe("Team name to delete"),kill_running:t.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 u1(`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?_0(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 mZ(){if(P.getAllNames().length===0)P.loadFromStandardLocations()}function cZ($){return`
|
|
1479
1479
|
You are ${$.memberName}, a teammate in Blade agent team "${$.teamName}".
|
|
1480
1480
|
|
|
1481
1481
|
Team purpose: ${$.teamDescription||"Coordinate parallel agent work"}.
|
|
@@ -1487,7 +1487,7 @@ Work independently on your assignment and return a concise final result for the
|
|
|
1487
1487
|
|
|
1488
1488
|
Assignment:
|
|
1489
1489
|
${$.memberPrompt}
|
|
1490
|
-
`.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=lZ(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 lZ($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function _0($){let Z=c.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":L9($),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 L9($){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 iZ($){let Z=new Set;for(let J of $){let W=
|
|
1490
|
+
`.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=lZ(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 lZ($){switch($.status){case"running":return"running";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled";default:return"unknown"}}function _0($){let Z=c.getInstance();return{name:$.name,description:$.description,status:$.deletedAt?"deleted":L9($),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 L9($){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 iZ($){let Z=new Set;for(let J of $){let W=H$.sanitizeName(J);if(Z.has(W))return J;Z.add(W)}return}function u1($,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 aZ(){return`
|
|
1491
1491
|
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.
|
|
1492
1492
|
|
|
1493
1493
|
When to use:
|
|
@@ -1502,7 +1502,7 @@ Workflow:
|
|
|
1502
1502
|
4. Inspect progress with TeamStatus.
|
|
1503
1503
|
5. Retrieve detailed teammate output with TaskOutput using the member task_output_id.
|
|
1504
1504
|
6. Stop the team with TeamDelete when the work is complete or cancelled.
|
|
1505
|
-
`.trim()}import{z as
|
|
1505
|
+
`.trim()}import{z as V$}from"zod";import{isPlainObject as _9}from"lodash-es";function A9($){if(!_9($))return;let Z=$;return typeof Z.name==="string"?Z.name:void 0}function nZ($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;if(_9($)){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:V$.object({url:V$.string().url().describe("URL to request"),method:V$.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),extract_content:V$.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:V$.object({with_generated_alt:V$.boolean().default(!1).describe("Generate alt text for images"),with_links_summary:V$.boolean().default(!1).describe("Include summary of all links"),wait_for_selector:V$.string().optional().describe("Wait for specific CSS selector to load")}).optional().describe("Jina Reader advanced options (only used when extract_content is true)"),headers:V$.record(V$.string()).optional().describe("Request headers (optional)"),body:V$.string().optional().describe("Request body (optional)"),timeout:y.timeout(1000,120000,30000),follow_redirects:V$.boolean().default(!0).describe("Follow redirects"),max_redirects:V$.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:V$.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
1506
1506
|
- Fetches content from a specified URL and processes it using an AI model
|
|
1507
1507
|
- Takes a URL and a prompt as input
|
|
1508
1508
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -1559,16 +1559,16 @@ Usage notes:
|
|
|
1559
1559
|
IMPORTANT - Use the correct year in search queries:
|
|
1560
1560
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
1561
1561
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
1562
|
-
`},async execute($,Z){let{query:J}=$,W=y9($.allowed_domains),X=y9($.blocked_domains),{updateOutput:Y}=Z,V=Z.signal??new AbortController().signal;Y?.(`Searching: "${J}" (${P9()} providers available)`);try{let{results:B,providerName:K}=await N3(J,G3,V,Y),Q=E3(B,W,X),U=Q.slice(0,F3),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:${_3($.query)}`,abstractPermissionRule:()=>"search:*"});async function A3(){try{return await F$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function S1($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||h9.join(f9.homedir(),".blade"),W=[q5,U5,G5,w5,E5,k5,T5,M5,b8,T8,D8,L8,..._8({sessionId:Z,configDir:J}),...R8({sessionId:Z,configDir:J}),j5,D5,...o4,S5,y5,
|
|
1562
|
+
`},async execute($,Z){let{query:J}=$,W=y9($.allowed_domains),X=y9($.blocked_domains),{updateOutput:Y}=Z,V=Z.signal??new AbortController().signal;Y?.(`Searching: "${J}" (${P9()} providers available)`);try{let{results:B,providerName:K}=await N3(J,G3,V,Y),Q=E3(B,W,X),U=Q.slice(0,F3),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:${_3($.query)}`,abstractPermissionRule:()=>"search:*"});async function A3(){try{return await F$.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function S1($){let Z=$?.sessionId||`session_${Date.now()}`,J=$?.configDir||h9.join(f9.homedir(),".blade"),W=[q5,U5,G5,w5,E5,k5,T5,M5,b8,T8,D8,L8,..._8({sessionId:Z,configDir:J}),...R8({sessionId:Z,configDir:J}),j5,D5,...o4,S5,y5,u5,m5,O5,z5,F5],X=await A3();return[...W,...X]}var H0=M("Agent");class P1{config;options;approvalStore=new f0;baseRegistry=new g$;attachmentCollector;chatService;executionEngine;currentModelId;currentModelMaxContextTokens;initialized=!1;constructor($,Z){this.config=$;this.options=Z;this.attachmentCollector=new I0({cwd:N(),maxFileSize:1048576,maxLines:2000,maxTokens:32000})}static async create($){if(await v1(),m$().length===0)throw Error(`没有可用的模型配置
|
|
1563
1563
|
|
|
1564
1564
|
`+`请先使用以下命令添加模型:
|
|
1565
1565
|
`+` /model add
|
|
1566
1566
|
|
|
1567
1567
|
`+`或运行初始化向导:
|
|
1568
|
-
`+" /init");let J=K$();if(!J)throw Error("配置未初始化,请确保应用已正确启动");M1.getInstance().validateConfig(J);let W=new P1(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,H0.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:v$()?.id;if(Z&&Z!==this.currentModelId)await this.applyModelConfig(this.resolveModelConfig(Z),"切换模型")}createExecutionPipeline($={}){let Z=new u$,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 d0(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?m0(Z):v$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){H0.debug(`${Z} ${$.name} (${$.model})`);let J=k1($),W=C1(),X=J&&W;this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await I1({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:this.currentModelMaxContextTokens,maxOutputTokens:$.maxOutputTokens??this.config.maxOutputTokens,timeout:this.config.timeout,supportsThinking:X});let Y=this.executionEngine?.getContextManager();this.executionEngine=new u0(this.chatService,Y),this.currentModelId=$.id}async validateSystemPromptConfig(){try{await t$({projectPath:N(),includeEnvironment:!1,language:this.config.language})}catch($){H0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let Z=(await S1({sessionId:this.sessionId,configDir:d9.join(p9.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 X1(this.options.mcpConfig);let $=D$();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){H0.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();for(let W of J)this.baseRegistry.registerMcpTool(W)}catch($){H0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(S.getAllNames().length>0)return;try{S.loadFromStandardLocations()}catch($){H0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await N0({cwd:N()})}catch($){H0.warn("Failed to discover skills:",$)}}}import*as H$ from"node:fs/promises";import{homedir as v3}from"node:os";import*as p from"node:path";import a9 from"gray-matter";function u1($,Z){return`${$}:${Z}`}function g9($,Z){return`${$}__${Z}`}import*as m1 from"node:fs/promises";import*as l9 from"node:path";import{z as _}from"zod";var R3=_.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"}),k3=_.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),b3=_.object({name:_.string().min(1,"Author name is required"),email:_.string().email().optional(),url:_.string().url().optional()}),m9=_.object({name:R3,description:_.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:k3,author:b3.optional(),license:_.string().optional(),repository:_.string().url().optional(),homepage:_.string().url().optional(),keywords:_.array(_.string()).optional(),dependencies:_.record(_.string()).optional(),bladeVersion:_.string().optional()}),u9=_.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()}),T3=_.union([_.object({mcpServers:_.record(u9)}),_.record(u9)]);function c9($){return T3.safeParse($)}var M3=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function R0($){for(let{dir:Z,source:J}of M3){let W=l9.join($,Z,"plugin.json");try{await m1.access(W)}catch{continue}try{let X=await m1.readFile(W,"utf-8"),Y=JSON.parse(X),V=m9.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 I.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 i9($){try{return await R0($)!==null}catch{return!1}}class c1{async loadPlugin($,Z,J={}){let W=await R0($);if(!W)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:X,source:Y}=W,V=X.name;I.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 I.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){I.warn(`Failed to load command from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseCommandFile($,Z,J){let W=await H$.readFile($,"utf-8"),{data:X,content:Y}=a9(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=u1(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){I.warn(`Failed to load agent from ${Y}: ${V instanceof Error?V.message:String(V)}`)}return W}async parseAgentFile($,Z,J){let W=await H$.readFile($,"utf-8"),{data:X,content:Y}=a9(W),V=p.relative(Z,$),B=p.basename(V,".md"),K=X.name||B,Q=u1(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 H$.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 n9(B,"project");if(K.success&&K.content){let Q=K.content.metadata.name,U=u1(Z,Q);W.push({originalName:Q,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:V})}}catch(K){I.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 H$.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 H$.readFile(J,"utf-8"),X=JSON.parse(W),Y=c9(X);if(!Y.success){I.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 H$.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 H$.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=v3();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 H$.access($)}catch{return{plugins:J,errors:W}}let X=await H$.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 G0{static instance=null;plugins=new Map;loader=new c1;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!G0.instance)G0.instance=new G0;return G0.instance}static resetInstance(){G0.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),I.info(`Loaded CLI plugin: ${V.manifest.name} from ${Y}`)}catch(V){W.push({path:Y,error:V instanceof Error?V.message:String(V)}),I.warn(`Failed to load CLI plugin from ${Y}: ${V}`)}let X=c1.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,I.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",I.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.status="active",I.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return I.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(`
|
|
1569
|
-
`)}}function C$(){return G0.getInstance()}class M8{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=d.getInstance(),this.hookManager=
|
|
1568
|
+
`+" /init");let J=W$();if(!J)throw Error("配置未初始化,请确保应用已正确启动");M1.getInstance().validateConfig(J);let W=new P1(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,H0.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 g$,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 d0(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?m0(Z):j$();if(!J)throw Error(`模型配置未找到: ${Z??"current"}`);return J}async applyModelConfig($,Z){H0.debug(`${Z} ${$.name} (${$.model})`);let J=k1($),W=C1(),X=J&&W;this.currentModelMaxContextTokens=$.maxContextTokens??this.config.maxContextTokens,this.chatService=await I1({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 g0(this.chatService,Y),this.currentModelId=$.id}async validateSystemPromptConfig(){try{await t$({projectPath:N(),includeEnvironment:!1,language:this.config.language})}catch($){H0.warn("[SessionRuntime] Failed to validate system prompt configuration:",$)}}async registerBuiltinTools(){let Z=(await S1({sessionId:this.sessionId,configDir:d9.join(p9.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 X1(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){H0.warn(`Warning: MCP server "${W}" connection failed:`,Y)}let J=await Z.getAvailableTools();for(let W of J)this.baseRegistry.registerMcpTool(W)}catch($){H0.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(P.getAllNames().length>0)return;try{P.loadFromStandardLocations()}catch($){H0.warn("Failed to load subagents:",$)}}async discoverSkills(){try{await N0({cwd:N()})}catch($){H0.warn("Failed to discover skills:",$)}}}import*as G$ from"node:fs/promises";import{homedir as v3}from"node:os";import*as p from"node:path";import a9 from"gray-matter";function g1($,Z){return`${$}:${Z}`}function u9($,Z){return`${$}__${Z}`}import*as m1 from"node:fs/promises";import*as l9 from"node:path";import{z as _}from"zod";var R3=_.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"}),k3=_.string().regex(/^\d+\.\d+\.\d+(-[\w.]+)?(\+[\w.]+)?$/,{message:"Version must be a valid semantic version (e.g., 1.0.0)"}),b3=_.object({name:_.string().min(1,"Author name is required"),email:_.string().email().optional(),url:_.string().url().optional()}),m9=_.object({name:R3,description:_.string().min(1,"Description is required").max(500,"Description must be at most 500 characters"),version:k3,author:b3.optional(),license:_.string().optional(),repository:_.string().url().optional(),homepage:_.string().url().optional(),keywords:_.array(_.string()).optional(),dependencies:_.record(_.string()).optional(),bladeVersion:_.string().optional()}),g9=_.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()}),T3=_.union([_.object({mcpServers:_.record(g9)}),_.record(g9)]);function c9($){return T3.safeParse($)}var M3=[{dir:".blade-plugin",source:"blade"},{dir:".claude-plugin",source:"claude"}];async function R0($){for(let{dir:Z,source:J}of M3){let W=l9.join($,Z,"plugin.json");try{await m1.access(W)}catch{continue}try{let X=await m1.readFile(W,"utf-8"),Y=JSON.parse(X),V=m9.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 I.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 i9($){try{return await R0($)!==null}catch{return!1}}class c1{async loadPlugin($,Z,J={}){let W=await R0($);if(!W)throw Error(`Not a valid plugin directory: ${$}`);let{manifest:X,source:Y}=W,V=X.name;I.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 I.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){I.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}=a9(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=g1(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){I.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}=a9(W),V=p.relative(Z,$),B=p.basename(V,".md"),K=X.name||B,Q=g1(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 n9(B,"project");if(K.success&&K.content){let Q=K.content.metadata.name,U=g1(Z,Q);W.push({originalName:Q,namespacedName:U,pluginName:Z,metadata:{...K.content.metadata,name:U},path:V})}}catch(K){I.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=c9(X);if(!Y.success){I.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=u9(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=v3();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 G0{static instance=null;plugins=new Map;loader=new c1;initialized=!1;workspaceRoot="";cliPluginDirs=[];constructor(){}static getInstance(){if(!G0.instance)G0.instance=new G0;return G0.instance}static resetInstance(){G0.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),I.info(`Loaded CLI plugin: ${V.manifest.name} from ${Y}`)}catch(V){W.push({path:Y,error:V instanceof Error?V.message:String(V)}),I.warn(`Failed to load CLI plugin from ${Y}: ${V}`)}let X=c1.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,I.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",I.info(`Plugin "${$}" disabled`),!0;return!1}enable($){let Z=this.plugins.get($);if(Z&&Z.status==="inactive")return Z.status="active",I.info(`Plugin "${$}" enabled`),!0;return!1}async refresh(){return I.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(`
|
|
1569
|
+
`)}}function C$(){return G0.getInstance()}class M8{commandRegistry;hookManager;mcpRegistry;constructor(){this.commandRegistry=d.getInstance(),this.hookManager=X$.getInstance(),this.mcpRegistry=F$.getInstance()}clearAllPluginResources(){this.commandRegistry.clearPluginCommands(),K$().clearPluginSkills(),P.clearPluginAgents(),I.debug("Cleared all plugin resources from subsystems")}async integrateAll(){let Z=C$().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)I.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 I.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=K$(),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){I.warn(`Failed to register MCP server "${J}" from plugin "${$.manifest.name}": ${X instanceof Error?X.message:String(X)}`)}return Z}}async function l1(){return new M8().integrateAll()}function i1(){new M8().clearAllPluginResources()}import{execSync as r9}from"node:child_process";import*as e from"node:fs/promises";import{homedir as C3}from"node:os";import*as k0 from"node:path";class s9{userPluginsDir;constructor($){this.userPluginsDir=$||k0.join(C3(),".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 e.mkdir(this.userPluginsDir,{recursive:!0,mode:493});let W=k0.join(this.userPluginsDir,J);try{return await e.access(W),{success:!1,pluginName:J,pluginPath:W,error:`Plugin "${J}" already exists at ${W}. Use /plugins uninstall first.`}}catch{}I.info(`Cloning ${Z} to ${W}...`);try{r9(`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 i9(W))return await e.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 R0(W)}catch(Y){return await e.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 e.rm(W,{recursive:!0,force:!0}),{success:!1,pluginName:J,error:"Invalid plugin manifest: No manifest found"};return I.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=k0.join(this.userPluginsDir,$);try{await e.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}return await e.rm(Z,{recursive:!0,force:!0}),I.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 e.access(this.userPluginsDir),(await e.readdir(this.userPluginsDir,{withFileTypes:!0})).filter((Z)=>Z.isDirectory()).map((Z)=>Z.name)}catch{return[]}}async update($){try{let Z=k0.join(this.userPluginsDir,$);try{await e.access(Z)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" not found at ${Z}`}}let J=k0.join(Z,".git");try{await e.access(J)}catch{return{success:!1,pluginName:$,error:`Plugin "${$}" is not a git repository`}}I.info(`Updating plugin: ${$}...`);try{r9(`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 R0(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 I.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 r0($){if(!v8)v8=new s9($);return v8}import iJ from"fuse.js";import U2 from"node:fs/promises";import q2 from"node:path";import I3 from"node:os";import o9 from"node:path";function S($){if($.acp)return{sendMessage:(Z)=>$.acp.sendMessage(`• ${Z}
|
|
1570
1570
|
|
|
1571
|
-
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>A().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var t9={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=
|
|
1571
|
+
`),sendToolStart:$.acp.sendToolStart,sendToolResult:$.acp.sendToolResult};return{sendMessage:(Z)=>A().addAssistantMessage(Z),sendToolStart:void 0,sendToolResult:void 0}}var t9={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=S(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 管理**
|
|
1572
1572
|
|
|
1573
1573
|
`+`没有找到任何 agent 配置
|
|
1574
1574
|
|
|
@@ -1613,12 +1613,12 @@ IMPORTANT - Use the correct year in search queries:
|
|
|
1613
1613
|
`+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
|
|
1614
1614
|
`+"- `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}\`
|
|
1615
1615
|
|
|
1616
|
-
`+"使用 `/agents help` 查看可用命令";return W.sendMessage(X),{success:!1,error:`Unknown subcommand: ${J}`}}};async function S3($,Z){let J=
|
|
1616
|
+
`+"使用 `/agents help` 查看可用命令";return W.sendMessage(X),{success:!1,error:`Unknown subcommand: ${J}`}}};async function S3($,Z){let J=S(Z);try{let W=W$(),X=j$();if(!W||!X)return{success:!1,error:"配置未初始化"};let Y=Z$().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=a1.countTokens(K,X.model),U=X.maxContextTokens??W.maxContextTokens,q=(Q/U*100).toFixed(1);if(J.sendMessage(`**当前上下文统计**
|
|
1617
1617
|
• 消息数量: ${K.length}
|
|
1618
1618
|
• Token 数量: ${Q.toLocaleString()}
|
|
1619
1619
|
• Token 限制: ${U.toLocaleString()}
|
|
1620
1620
|
• 使用率: ${q}%`),Q<U*0.5)return J.sendMessage(`提示: 当前 token 使用率较低(${q}%),可以暂时不压缩。
|
|
1621
|
-
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let H=await e9.compact(K,{trigger:"manual",modelName:X.model,maxContextTokens:U,apiKey:X.apiKey,baseURL:X.baseUrl});if(H.success){try{if(B)await new
|
|
1621
|
+
系统会在达到 80% 时自动触发压缩。`),{success:!0,message:"无需压缩"};J.sendMessage("**正在压缩上下文...**");let H=await e9.compact(K,{trigger:"manual",modelName:X.model,maxContextTokens:U,apiKey:X.apiKey,baseURL:X.baseUrl});if(H.success){try{if(B)await new u0().saveCompaction(B,H.summary,{trigger:"manual",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(O){console.warn("[/compact] 保存压缩数据失败:",O)}let G=`[OK] **压缩完成!**
|
|
1622
1622
|
|
|
1623
1623
|
**Token 变化**
|
|
1624
1624
|
• 压缩前: ${H.preTokens.toLocaleString()} tokens
|
|
@@ -1635,7 +1635,7 @@ IMPORTANT - Use the correct year in search queries:
|
|
|
1635
1635
|
• 压缩后: ${H.postTokens.toLocaleString()} tokens
|
|
1636
1636
|
|
|
1637
1637
|
由于压缩过程出现错误,已使用简单截断策略。
|
|
1638
|
-
错误信息: ${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 P3={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:S3},$2=P3;function J2($){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 y3($){let Z=F$.getInstance(),J=
|
|
1638
|
+
错误信息: ${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 P3={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:S3},$2=P3;function J2($){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 y3($){let Z=F$.getInstance(),J=L$();if(Object.keys(J).length===0){$.sendMessage(`**MCP 服务器状态**
|
|
1639
1639
|
|
|
1640
1640
|
[WARN] 暂无配置的 MCP 服务器
|
|
1641
1641
|
|
|
@@ -1654,7 +1654,7 @@ IMPORTANT - Use the correct year in search queries:
|
|
|
1654
1654
|
`,J+=`- 服务器: ${Z.size} 个 (${W} 连接, ${X} 断开)
|
|
1655
1655
|
`,J+=`- 可用工具: ${Y} 个
|
|
1656
1656
|
|
|
1657
|
-
`,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function f3($,Z){let J=F$.getInstance(),X=
|
|
1657
|
+
`,J+="使用 `/mcp <server-name>` 查看详细信息\n",J+="使用 `/mcp tools` 查看所有工具",$.sendMessage(J)}async function f3($,Z){let J=F$.getInstance(),X=L$()[Z];if(!X){$.sendMessage(`服务器 "${Z}" 不存在
|
|
1658
1658
|
|
|
1659
1659
|
使用 \`/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)h3($,Z,Y);else Z2($,Z,X)}catch(Y){Z2($,Z,X),$.sendMessage(`
|
|
1660
1660
|
[WARN] 连接失败: ${Y instanceof Error?Y.message:"未知错误"}`)}}function h3($,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}**
|
|
@@ -1692,7 +1692,7 @@ IMPORTANT - Use the correct year in search queries:
|
|
|
1692
1692
|
`,J.headers&&Object.keys(J.headers).length>0)W+=` Headers: ${Object.keys(J.headers).join(", ")}
|
|
1693
1693
|
`;if(J.timeout)W+=` 超时: ${J.timeout}ms
|
|
1694
1694
|
`;W+=`
|
|
1695
|
-
服务器将在 Agent 启动时自动连接`,$.sendMessage(W)}async function p3($){let Z=F$.getInstance(),J=
|
|
1695
|
+
服务器将在 Agent 启动时自动连接`,$.sendMessage(W)}async function p3($){let Z=F$.getInstance(),J=L$();if(Object.keys(J).length===0){$.sendMessage(`**可用的 MCP 工具**
|
|
1696
1696
|
|
|
1697
1697
|
[WARN] 暂无配置的 MCP 服务器
|
|
1698
1698
|
|
|
@@ -1705,7 +1705,7 @@ IMPORTANT - Use the correct year in search queries:
|
|
|
1705
1705
|
|
|
1706
1706
|
`;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+=`
|
|
1707
1707
|
`}Y+=`
|
|
1708
|
-
`}Y+=`**总计:** ${V} 个工具可用`,$.sendMessage(Y)}var d3={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=
|
|
1708
|
+
`}Y+=`**总计:** ${V} 个工具可用`,$.sendMessage(Y)}var d3={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=S(Z);try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await y3(J),{success:!0,message:"MCP 服务器概览已显示"};let W=$[0];if(console.log("[MCP Command] Subcommand:",W),W==="tools")return await p3(J),{success:!0,message:"MCP 工具列表已显示"};return await f3(J,W),{success:!0,message:`服务器 "${W}" 详情已显示`}}catch(W){return{success:!1,error:`显示 MCP 信息失败: ${W instanceof Error?W.message:"未知错误"}`}}}},W2=d3;import{spawn as u3}from"node:child_process";import*as X2 from"node:path";function g3($){return new Promise((Z)=>{let J=process.env.EDITOR||process.env.VISUAL||"vi",W=u3(J,[$],{stdio:"inherit"});W.on("close",(X)=>{Z(X===0)}),W.on("error",()=>{Z(!1)})})}var m3={name:"memory",description:"Manage project auto memory",fullDescription:"查看和管理项目的 Auto Memory(跨会话持久记忆)",usage:"/memory [list|show|edit|clear]",aliases:["mem"],async handler($,Z){let J=S(Z),W=N(),X=new b$(W);switch($[0]||"list"){case"list":{let V=await X.listTopics();if(V.length===0)J.sendMessage(`暂无记忆文件。Agent 在工作过程中会自动记录有价值的项目知识。
|
|
1709
1709
|
|
|
1710
1710
|
`+`记忆目录: ${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(`
|
|
1711
1711
|
`);J.sendMessage(`**项目记忆文件:**
|
|
@@ -1714,7 +1714,7 @@ ${B}
|
|
|
1714
1714
|
|
|
1715
1715
|
`+"使用 `/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:**
|
|
1716
1716
|
|
|
1717
|
-
${B}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",B=X2.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
|
|
1717
|
+
${B}`);return{success:!0,message:"记忆内容已显示"}}case"edit":{let V=$[1]||"MEMORY",B=X2.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 g3(B))J.sendMessage(`[OK] ${V}.md 编辑完成`);else J.sendMessage(`[WARN] 编辑器退出异常。你可以手动编辑:
|
|
1718
1718
|
${B}
|
|
1719
1719
|
|
|
1720
1720
|
`+"设置 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 命令:**
|
|
@@ -1724,9 +1724,9 @@ ${B}
|
|
|
1724
1724
|
`+`/memory edit [topic] — 用编辑器打开记忆文件(默认 MEMORY)
|
|
1725
1725
|
`+"/memory clear — 清空所有记忆"),{success:!0,message:"帮助信息已显示"}}}},Y2=m3;async function c3($,Z){return{success:!0,message:"show_permissions_editor",data:{action:"show_permissions_editor"}}}var l3={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:c3},n1=l3;import{readdir as V2,readFile as B2,rm as i3}from"node:fs/promises";import*as r1 from"node:path";var C8=M("Service");class s0{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=r1.join(s$(),"projects");try{let J=await V2(Z,{withFileTypes:!0});for(let W of J){if(!W.isDirectory())continue;let X=r1.join(Z,W.name),Y=i8(W.name),B=(await V2(X)).filter((K)=>K.endsWith(".jsonl"));for(let K of B){let Q=r1.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 B2($,"utf-8")).trim().split(`
|
|
1726
1726
|
`).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)=>i3(W.filePath,{force:!0}))),J.length}static async loadSessionFromFile($){let W=(await B2($,"utf-8")).trim().split(`
|
|
1727
|
-
`).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=K2(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=K2(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
|
|
1727
|
+
`).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=K2(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=K2(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 J$($,Z)}}function K2($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}var a3={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Z){let J=S(Z),W=A().restoreSession;if($.length>0){let X=$[0];try{let Y=await s0.loadSession(X);if(Y.length===0)return J.sendMessage(`[FAIL] 会话 \`${X}\` 为空或无法加载`),{success:!1,error:"会话为空"};let V=s0.toUISafeMessages(Y);return W(X,V,Y),J.sendMessage(`[OK] 已恢复会话 \`${X}\`
|
|
1728
1728
|
|
|
1729
|
-
共 ${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 s0.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}`}}}},Q2=a3;var n3={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=
|
|
1729
|
+
共 ${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 s0.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}`}}}},Q2=a3;var n3={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Z){let J=S(Z),W=`**可用的 Slash Commands:**
|
|
1730
1730
|
|
|
1731
1731
|
**/init** - 分析当前项目并生成 BLADE.md 配置文件
|
|
1732
1732
|
**/git** - Git 仓库查询和 AI 辅助 (status/log/diff/review/commit)
|
|
@@ -1736,6 +1736,7 @@ ${B}
|
|
|
1736
1736
|
**/clear** - 清除屏幕内容
|
|
1737
1737
|
**/resume** - 恢复历史会话
|
|
1738
1738
|
**/compact** - 手动压缩上下文,生成总结并节省 token
|
|
1739
|
+
**/cost** - 显示当前会话 token 消耗和费用估算
|
|
1739
1740
|
**/memory** - 管理项目 Auto Memory(list/show/edit/clear)
|
|
1740
1741
|
**/version** - 显示 Blade Code 版本信息
|
|
1741
1742
|
**/status** - 显示当前配置状态
|
|
@@ -1754,7 +1755,7 @@ ${B}
|
|
|
1754
1755
|
- 在命令前加上 \`/\` 即可执行 slash command
|
|
1755
1756
|
- 普通消息会发送给 AI 助手处理
|
|
1756
1757
|
- 按 Ctrl+C 退出程序
|
|
1757
|
-
- 按 Ctrl+L 快速清屏`,J.sendMessage(W),{success:!0,message:"帮助信息已显示",content:W}}},r3={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},s3={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let J=
|
|
1758
|
+
- 按 Ctrl+L 快速清屏`,J.sendMessage(W),{success:!0,message:"帮助信息已显示",content:W}}},r3={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Z){return{success:!0,message:"clear_screen"}}},s3={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Z){let J=S(Z),X=`**Blade Code v${T1()}**
|
|
1758
1759
|
|
|
1759
1760
|
**构建信息:**
|
|
1760
1761
|
- Node.js: ${process.version}
|
|
@@ -1765,13 +1766,24 @@ ${B}
|
|
|
1765
1766
|
- 智能 AI 对话
|
|
1766
1767
|
- 项目自动分析
|
|
1767
1768
|
- 自定义系统提示
|
|
1768
|
-
- 多工具集成支持`;return J.sendMessage(X),{success:!0,message:"版本信息已显示"}}},o3={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=
|
|
1769
|
+
- 多工具集成支持`;return J.sendMessage(X),{success:!0,message:"版本信息已显示"}}},o3={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Z){let J=S(Z),{cwd:W}=Z;try{let X=q2.join(W,"BLADE.md"),Y=await U2.access(X).then(()=>!0).catch(()=>!1),V=q2.join(W,"package.json"),B="未知项目",K="未知类型";try{let O=await U2.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=W$(),U=j$(),H=Z$().session.tokenUsage,G=`**当前状态**
|
|
1769
1770
|
|
|
1770
1771
|
**项目信息:**
|
|
1771
1772
|
- 名称: ${B}
|
|
1772
1773
|
- 类型: ${K}
|
|
1773
1774
|
- 路径: ${W}
|
|
1774
1775
|
|
|
1776
|
+
**模型配置:**
|
|
1777
|
+
- 当前模型: ${U?.name??"N/A"} (${U?.model??"N/A"})
|
|
1778
|
+
- Provider: ${U?.provider??"N/A"}
|
|
1779
|
+
- 可用模型数: ${Q?.models?.length??0}
|
|
1780
|
+
|
|
1781
|
+
**会话统计:**
|
|
1782
|
+
- Turn: ${H.turnCount}
|
|
1783
|
+
- Token: ${H.totalInputTokens.toLocaleString()} in / ${H.totalOutputTokens.toLocaleString()} out
|
|
1784
|
+
- 费用: ${H.estimatedCostUsd>0?`$${H.estimatedCostUsd.toFixed(4)}`:"N/A"}
|
|
1785
|
+
- Context: ${H.maxContextTokens>0?`${Math.round((1-H.inputTokens/H.maxContextTokens)*100)}% 剩余`:"N/A"}
|
|
1786
|
+
|
|
1775
1787
|
**配置状态:**
|
|
1776
1788
|
- BLADE.md: ${Y?"[OK] 已配置":"[FAIL] 未配置 (使用 /init 创建)"}
|
|
1777
1789
|
|
|
@@ -1779,7 +1791,7 @@ ${B}
|
|
|
1779
1791
|
- 工作目录: ${N()} (process.cwd: ${process.cwd()})
|
|
1780
1792
|
- Node.js: ${process.version}
|
|
1781
1793
|
|
|
1782
|
-
${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(
|
|
1794
|
+
${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return J.sendMessage(G),{success:!0,message:"状态信息已显示"}}catch(X){return{success:!1,error:`获取状态信息失败: ${X instanceof Error?X.message:"未知错误"}`}}}},t3={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Z){return{success:!0,message:"exit_application"}}},e3={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Z){let J=S(Z),W=W$(),X=j$(),V=Z$().session.messages||[],B=V.map((z)=>({role:z.role,content:z.content})),K=X?.model||"gpt-4",Q=B.length>0?a1.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=`**上下文使用情况**
|
|
1783
1795
|
|
|
1784
1796
|
**当前会话:**
|
|
1785
1797
|
- 消息数量: ${V.length}
|
|
@@ -1793,8 +1805,19 @@ ${!Y?"\n**建议:** 运行 `/init` 命令来创建项目配置文件":""}`;retur
|
|
|
1793
1805
|
|
|
1794
1806
|
**状态:** ${O}
|
|
1795
1807
|
|
|
1796
|
-
使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(F),{success:!0,message:"上下文信息已显示"}}}
|
|
1797
|
-
|
|
1808
|
+
使用 \`/compact\` 可手动压缩上下文`;return J.sendMessage(F),{success:!0,message:"上下文信息已显示"}}},$J={name:"cost",description:"Show session token usage and estimated cost",fullDescription:"显示当前会话的 token 消耗和费用估算",usage:"/cost",aliases:[],async handler($,Z){let J=S(Z),X=Z$().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?`
|
|
1809
|
+
- Cache read: ${X.cacheReadTokens.toLocaleString()} tokens
|
|
1810
|
+
- Cache write: ${X.cacheWriteTokens.toLocaleString()} tokens`:"",K=`**Session Cost Summary**
|
|
1811
|
+
|
|
1812
|
+
- Model: ${Y?.model??"unknown"}
|
|
1813
|
+
- Turns: ${X.turnCount}
|
|
1814
|
+
- Current input: ${X.inputTokens.toLocaleString()} tokens
|
|
1815
|
+
- Current output: ${X.outputTokens.toLocaleString()} tokens
|
|
1816
|
+
- **Total input: ${X.totalInputTokens.toLocaleString()} tokens**
|
|
1817
|
+
- **Total output: ${X.totalOutputTokens.toLocaleString()} tokens**${B}
|
|
1818
|
+
- Context remaining: ${X.maxContextTokens>0?Math.round((1-X.inputTokens/X.maxContextTokens)*100):"?"}%
|
|
1819
|
+
- **Estimated cost: ${V}**`;return J.sendMessage(K),{success:!0,message:"Cost summary displayed"}}},H2={help:n3,clear:r3,version:s3,status:o3,exit:t3,context:e3,cost:$J,permissions:n1,resume:Q2,compact:$2,mcp:W2,memory:Y2,agents:t9};import{execFile as G2,spawn as ZJ}from"child_process";import{promisify as JJ}from"util";var uF=JJ(G2);async function o0($,Z){return new Promise((J)=>{G2("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 WJ($,Z){let{code:J}=await o0($,Z);return J===0}async function R$($,Z){let{stdout:J}=await o0($,Z);return J.trim()}async function I8($){return WJ($,["rev-parse","--is-inside-work-tree"])}async function s1($){return(await R$($,["status","--porcelain"])).length>0}async function gF($){return R$($,["branch","--show-current"])}async function o1($,Z=10){return R$($,["log","-n",String(Z),"--pretty=format:%s"])}async function S8($){let{code:Z,stderr:J}=await o0($,["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 F2($,Z,J=!1,W){let X=["commit","-m",Z];if(J)X.push("--no-verify");if(!W){let{code:Y,stderr:V}=await o0($,X);if(Y!==0)throw Error(V||"Commit failed");return}return new Promise((Y,V)=>{let B=ZJ("git",X,{cwd:$}),K="",Q=(H,G,O)=>{let z=(O+H.toString()).split(`
|
|
1820
|
+
`),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 O2($){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 z2($){if(!$)return null;return`
|
|
1798
1821
|
Git repository status (snapshot at conversation start):
|
|
1799
1822
|
Current branch: ${$.branch}
|
|
1800
1823
|
Main branch (target for PRs): ${$.mainBranch}
|
|
@@ -1807,14 +1830,14 @@ ${$.log||"(no commits)"}
|
|
|
1807
1830
|
|
|
1808
1831
|
Your recent commits:
|
|
1809
1832
|
${$.authorLog||"(no recent commits)"}
|
|
1810
|
-
`.trim()}async function t0($){return
|
|
1833
|
+
`.trim()}async function t0($){return R$($,["diff","--cached","--name-status"])}async function e0($){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 o0($,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)+`
|
|
1811
1834
|
|
|
1812
|
-
[Diff truncated due to size. Total diff size: `+(X.length/1024).toFixed(2)+"KB]";return X}var
|
|
1835
|
+
[Diff truncated due to size. Total diff size: `+(X.length/1024).toFixed(2)+"KB]";return X}var XJ={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 w2(Z);case"log":case"l":return YJ(Z,$[1]);case"diff":case"d":return VJ(Z);case"review":case"r":return BJ(Z);case"commit":case"c":return QJ(Z);case"pre-commit":case"pc":return KJ(Z);default:return w2(Z)}}catch(X){return{success:!1,error:`Git 命令失败: ${X instanceof Error?X.message:"未知错误"}`}}}};async function w2($){let Z=S($),J=await O2({cwd:$.cwd});if(!J)return{success:!1,error:"无法获取 Git 状态"};let W=z2(J);if(W)Z.sendMessage(`\`\`\`
|
|
1813
1836
|
${W}
|
|
1814
|
-
\`\`\``);else Z.sendMessage("无法获取 Git 状态信息");return{success:!0}}async function
|
|
1837
|
+
\`\`\``);else Z.sendMessage("无法获取 Git 状态信息");return{success:!0}}async function YJ($,Z){let J=S($),W=Math.min(Math.max(parseInt(Z||"5",10)||5,1),50),X=await o1($.cwd,W);if(!X)J.sendMessage("暂无提交记录");else J.sendMessage(`**最近 ${W} 条提交:**
|
|
1815
1838
|
\`\`\`
|
|
1816
1839
|
${X}
|
|
1817
|
-
\`\`\``);return{success:!0}}async function
|
|
1840
|
+
\`\`\``);return{success:!0}}async function VJ($){let Z=S($),{cwd:J}=$,W=await t0(J);if(!W)return Z.sendMessage("暂存区为空,没有待提交的改动"),{success:!0};let X=await e0(J),Y=`**暂存文件:**
|
|
1818
1841
|
\`\`\`
|
|
1819
1842
|
${W}
|
|
1820
1843
|
\`\`\`
|
|
@@ -1822,7 +1845,7 @@ ${W}
|
|
|
1822
1845
|
**Diff:**
|
|
1823
1846
|
\`\`\`diff
|
|
1824
1847
|
${X||"(无差异)"}
|
|
1825
|
-
\`\`\``;return Z.sendMessage(Y),{success:!0}}async function
|
|
1848
|
+
\`\`\``;return Z.sendMessage(Y),{success:!0}}async function BJ($){let Z=S($),{cwd:J,signal:W}=$;if(!await s1(J))return Z.sendMessage("没有未提交的改动,无需 Review"),{success:!0};Z.sendMessage("正在分析代码改动...");let X=await t0(J),Y=await e0(J);if(!Y&&!X)return Z.sendMessage("请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let V=await Y$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let B=Z$().session.sessionId,K=`请对以下 Git 改动进行 Code Review。
|
|
1826
1849
|
|
|
1827
1850
|
**暂存文件:**
|
|
1828
1851
|
${X||"(无)"}
|
|
@@ -1838,7 +1861,7 @@ ${Y||"(无差异)"}
|
|
|
1838
1861
|
3. **潜在问题**:指出可能的 bug、安全问题或性能问题
|
|
1839
1862
|
4. **改进建议**:具体的代码改进建议
|
|
1840
1863
|
|
|
1841
|
-
如果改动很好,也请说明优点。保持简洁专业。`,U=(await
|
|
1864
|
+
如果改动很好,也请说明优点。保持简洁专业。`,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 KJ($){let Z=S($),{cwd:J,signal:W}=$;if(!await s1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await t0(J),Y=await e0(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await o1(J,5),B=await Y$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=Z$().session.sessionId,Q=j2(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:**
|
|
1842
1865
|
\`\`\`
|
|
1843
1866
|
${H}
|
|
1844
1867
|
\`\`\`
|
|
@@ -1847,7 +1870,7 @@ ${H}
|
|
|
1847
1870
|
\`\`\`bash
|
|
1848
1871
|
git commit -m "${H.split(`
|
|
1849
1872
|
`)[0]}"
|
|
1850
|
-
\`\`\``),{success:!0}}async function
|
|
1873
|
+
\`\`\``),{success:!0}}async function QJ($){let Z=S($),{cwd:J,signal:W}=$;if(!await s1(J))return Z.sendMessage("没有未提交的改动"),{success:!0};Z.sendMessage("暂存所有改动..."),await S8(J);let X=await t0(J),Y=await e0(J);if(!X)return Z.sendMessage("没有需要提交的改动"),{success:!0};Z.sendMessage("正在生成 commit message...");let V=await o1(J,5),B=await Y$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let K=Z$().session.sessionId,Q=j2(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:**
|
|
1851
1874
|
\`\`\`
|
|
1852
1875
|
${H}
|
|
1853
1876
|
\`\`\``);try{await F2(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 j2($,Z,J){let W=J&&J.trim().length>0;return`请根据以下 Git 改动生成一条 commit message。
|
|
@@ -1871,7 +1894,7 @@ ${J}
|
|
|
1871
1894
|
1. ${W?"严格模仿历史提交的语言和格式风格":"使用英文,遵循 Conventional Commits 格式(feat:, fix:, docs:, refactor:, chore: 等)"}
|
|
1872
1895
|
2. 第一行简明扼要,不超过 72 字符
|
|
1873
1896
|
3. 如有必要,可添加空行后的详细说明
|
|
1874
|
-
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var N2=
|
|
1897
|
+
4. 只输出 commit message 内容,不要其他解释或代码块标记`}var N2=XJ;var UJ={name:"hooks",description:"Manage hook configurations for tool events",fullDescription:`管理 Hook 配置,查看当前启用的 hooks 和执行统计。
|
|
1875
1898
|
|
|
1876
1899
|
子命令:
|
|
1877
1900
|
/hooks - 打开交互式 hooks 管理界面(添加新 hook)
|
|
@@ -1879,16 +1902,16 @@ ${J}
|
|
|
1879
1902
|
/hooks status - 显示 hooks 启用状态和统计
|
|
1880
1903
|
/hooks enable - 启用当前会话的 hooks
|
|
1881
1904
|
/hooks disable - 禁用当前会话的 hooks
|
|
1882
|
-
/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=
|
|
1883
|
-
使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function
|
|
1884
|
-
`)),{success:!0,message:"Hooks status displayed"}}function
|
|
1885
|
-
`)),{success:!0,message:"Hooks config listed"}}var D2=
|
|
1905
|
+
/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 qJ(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 HJ(W);default:return A().addAssistantMessage(`未知子命令: ${J}
|
|
1906
|
+
使用 /hooks 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function qJ($){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(`
|
|
1907
|
+
`)),{success:!0,message:"Hooks status displayed"}}function HJ($){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(`
|
|
1908
|
+
`)),{success:!0,message:"Hooks config listed"}}var D2=UJ;import{existsSync as wJ,readFileSync as jJ}from"fs";import{homedir as NJ}from"os";import{join as DJ}from"path";import{exec as GJ}from"child_process";import{promisify as FJ}from"util";var L2=FJ(GJ);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 L2("code --version"),J=$.trim().split(`
|
|
1886
1909
|
`)[0]||"unknown",W=[];try{let{stdout:X}=await L2("code --list-extensions");W=X.trim().split(`
|
|
1887
|
-
`).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
|
|
1910
|
+
`).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 OJ}from"child_process";import{promisify as zJ}from"util";var t1=zJ(OJ);class $1{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 t1(Z),{success:!0,message:"扩展安装成功"}}catch(J){return{success:!1,message:"安装失败: "+(J instanceof Error?J.message:"未知错误")}}}static async checkVsCode(){try{let{stdout:$}=await t1("code --version");return{id:"vscode",name:"VS Code",version:$.trim().split(`
|
|
1888
1911
|
`)[0]||"unknown"}}catch{return null}}static async checkVsCodeInsiders(){try{let{stdout:$}=await t1("code-insiders --version");return{id:"vscode-insiders",name:"VS Code Insiders",version:$.trim().split(`
|
|
1889
1912
|
`)[0]||"unknown"}}catch{return null}}static async checkCursor(){try{let{stdout:$}=await t1("cursor --version");return{id:"cursor",name:"Cursor",version:$.trim().split(`
|
|
1890
|
-
`)[0]||"unknown"}}catch{return null}}}var E2=NJ(
|
|
1891
|
-
`)}async function
|
|
1913
|
+
`)[0]||"unknown"}}catch{return null}}}var E2=DJ(NJ(),".blade","ide-port");var b0="disconnected",x8=null,f8=null;function LJ(){switch(b0){case"connected":return{type:"info",content:`[OK] 已连接到 ${x8||"IDE"} (端口: ${f8})`};case"connecting":return{type:"info",content:"正在连接..."};default:return{type:"error",content:"未连接到 IDE"}}}function _2(){try{if(wJ(E2)){let $=jJ(E2,"utf-8");return JSON.parse($)}}catch{}return null}function A2(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let Z=_2();if(Z)return Z.port;return null}async function EJ(){let $=[],Z=LJ();$.push(Z.content),$.push(""),$.push("已安装的 IDE:");let J=await $1.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=A2(),Y=_2();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(`
|
|
1914
|
+
`)}async function _J(){let $=A2();if(!$)return`未检测到 IDE 端口
|
|
1892
1915
|
|
|
1893
1916
|
请确保:
|
|
1894
1917
|
1. 已在 VS Code 中安装 Blade Code 插件
|
|
@@ -1906,15 +1929,15 @@ ${J}
|
|
|
1906
1929
|
请检查:
|
|
1907
1930
|
1. VS Code 插件是否正在运行
|
|
1908
1931
|
2. 端口 ${$} 是否正确
|
|
1909
|
-
3. 防火墙设置`}}async function
|
|
1932
|
+
3. 防火墙设置`}}async function AJ(){let $=[];if($.push("安装 Blade Code VS Code 插件"),$.push(""),!await $1.isIdeInstalled("vscode"))return $.push("未检测到 VS Code"),$.push(""),$.push("请先安装 VS Code:"),$.push(" https://code.visualstudio.com/"),$.join(`
|
|
1910
1933
|
`);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(`
|
|
1911
|
-
`)}async function
|
|
1934
|
+
`)}async function RJ(){if(b0==="disconnected")return"[WARN] 当前未连接到任何 IDE";return b0="disconnected",x8=null,f8=null,"[OK] 已断开与 IDE 的连接"}var kJ={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 EJ();break;case"connect":W=await _J();break;case"install":W=await AJ();break;case"disconnect":W=await RJ();break;default:W=`未知的子命令: ${J}
|
|
1912
1935
|
|
|
1913
1936
|
可用命令:
|
|
1914
1937
|
/ide status - 显示连接状态
|
|
1915
1938
|
/ide connect - 连接到 IDE
|
|
1916
1939
|
/ide install - 安装 VS Code 插件
|
|
1917
|
-
/ide disconnect - 断开连接`}return{success:!0,message:W}}},R2=
|
|
1940
|
+
/ide disconnect - 断开连接`}return{success:!0,message:W}}},R2=kJ;import{promises as Z1}from"fs";import*as k2 from"path";var T0=M("Agent"),bJ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Z){try{let{cwd:J,signal:W}=Z,X=S(Z),Y=(O)=>{X.sendMessage(`${O}`)},V=Z$().session.sessionId,B=k2.join(J,"BLADE.md"),K=!1,Q=!1;try{if(K=(await Z1.stat(B)).isFile(),K)Q=(await Z1.readFile(B,"utf-8")).trim().length===0}catch{K=!1}if(K&&!Q){X.sendMessage("[WARN] BLADE.md 已存在。"),X.sendMessage("正在分析现有文件并提供改进建议...");let O=await Y$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let F=`Please analyze the existing BLADE.md file and provide improvement suggestions.
|
|
1918
1941
|
|
|
1919
1942
|
**Important**:
|
|
1920
1943
|
- After each step, briefly describe what you found before proceeding
|
|
@@ -1953,7 +1976,7 @@ ${J}
|
|
|
1953
1976
|
- 具体的改进建议(附带示例)
|
|
1954
1977
|
- 如果需要重大修改,提供完整的改进版本内容
|
|
1955
1978
|
|
|
1956
|
-
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;T0.info(`[/init] Starting agent.chatStream, signal.aborted: ${W?.aborted}`);let w=(await
|
|
1979
|
+
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`;T0.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(T0.info(`[/init] agent.chatStream completed, signal.aborted: ${W?.aborted}`),W?.aborted)return T0.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 Y$.create();if(W?.aborted)return{success:!1,message:"操作已取消"};let q=`Please analyze this codebase and generate BLADE.md content.
|
|
1957
1980
|
|
|
1958
1981
|
**Important**: After each step, briefly describe what you found before proceeding.
|
|
1959
1982
|
|
|
@@ -1999,7 +2022,7 @@ ${J}
|
|
|
1999
2022
|
- Focus on non-obvious insights
|
|
2000
2023
|
- Be concise but comprehensive for complex projects
|
|
2001
2024
|
|
|
2002
|
-
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;T0.info(`[/init] Starting agent.chatStream for new BLADE.md, signal.aborted: ${W?.aborted}`);let G=(await
|
|
2025
|
+
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`;T0.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(T0.info(`[/init] agent.chatStream completed for new BLADE.md, signal.aborted: ${W?.aborted}`),W?.aborted)return T0.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 Z1.writeFile(B,G,"utf-8"),{success:!0,message:"[OK] 已成功生成 BLADE.md 文件"}}catch(J){return{success:!1,error:`初始化失败: ${J instanceof Error?J.message:"未知错误"}`}}}},b2=bJ;var TJ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
|
|
2003
2026
|
管理和切换模型配置
|
|
2004
2027
|
|
|
2005
2028
|
子命令:
|
|
@@ -2017,7 +2040,7 @@ ${J}
|
|
|
2017
2040
|
|
|
2018
2041
|
使用 /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:`请指定要删除的模型名称
|
|
2019
2042
|
用法: /model remove <名称>`};let Y=m$().find((V)=>V.name.toLowerCase().includes(W.toLowerCase()));if(!Y)return{success:!1,message:`未找到匹配的模型配置: ${W}`};try{return await y$().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=m$(),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}
|
|
2020
|
-
使用 /model 查看可用操作`}}}},T2=
|
|
2043
|
+
使用 /model 查看可用操作`}}}},T2=TJ;var MJ={name:"plugins",description:"管理已安装的插件",fullDescription:`管理 Blade Code 插件系统。
|
|
2021
2044
|
|
|
2022
2045
|
子命令:
|
|
2023
2046
|
/plugins - 打开插件管理界面
|
|
@@ -2029,25 +2052,25 @@ ${J}
|
|
|
2029
2052
|
/plugins enable <name> - 启用插件
|
|
2030
2053
|
/plugins disable <name> - 禁用插件
|
|
2031
2054
|
/plugins refresh - 刷新插件列表
|
|
2032
|
-
/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=C$();switch(J){case"":return await
|
|
2033
|
-
使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function
|
|
2055
|
+
/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=C$();switch(J){case"":return await PJ(W),{success:!0,message:"show_plugins_manager",data:{action:"show_plugins_manager"}};case"list":case"ls":return vJ(W);case"info":return CJ(W,$[1]);case"install":case"add":return hJ($[1]);case"uninstall":case"remove":case"rm":return pJ($[1]);case"update":case"upgrade":return dJ($[1]);case"enable":return IJ(W,$[1]);case"disable":return SJ(W,$[1]);case"refresh":return yJ(W);case"stats":return xJ(W);default:return A().addAssistantMessage(`未知子命令: ${J}
|
|
2056
|
+
使用 /plugins 查看帮助`),{success:!1,error:`Unknown subcommand: ${J}`}}}};function vJ($){if($.getAll().length===0)return A().addAssistantMessage(`没有已加载的插件。
|
|
2034
2057
|
|
|
2035
2058
|
`+"使用 `--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(`
|
|
2036
|
-
`)),{success:!0,message:"Plugins listed"}}function
|
|
2037
|
-
`)),{success:!0,message:"Plugin info displayed"}}function
|
|
2038
|
-
`)),{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
|
|
2039
|
-
`)),{success:!0,message:"Stats displayed"}}function
|
|
2059
|
+
`)),{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] 启用":"禁用"}`,`**来源**: ${fJ(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(`
|
|
2060
|
+
`)),{success:!0,message:"Plugin info displayed"}}function IJ($,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 SJ($,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 PJ($){i1(),await $.refresh(),await l1()}async function yJ($){try{i1();let Z=await $.refresh(),J=await l1(),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(`
|
|
2061
|
+
`)),{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 xJ($){let Z=$.getStats(),J=["## 插件统计","","| 指标 | 数量 |","|------|------|",`| 总插件数 | ${Z.total} |`,`| 启用 | ${Z.active} |`,`| 禁用 | ${Z.inactive} |`,`| 命令 | ${Z.commands} |`,`| 技能 | ${Z.skills} |`,`| 代理 | ${Z.agents} |`];return A().addAssistantMessage(J.join(`
|
|
2062
|
+
`)),{success:!0,message:"Stats displayed"}}function fJ($){switch($){case"cli":return"CLI 参数";case"project":return"项目级";case"user":return"用户级";default:return $}}async function hJ($){if(!$)return A().addAssistantMessage("请指定插件 URL: `/plugins install <url>`\n\n"+`支持的格式:
|
|
2040
2063
|
`+"- GitHub 简写: `user/repo`\n"+"- 完整 URL: `https://github.com/user/repo`"),{success:!1,error:"Plugin URL required"};A().addAssistantMessage(`正在安装插件: ${$}...`);let J=await r0().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(`
|
|
2041
|
-
`)),{success:!0,message:`Installed ${J.pluginName}`}}return A().addAssistantMessage(`安装失败: ${J.error}`),{success:!1,error:J.error}}async function
|
|
2064
|
+
`)),{success:!0,message:`Installed ${J.pluginName}`}}return A().addAssistantMessage(`安装失败: ${J.error}`),{success:!1,error:J.error}}async function pJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins uninstall <name>`"),{success:!1,error:"Plugin name required"};let J=await r0().uninstall($);if(J.success)return A().addAssistantMessage(`[OK] 已卸载插件: ${J.pluginName}
|
|
2042
2065
|
|
|
2043
|
-
`+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${J.pluginName}`};return A().addAssistantMessage(`卸载失败: ${J.error}`),{success:!1,error:J.error}}async function
|
|
2044
|
-
`)),{success:!0,message:`Updated ${J.pluginName}`}}return A().addAssistantMessage(`更新失败: ${J.error}`),{success:!1,error:J.error}}var M2=
|
|
2066
|
+
`+"使用 `/plugins refresh` 刷新插件列表。"),{success:!0,message:`Uninstalled ${J.pluginName}`};return A().addAssistantMessage(`卸载失败: ${J.error}`),{success:!1,error:J.error}}async function dJ($){if(!$)return A().addAssistantMessage("请指定插件名称: `/plugins update <name>`"),{success:!1,error:"Plugin name required"};A().addAssistantMessage(`正在更新插件: ${$}...`);let J=await r0().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(`
|
|
2067
|
+
`)),{success:!0,message:`Updated ${J.pluginName}`}}return A().addAssistantMessage(`更新失败: ${J.error}`),{success:!1,error:J.error}}var M2=MJ;var uJ={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{return await K$().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}}}},v2=uJ;function e1($){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 C2($){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 I2($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function gJ($,Z){let J=S(Z),W=$[0],X=a.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=[`**后台任务列表**
|
|
2045
2068
|
`],B=X.processes,K=Array.from(B?.values()||[]);if(K.length>0){V.push(`### Shells
|
|
2046
2069
|
`),V.push("| ID | 状态 | 命令 | PID | 运行时间 |"),V.push("|:---|:-----|:-----|:----|:---------|");for(let H of K){let G=H.endTime?e1(H.endTime-H.startTime):e1(Date.now()-H.startTime),O=C2(H.status);V.push(`| \`${H.id.slice(0,12)}...\` | ${O} ${H.status} | \`${I2(H.command,30)}\` | ${H.pid||"-"} | ${G} |`)}V.push("")}let Q=Y.listAll();if(Q.length>0){V.push(`### Agents
|
|
2047
2070
|
`),V.push("| ID | 状态 | 类型 | 描述 | 运行时间 |"),V.push("|:---|:-----|:-----|:-----|:---------|");for(let H of Q){let G=H.completedAt?e1(H.completedAt-H.createdAt):e1(Date.now()-H.createdAt),O=C2(H.status);V.push(`| \`${H.id.slice(0,12)}...\` | ${O} ${H.status} | ${H.subagentType} | ${I2(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(`*暂无后台任务*
|
|
2048
2071
|
`);else V.push(`**统计**: ${K.length} shells (${U} 运行中), ${Q.length} agents (${q} 运行中)`);return V.push(`
|
|
2049
2072
|
---`),V.push("**命令**:"),V.push("- `/tasks` - 列出所有后台任务"),V.push("- `/tasks clean` - 清理已完成的 Agent 会话"),J.sendMessage(V.join(`
|
|
2050
|
-
`)),{success:!0,message:`Listed ${K.length} shells and ${Q.length} agents`}}var
|
|
2073
|
+
`)),{success:!0,message:`Listed ${K.length} shells and ${Q.length} agents`}}var mJ={name:"tasks",description:"列出所有后台任务(shells 和 agents)",fullDescription:`查看和管理后台运行的任务。
|
|
2051
2074
|
|
|
2052
2075
|
**功能**:
|
|
2053
2076
|
- 列出所有后台 shell 进程
|
|
@@ -2056,8 +2079,8 @@ ${J}
|
|
|
2056
2079
|
|
|
2057
2080
|
**使用示例**:
|
|
2058
2081
|
- \`/tasks\` - 显示所有后台任务
|
|
2059
|
-
- \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:gJ},S2=
|
|
2082
|
+
- \`/tasks clean\` - 清理已完成的 agent 会话`,usage:"/tasks [clean]",category:"system",examples:["/tasks","/tasks clean"],handler:gJ},S2=mJ;async function cJ($,Z){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var lJ={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:cJ},P2=lJ;var J1={...H2,init:b2,theme:P2,permissions:n1,model:T2,git:N2,ide:R2,skills:v2,hooks:D2,tasks:S2,plugins:M2};function rO($){return $.trim().startsWith("/")}function aJ($){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 nJ($){if(J1[$])return J1[$];for(let Z of Object.values(J1))if(Z.aliases?.includes($))return Z;return}function y2($){let Z=$.argumentHint?`/${$.name} ${$.argumentHint}`:`/${$.name}`;return{name:$.name,description:$.description,fullDescription:`[Skill] ${$.description}${$.whenToUse?`
|
|
2060
2083
|
|
|
2061
|
-
**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
|
|
2062
|
-
使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function tO(){let $=Object.values(J1),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=C$().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=
|
|
2063
|
-
export{
|
|
2084
|
+
**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 rJ($){return K$().getUserInvocableSkills().find((W)=>W.name===$)}async function sJ(){await N0()}async function sO($){return await d.getInstance().initialize($)}async function oO($,Z){try{let{command:J,args:W}=aJ($),X=nJ(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=C$().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 sJ();let K=rJ(J);if(K)return await y2(K).handler(W,Z);return{success:!1,error:`未知命令: /${J}
|
|
2085
|
+
使用 /help 查看可用命令`}}catch(J){return{success:!1,error:`命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}}function tO(){let $=Object.values(J1),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=C$().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=K$().getUserInvocableSkills().map(y2);return[...$,...J,...X,...V]}function eO($){let Z=($.startsWith("/")?$.slice(1):$).trim(),J=Object.values(J1).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=C$().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=K$().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 iJ(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)}
|
|
2086
|
+
export{aW as y,z0 as z,R as A,Z0 as B,y6 as C,a as D,k1 as E,P as F,P1 as G,K0 as H,N8 as I,F9 as J,O9 as K,j9 as L,Y$ as M,C$ as N,l1 as O,s0 as P,I8 as Q,gF as R,rO as S,sO as T,oO as U,tO as V,eO as W};
|