blade-code 0.0.22 → 0.0.23
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 +228 -228
- package/package.json +1 -1
package/dist/blade.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as fY}from"node:module";var EY=Object.create;var{getPrototypeOf:jY,defineProperty:C$,getOwnPropertyNames:j8,getOwnPropertyDescriptor:SY}=Object,S8=Object.prototype.hasOwnProperty;var O1=($,Y,Z)=>{Z=$!=null?EY(jY($)):{};let X=Y||!$||!$.__esModule?C$(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of j8($))if(!S8.call(X,Q))C$(X,Q,{get:()=>$[Q],enumerable:!0});return X},E8=new WeakMap,PY=($)=>{var Y=E8.get($),Z;if(Y)return Y;if(Y=C$({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function")j8($).map((X)=>!S8.call(Y,X)&&C$(Y,X,{get:()=>$[X],enumerable:!(Z=SY($,X))||Z.enumerable}));return E8.set($,Y),Y};var TY=($,Y)=>{for(var Z in Y)C$($,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(X)=>Y[Z]=()=>X})};var CY=($,Y)=>()=>($&&(Y=$($=0)),Y);var A0=fY(import.meta.url);var A9={};TY(A9,{unescapeProjectPath:()=>c6,listProjectDirectories:()=>l6,getSessionFilePath:()=>X1,getProjectStoragePath:()=>F$,getBladeStorageRoot:()=>E1,escapeProjectPath:()=>L9,detectGitBranch:()=>a1});import{execSync as j7}from"node:child_process";import*as d6 from"node:os";import*as n1 from"node:path";function L9($){return n1.resolve($).replace(/\//g,"-")}function c6($){if($.startsWith("-"))return"/"+$.slice(1).replace(/-/g,"/");return $.replace(/-/g,"/")}function F$($){let Y=d6.homedir(),Z=L9($);return n1.join(Y,".blade","projects",Z)}function X1($,Y){return n1.join(F$($),`${Y}.jsonl`)}function a1($){try{return j7("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E1(){return n1.join(d6.homedir(),".blade")}async function l6(){let{readdir:$}=await import("node:fs/promises");try{let Y=n1.join(E1(),"projects");return(await $(Y,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}catch{return[]}}var z$=()=>{};import{render as Sq}from"ink";import Pq from"react";import Tq from"yargs";import{hideBin as IY}from"yargs/helpers";var f$={name:"blade-code",version:"0.0.22",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","bin","vendor/ripgrep/**","config.env.example","README.md"],scripts:{dev:"bun --watch src/blade.tsx",build:"rm -rf dist && bun run scripts/build.ts",start:"bun run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:coverage":"node scripts/test.js all --coverage","test:unit:coverage":"node scripts/test.js unit --coverage","test:integration:coverage":"node scripts/test.js integration --coverage","test:cli:coverage":"node scripts/test.js cli --coverage","test:watch":"vitest --watch --config vitest.config.ts","test:unit:watch":"vitest --watch --config vitest.config.ts --project unit","test:integration:watch":"vitest --watch --config vitest.config.ts --project integration","test:cli:watch":"vitest --watch --config vitest.config.ts --project cli","test:debug":"node scripts/test.js all --debug","test:verbose":"node scripts/test.js all --verbose","test:ci":"vitest run --config vitest.config.ts --coverage --reporter=verbose","test:performance":'vitest --testNamePattern="performance" --verbose',lint:"biome lint src tests","lint:fix":"biome lint --write src tests",format:"biome format --write src tests","format:check":"biome format src tests",check:"biome check src tests","check:fix":"biome check --write src tests","type-check":"tsc --noEmit","check:full":"npm run type-check && npm run lint && npm run format:check && npm run test:ci","security:audit":"pnpm audit","security:test":"bash scripts/run-security-tests.sh","vendor:ripgrep":"node scripts/download-ripgrep.js","vendor:ripgrep:clean":"rm -rf vendor/ripgrep/darwin-* vendor/ripgrep/linux-* vendor/ripgrep/win32-*",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch",clean:"rm -rf dist node_modules/.cache coverage",prepare:"bun run build",preflight:"npm run clean && pnpm install && npm run format && npm run lint && npm run build && npm run type-check && npm run test:ci"},keywords:["cli","blade","ai","assistant","agent","llm","tool","qwen","volcengine","smart-tools","code-review","documentation","git-tools"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=16.0.0"},devDependencies:{"@biomejs/biome":"^2.2.4","@testing-library/react":"^16.2.0","@testing-library/user-event":"^14.5.0","@types/bun":"^1.3.4","@types/diff":"^8.0.0","@types/inquirer":"^9.0.8","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.12","@types/react-dom":"^19.1.9","@types/uuid":"^10.0.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",execa:"^9.6.0",jsdom:"^26.0.0","ts-node":"^10.9.2",typescript:"^5.9.2",vitest:"^3.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0"},dependencies:{"@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.5","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0",glob:"^11.0.3",ink:"^6.4.0","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-progress-bar":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",inquirer:"^12.6.3","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",openai:"^6.2.0",picomatch:"^4.0.3",pino:"^10.1.0","pino-pretty":"^13.1.3",react:"^19.1.1","react-dom":"^19.1.1","string-width":"^8.1.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"}};function F2(){return f$.version}function P8(){return f$.name}function T8(){return f$.description}function C8(){return`v${f$.version} © 2025 Blade Code`}var f8={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json"],default:"text",describe:"Output format (only works with --print)",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:($)=>{if($===void 0||$===!0||$==="")return"true";return String($)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},model:{type:"string",describe:"Model for the current session",group:"AI Options:"},"fallback-model":{alias:["fallbackModel"],type:"string",describe:"Enable automatic fallback to specified model",group:"AI Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"}},c1={scriptName:"blade",usage:"$0 [command] [options]",description:T8(),version:F2(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};import{promises as z2}from"fs";import{merge as h8}from"lodash-es";import x8 from"os";import q$ from"path";var G$={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:32768,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"GitHub",language:"zh-CN",fontSize:14,debug:!1,mcpEnabled:!1,mcpServers:{},enabledMcpjsonServers:[],disabledMcpjsonServers:[],permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git log *)","Bash(git diff *)","Bash(git branch *)","Bash(git show *)","Bash(git remote *)","Bash(npm list *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],Stop:[]},env:{},disableAllHooks:!1,maxTurns:-1};class V0{static instance=null;constructor(){}static getInstance(){if(!V0.instance)V0.instance=new V0;return V0.instance}static resetInstance(){V0.instance=null}async initialize(){try{let $=await this.loadConfigFiles(),Y=await this.loadSettingsFiles(),Z={...G$,...$,...Y};if(this.resolveEnvInterpolation(Z),await this.ensureGitIgnore(Z.debug),Z.debug)console.log("[ConfigManager] Configuration loaded successfully");return Z}catch($){return console.error("[ConfigManager] Failed to initialize:",$),G$}}async loadConfigFiles(){let $=q$.join(x8.homedir(),".blade","config.json"),Y=q$.join(process.cwd(),".blade","config.json"),Z={},X=await this.loadJsonFile($);if(X)Z={...Z,...X};let Q=await this.loadJsonFile(Y);if(Q)Z={...Z,...Q};return Z}async loadSettingsFiles(){let $=q$.join(x8.homedir(),".blade","settings.json"),Y=q$.join(process.cwd(),".blade","settings.json"),Z=q$.join(process.cwd(),".blade","settings.local.json"),X={},Q=await this.loadJsonFile($);if(Q)X=this.mergeSettings(X,Q);let J=await this.loadJsonFile(Y);if(J)X=this.mergeSettings(X,J);let G=await this.loadJsonFile(Z);if(G)X=this.mergeSettings(X,G);return X}mergeSettings($,Y){let Z=JSON.parse(JSON.stringify($));if(Y.permissions){if(!Z.permissions)Z.permissions={allow:[],ask:[],deny:[]};if(Y.permissions.allow){let X=[...Z.permissions.allow||[],...Y.permissions.allow];Z.permissions.allow=Array.from(new Set(X))}if(Y.permissions.ask){let X=[...Z.permissions.ask||[],...Y.permissions.ask];Z.permissions.ask=Array.from(new Set(X))}if(Y.permissions.deny){let X=[...Z.permissions.deny||[],...Y.permissions.deny];Z.permissions.deny=Array.from(new Set(X))}}if(Y.hooks)Z.hooks=h8({},Z.hooks,Y.hooks);if(Y.env)Z.env=h8({},Z.env,Y.env);if(Y.disableAllHooks!==void 0)Z.disableAllHooks=Y.disableAllHooks;if(Y.permissionMode!==void 0)Z.permissionMode=Y.permissionMode;if(Y.maxTurns!==void 0)Z.maxTurns=Y.maxTurns;if(Y.mcpServers!==void 0)Z.mcpServers=Y.mcpServers;if(Y.enabledMcpjsonServers!==void 0)Z.enabledMcpjsonServers=Y.enabledMcpjsonServers;if(Y.disabledMcpjsonServers!==void 0)Z.disabledMcpjsonServers=Y.disabledMcpjsonServers;return Z}resolveEnvInterpolation($){let Y=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,Z=(X)=>{if(typeof X==="string")return X.replace(Y,(Q,J,G,q)=>{return process.env[J]||q||Q});return X};for(let[X,Q]of Object.entries($))if(typeof Q==="string")$[X]=Z(Q)}async ensureGitIgnore($){let Y=q$.join(process.cwd(),".gitignore"),Z=".blade/settings.local.json";try{let X="";if(await this.fileExists(Y))X=await z2.readFile(Y,"utf-8");if(!X.includes(".blade/settings.local.json")){let Q=X.trim()+`
|
|
2
|
+
import{createRequire as mY}from"node:module";var CY=Object.create;var{getPrototypeOf:fY,defineProperty:h$,getOwnPropertyNames:T8,getOwnPropertyDescriptor:hY}=Object,C8=Object.prototype.hasOwnProperty;var O1=($,Y,Z)=>{Z=$!=null?CY(fY($)):{};let X=Y||!$||!$.__esModule?h$(Z,"default",{value:$,enumerable:!0}):Z;for(let Q of T8($))if(!C8.call(X,Q))h$(X,Q,{get:()=>$[Q],enumerable:!0});return X},S8=new WeakMap,xY=($)=>{var Y=S8.get($),Z;if(Y)return Y;if(Y=h$({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function")T8($).map((X)=>!C8.call(Y,X)&&h$(Y,X,{get:()=>$[X],enumerable:!(Z=hY($,X))||Z.enumerable}));return S8.set($,Y),Y};var pY=($,Y)=>{for(var Z in Y)h$($,Z,{get:Y[Z],enumerable:!0,configurable:!0,set:(X)=>Y[Z]=()=>X})};var gY=($,Y)=>()=>($&&(Y=$($=0)),Y);var A0=mY(import.meta.url);var V9={};pY(V9,{unescapeProjectPath:()=>r6,listProjectDirectories:()=>a6,getSessionFilePath:()=>Q1,getProjectStoragePath:()=>z$,getBladeStorageRoot:()=>j1,escapeProjectPath:()=>b9,detectGitBranch:()=>o1});import{execSync as f7}from"node:child_process";import*as i6 from"node:os";import*as n1 from"node:path";function b9($){return n1.resolve($).replace(/\//g,"-")}function r6($){if($.startsWith("-"))return"/"+$.slice(1).replace(/-/g,"/");return $.replace(/-/g,"/")}function z$($){let Y=i6.homedir(),Z=b9($);return n1.join(Y,".blade","projects",Z)}function Q1($,Y){return n1.join(z$($),`${Y}.jsonl`)}function o1($){try{return f7("git rev-parse --abbrev-ref HEAD",{cwd:$,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function j1(){return n1.join(i6.homedir(),".blade")}async function a6(){let{readdir:$}=await import("node:fs/promises");try{let Y=n1.join(j1(),"projects");return(await $(Y,{withFileTypes:!0})).filter((X)=>X.isDirectory()).map((X)=>X.name)}catch{return[]}}var N$=()=>{};import{render as hG}from"ink";import xG from"react";import pG from"yargs";import{hideBin as yY}from"yargs/helpers";var x$={name:"blade-code",version:"0.0.23",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","bin","vendor/ripgrep/**","config.env.example","README.md"],scripts:{dev:"bun --watch src/blade.tsx",build:"rm -rf dist && bun run scripts/build.ts",start:"bun run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:cli":"node scripts/test.js cli","test:coverage":"node scripts/test.js all --coverage","test:unit:coverage":"node scripts/test.js unit --coverage","test:integration:coverage":"node scripts/test.js integration --coverage","test:cli:coverage":"node scripts/test.js cli --coverage","test:watch":"vitest --watch --config vitest.config.ts","test:unit:watch":"vitest --watch --config vitest.config.ts --project unit","test:integration:watch":"vitest --watch --config vitest.config.ts --project integration","test:cli:watch":"vitest --watch --config vitest.config.ts --project cli","test:debug":"node scripts/test.js all --debug","test:verbose":"node scripts/test.js all --verbose","test:ci":"vitest run --config vitest.config.ts --coverage --reporter=verbose","test:performance":'vitest --testNamePattern="performance" --verbose',lint:"biome lint src tests","lint:fix":"biome lint --write src tests",format:"biome format --write src tests","format:check":"biome format src tests",check:"biome check src tests","check:fix":"biome check --write src tests","type-check":"tsc --noEmit","check:full":"npm run type-check && npm run lint && npm run format:check && npm run test:ci","security:audit":"pnpm audit","security:test":"bash scripts/run-security-tests.sh","vendor:ripgrep":"node scripts/download-ripgrep.js","vendor:ripgrep:clean":"rm -rf vendor/ripgrep/darwin-* vendor/ripgrep/linux-* vendor/ripgrep/win32-*",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch",clean:"rm -rf dist node_modules/.cache coverage",prepare:"bun run build",preflight:"npm run clean && pnpm install && npm run format && npm run lint && npm run build && npm run type-check && npm run test:ci"},keywords:["cli","blade","ai","assistant","agent","llm","tool","qwen","volcengine","smart-tools","code-review","documentation","git-tools"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=16.0.0"},devDependencies:{"@biomejs/biome":"^2.2.4","@testing-library/react":"^16.2.0","@testing-library/user-event":"^14.5.0","@types/bun":"^1.3.4","@types/diff":"^8.0.0","@types/inquirer":"^9.0.8","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.12","@types/react-dom":"^19.1.9","@types/uuid":"^10.0.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",execa:"^9.6.0",jsdom:"^26.0.0","ts-node":"^10.9.2",typescript:"^5.9.2",vitest:"^3.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0"},dependencies:{"@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.5","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0",glob:"^11.0.3",ink:"^6.4.0","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-progress-bar":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",inquirer:"^12.6.3","js-tiktoken":"^1.0.21","lodash-es":"^4.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",openai:"^6.2.0",picomatch:"^4.0.3",pino:"^10.1.0","pino-pretty":"^13.1.3",react:"^19.1.1","react-dom":"^19.1.1","string-width":"^8.1.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"}};function N2(){return x$.version}function f8(){return x$.name}function h8(){return x$.description}function x8(){return`v${x$.version} © 2025 Blade Code`}var p8={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json"],default:"text",describe:"Output format (only works with --print)",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:($)=>{if($===void 0||$===!0||$==="")return"true";return String($)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},model:{type:"string",describe:"Model for the current session",group:"AI Options:"},"fallback-model":{alias:["fallbackModel"],type:"string",describe:"Enable automatic fallback to specified model",group:"AI Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"}},l1={scriptName:"blade",usage:"$0 [command] [options]",description:h8(),version:N2(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};import{promises as B2}from"fs";import{merge as g8}from"lodash-es";import m8 from"os";import K$ from"path";var G$={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:32768,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"GitHub",language:"zh-CN",fontSize:14,debug:!1,mcpEnabled:!1,mcpServers:{},enabledMcpjsonServers:[],disabledMcpjsonServers:[],permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git log *)","Bash(git diff *)","Bash(git branch *)","Bash(git show *)","Bash(git remote *)","Bash(npm list *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],Stop:[]},env:{},disableAllHooks:!1,maxTurns:-1};class V0{static instance=null;constructor(){}static getInstance(){if(!V0.instance)V0.instance=new V0;return V0.instance}static resetInstance(){V0.instance=null}async initialize(){try{let $=await this.loadConfigFiles(),Y=await this.loadSettingsFiles(),Z={...G$,...$,...Y};if(this.resolveEnvInterpolation(Z),await this.ensureGitIgnore(Z.debug),Z.debug)console.log("[ConfigManager] Configuration loaded successfully");return Z}catch($){return console.error("[ConfigManager] Failed to initialize:",$),G$}}async loadConfigFiles(){let $=K$.join(m8.homedir(),".blade","config.json"),Y=K$.join(process.cwd(),".blade","config.json"),Z={},X=await this.loadJsonFile($);if(X)Z={...Z,...X};let Q=await this.loadJsonFile(Y);if(Q)Z={...Z,...Q};return Z}async loadSettingsFiles(){let $=K$.join(m8.homedir(),".blade","settings.json"),Y=K$.join(process.cwd(),".blade","settings.json"),Z=K$.join(process.cwd(),".blade","settings.local.json"),X={},Q=await this.loadJsonFile($);if(Q)X=this.mergeSettings(X,Q);let J=await this.loadJsonFile(Y);if(J)X=this.mergeSettings(X,J);let q=await this.loadJsonFile(Z);if(q)X=this.mergeSettings(X,q);return X}mergeSettings($,Y){let Z=JSON.parse(JSON.stringify($));if(Y.permissions){if(!Z.permissions)Z.permissions={allow:[],ask:[],deny:[]};if(Y.permissions.allow){let X=[...Z.permissions.allow||[],...Y.permissions.allow];Z.permissions.allow=Array.from(new Set(X))}if(Y.permissions.ask){let X=[...Z.permissions.ask||[],...Y.permissions.ask];Z.permissions.ask=Array.from(new Set(X))}if(Y.permissions.deny){let X=[...Z.permissions.deny||[],...Y.permissions.deny];Z.permissions.deny=Array.from(new Set(X))}}if(Y.hooks)Z.hooks=g8({},Z.hooks,Y.hooks);if(Y.env)Z.env=g8({},Z.env,Y.env);if(Y.disableAllHooks!==void 0)Z.disableAllHooks=Y.disableAllHooks;if(Y.permissionMode!==void 0)Z.permissionMode=Y.permissionMode;if(Y.maxTurns!==void 0)Z.maxTurns=Y.maxTurns;if(Y.mcpServers!==void 0)Z.mcpServers=Y.mcpServers;if(Y.enabledMcpjsonServers!==void 0)Z.enabledMcpjsonServers=Y.enabledMcpjsonServers;if(Y.disabledMcpjsonServers!==void 0)Z.disabledMcpjsonServers=Y.disabledMcpjsonServers;return Z}resolveEnvInterpolation($){let Y=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,Z=(X)=>{if(typeof X==="string")return X.replace(Y,(Q,J,q,G)=>{return process.env[J]||G||Q});return X};for(let[X,Q]of Object.entries($))if(typeof Q==="string")$[X]=Z(Q)}async ensureGitIgnore($){let Y=K$.join(process.cwd(),".gitignore"),Z=".blade/settings.local.json";try{let X="";if(await this.fileExists(Y))X=await B2.readFile(Y,"utf-8");if(!X.includes(".blade/settings.local.json")){let Q=X.trim()+`
|
|
3
3
|
|
|
4
4
|
# Blade local settings
|
|
5
5
|
.blade/settings.local.json
|
|
6
|
-
`;if(await
|
|
6
|
+
`;if(await B2.writeFile(Y,Q,"utf-8"),$)console.log("[ConfigManager] Added .blade/settings.local.json to .gitignore")}}catch(X){}}async loadJsonFile($){try{if(await this.fileExists($)){let Y=await B2.readFile($,"utf-8");return JSON.parse(Y)}}catch(Y){console.warn(`[ConfigManager] Failed to load ${$}:`,Y)}return null}async fileExists($){try{return await B2.access($),!0}catch{return!1}}validateConfig($){let Y=[];if(!$.models||$.models.length===0)Y.push("没有可用的模型配置");if($.models&&$.models.length>0){if(!$.currentModelId)Y.push("未设置当前模型 ID");else if(!$.models.find((X)=>X.id===$.currentModelId))Y.push("当前模型 ID 无效")}if(Y.length>0)throw Error(`配置验证失败:
|
|
7
7
|
${Y.map((Z)=>` - ${Z}`).join(`
|
|
8
8
|
`)}
|
|
9
9
|
|
|
@@ -26,22 +26,22 @@ ${Y.map((Z)=>` - ${Z}`).join(`
|
|
|
26
26
|
}
|
|
27
27
|
]
|
|
28
28
|
}
|
|
29
|
-
`)}}function B2($,Y={}){let Z={...$};if(Y.fallbackModel!==void 0)Z.fallbackModel=Y.fallbackModel;if(Y.debug!==void 0)Z.debug=Y.debug===""?!0:Y.debug;if(Y.yolo===!0)Z.permissionMode="yolo";else if(Y.permissionMode!==void 0)Z.permissionMode=Y.permissionMode;if(Y.maxTurns!==void 0)Z.maxTurns=Y.maxTurns;return Z.systemPrompt=Y.systemPrompt,Z.appendSystemPrompt=Y.appendSystemPrompt,Z.resumeSessionId=Y.sessionId,Z.forkSession=Y.forkSession,Z.allowedTools=Y.allowedTools,Z.disallowedTools=Y.disallowedTools,Z.mcpConfigPaths=Y.mcpConfig,Z.strictMcpConfig=Y.strictMcpConfig,Z.addDirs=Y.addDir,Z.outputFormat=Y.outputFormat,Z.inputFormat=Y.inputFormat,Z.print=Y.print,Z.includePartialMessages=Y.includePartialMessages,Z.replayUserMessages=Y.replayUserMessages,Z.agentsConfig=Y.agents,Z.settingSources=Y.settingSources,Z}import{Mutex as m8}from"async-mutex";import{merge as cY}from"lodash-es";import{promises as N2}from"node:fs";import d8 from"node:os";import v1 from"node:path";import lY from"write-file-atomic";import{promises as xY}from"node:fs";import pY from"node:os";import p8 from"node:path";import gY from"pino";var u8;((Q)=>{Q[Q.DEBUG=0]="DEBUG";Q[Q.INFO=1]="INFO";Q[Q.WARN=2]="WARN";Q[Q.ERROR=3]="ERROR"})(u8||={});var uY={[0]:"debug",[1]:"info",[2]:"warn",[3]:"error"};async function mY(){let $=p8.join(pY.homedir(),".blade","logs");return await xY.mkdir($,{recursive:!0}),p8.join($,"blade.log")}var h$=null,x$=null;async function dY(){if(h$)return h$;if(x$)return x$;return x$=(async()=>{let $=await mY();return h$=gY({level:"debug",transport:{target:"pino/file",options:{destination:$}}}),h$})(),x$}function g8(){h$=null,x$=null}class S0{static globalDebugConfig=null;enabled;minLevel;category;pinoLogger=null;constructor($={}){if($.enabled!==void 0)this.enabled=$.enabled;else if(S0.globalDebugConfig!==null)this.enabled=Boolean(S0.globalDebugConfig);else this.enabled=!1;this.minLevel=$.minLevel??0,this.category=$.category??"General",this.initPino()}async initPino(){try{let $=await dY();this.pinoLogger=$.child({category:this.category})}catch($){console.error("[Logger] Failed to initialize pino:",$)}}static setGlobalDebug($){S0.globalDebugConfig=$,g8()}static clearGlobalDebug(){S0.globalDebugConfig=null,g8()}setEnabled($){this.enabled=$}parseDebugFilter($){if(!$)return{enabled:!1};if($===!0||$==="true"||$==="1")return{enabled:!0};let Y=String($).trim();if(!Y)return{enabled:!0};if(Y.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:Y.split(",").map((Q)=>Q.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:Y.split(",").map((X)=>X.trim()).filter(Boolean)}}}shouldLogCategory($){if(!$)return!0;let Y=this.category.toLowerCase();if($.mode==="include")return $.categories.some((Z)=>Y.includes(Z.toLowerCase()));return!$.categories.some((Z)=>Y.includes(Z.toLowerCase()))}shouldLogToConsole($){if(S0.globalDebugConfig!==null){let{enabled:Y,filter:Z}=this.parseDebugFilter(S0.globalDebugConfig);if(!Y)return!1;if($<this.minLevel)return!1;return this.shouldLogCategory(Z)}return this.enabled&&$>=this.minLevel}log($,...Y){let Z=Y.map((X)=>typeof X==="object"?JSON.stringify(X):String(X)).join(" ");if(this.pinoLogger){let X=uY[$];this.pinoLogger[X](Z)}if(this.shouldLogToConsole($)){let X=u8[$],Q=`[${this.category}] [${X}]`;console.error(Q,...Y)}}debug(...$){this.log(0,...$)}info(...$){this.log(1,...$)}warn(...$){this.log(2,...$)}error(...$){this.log(3,...$)}}function Q0($,Y){return new S0({...Y,category:$})}var GK=new S0({category:"General"});var c8=Q0("Service"),y1={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},enabledMcpjsonServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},disabledMcpjsonServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},fallbackModel:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},zK=new Set(Object.entries(y1).filter(([$,Y])=>Y.persistable).map(([$])=>$)),BK=new Set(Object.entries(y1).filter(([$,Y])=>!Y.persistable).map(([$])=>$)),NK=new Set(Object.entries(y1).filter(([$,Y])=>Y.target==="config").map(([$])=>$)),wK=new Set(Object.entries(y1).filter(([$,Y])=>Y.target==="settings").map(([$])=>$));class V1{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!V1.instance)V1.instance=new V1;return V1.instance}static resetInstance(){if(V1.instance)for(let $ of V1.instance.timers.values())clearTimeout($);V1.instance=null}async save($,Y={}){this.validatePersistableFields($);let Z=this.groupUpdatesByTarget($,Y.scope);if(Y.immediate)await Promise.all(Array.from(Z.entries()).map(([X,Q])=>this.flushTarget(X,Q)));else for(let[X,Q]of Z)this.scheduleSave(X,Q)}async flush(){for(let Y of this.timers.values())clearTimeout(Y);this.timers.clear();let $=Array.from(this.pendingUpdates.entries()).map(([Y,Z])=>this.flushTarget(Y,Z));this.pendingUpdates.clear(),await Promise.all($)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule($,Y={}){let Z=Y.scope??"local",X=this.resolveFilePath("settings",Z);await this.flushTargetWithModifier(X,(Q)=>{let J=Q.permissions??{allow:[],ask:[],deny:[]},G={allow:this.dedupeArray([...J.allow||[],$]),ask:J.ask||[],deny:J.deny||[]};return{...Q,permissions:G}})}async appendLocalPermissionRule($,Y={}){await this.appendPermissionRule($,{...Y,scope:"local"})}validatePersistableFields($){for(let Y of Object.keys($)){let Z=y1[Y];if(!Z)throw Error(`Unknown config field: ${Y}`);if(!Z.persistable)throw Error(`Field "${Y}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget($,Y){let Z=new Map;for(let[X,Q]of Object.entries($)){let J=y1[X];if(!J)continue;let G=Y??J.defaultScope,q=this.resolveFilePath(J.target,G);if(!Z.has(q))Z.set(q,{});Z.get(q)[X]=Q}return Z}resolveFilePath($,Y){if($==="config")return Y==="global"?v1.join(d8.homedir(),".blade","config.json"):v1.join(process.cwd(),".blade","config.json");switch(Y){case"local":return v1.join(process.cwd(),".blade","settings.local.json");case"project":return v1.join(process.cwd(),".blade","settings.json");case"global":return v1.join(d8.homedir(),".blade","settings.json");default:return v1.join(process.cwd(),".blade","settings.local.json")}}scheduleSave($,Y){let Z=this.pendingUpdates.get($)??{},X=this.mergePendingUpdates(Z,Y);this.pendingUpdates.set($,X);let Q=this.timers.get($);if(Q)clearTimeout(Q);let J=setTimeout(async()=>{let G=this.pendingUpdates.get($);if(G){this.pendingUpdates.delete($),this.timers.delete($);try{await this.flushTarget($,G),this.lastSaveError=null}catch(q){let K=q instanceof Error?q:Error(String(q));this.lastSaveError=K,c8.error(`Failed to save config to ${$}:`,K.message),c8.error("Stack trace:",K.stack)}}},this.debounceDelay);this.timers.set($,J)}mergePendingUpdates($,Y){let Z={...$};for(let[X,Q]of Object.entries(Y)){let J=y1[X];if(!J){Z[X]=Q;continue}switch(J.mergeStrategy){case"replace":Z[X]=Q;break;case"append-dedupe":this.applyAppendDedupe(Z,X,Q);break;case"deep-merge":this.applyDeepMerge(Z,X,Q);break}}return Z}async flushTarget($,Y){let Z=this.fileLocks.get($);if(!Z)Z=new m8,this.fileLocks.set($,Z);await Z.runExclusive(async()=>{await this.performWrite($,Y)})}async flushTargetWithModifier($,Y){let Z=this.fileLocks.get($);if(!Z)Z=new m8,this.fileLocks.set($,Z);await Z.runExclusive(async()=>{await N2.mkdir(v1.dirname($),{recursive:!0});let X={};try{let J=await N2.readFile($,"utf-8");X=JSON.parse(J)}catch{X={}}let Q=Y(X);await this.atomicWrite($,Q)})}async performWrite($,Y){await N2.mkdir(v1.dirname($),{recursive:!0});let Z={};try{let Q=await N2.readFile($,"utf-8");Z=JSON.parse(Q)}catch{Z={}}let X={...Z};for(let[Q,J]of Object.entries(Y)){let G=y1[Q];if(!G){X[Q]=J;continue}switch(G.mergeStrategy){case"replace":X[Q]=J;break;case"append-dedupe":this.applyAppendDedupe(X,Q,J);break;case"deep-merge":this.applyDeepMerge(X,Q,J);break}}await this.atomicWrite($,X)}applyAppendDedupe($,Y,Z){if(Y==="permissions"&&typeof Z==="object"&&Z!==null){let X=$[Y]??{allow:[],ask:[],deny:[]},Q=Z;$[Y]={allow:this.dedupeArray([...X.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...X.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...X.deny||[],...Q.deny||[]])}}else if(Array.isArray(Z)){let X=Array.isArray($[Y])?$[Y]:[];$[Y]=this.dedupeArray([...X,...Z])}else $[Y]=Z}applyDeepMerge($,Y,Z){if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z)){let X=typeof $[Y]==="object"&&$[Y]!==null?$[Y]:{};$[Y]=cY({},X,Z)}else $[Y]=Z}dedupeArray($){return Array.from(new Set($))}async atomicWrite($,Y){await lY($,JSON.stringify(Y,null,2),{mode:384,encoding:"utf-8"})}}function I0(){return V1.getInstance()}import p$ from"picomatch";class l1{config;constructor($){this.config=$}check($){let Y=l1.buildSignature($),Z=this.matchRules(Y,this.config.deny);if(Z)return{result:"deny",matchedRule:Z.rule,matchType:Z.type,reason:`工具调用被拒绝规则阻止: ${Z.rule}`};let X=this.matchRules(Y,this.config.allow);if(X)return{result:"allow",matchedRule:X.rule,matchType:X.type,reason:`工具调用符合允许规则: ${X.rule}`};let Q=this.matchRules(Y,this.config.ask);if(Q)return{result:"ask",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用需要用户确认: ${Q.rule}`};return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Y,params:Z,tool:X}=$;try{if(X?.extractSignatureContent){let Q=X.extractSignatureContent(Z);return Q?`${Y}(${Q})`:Y}return Y}catch(Q){return console.warn(`Failed to build signature for ${Y}:`,Q instanceof Error?Q.message:Q),Y}}static abstractPattern($){let{toolName:Y,params:Z,tool:X}=$;try{if(X?.abstractPermissionRule){let Q=X.abstractPermissionRule(Z);if(Q==="")return"";return Q?`${Y}(${Q})`:Y}return Y}catch(Q){return console.warn(`Failed to abstract pattern for ${Y}:`,Q instanceof Error?Q.message:Q),Y}}matchRules($,Y){for(let Z of Y){let X=this.matchRule($,Z);if(X)return{rule:Z,type:X}}return null}matchRule($,Y){if($===Y)return"exact";if(Y==="*"||Y==="**")return"wildcard";let Z=this.extractToolName($),X=this.extractToolName(Y);if(!Z||!X)return null;if(X.includes("*")){if(!p$.isMatch(Z,X,{dot:!0,bash:!0}))return null}else if(Z!==X)return null;if(Y===X)return"prefix";if(Y.includes("*")){let Q=this.extractParams($),J=this.extractParams(Y);if(J==="*"||J==="**")return"wildcard";if(this.matchParams(Q,J))return J.includes("**")?"glob":"wildcard";if(p$.isMatch($,Y,{dot:!0,bash:!0}))return Y.includes("**")?"glob":"wildcard"}return null}extractParams($){let Y=$.match(/\(([\s\S]*)\)$/);return Y?Y[1]:""}matchParams($,Y){if(!$||!Y)return!1;let Z=this.parseParamPairs($),X=this.parseParamPairs(Y),Q=Object.keys(X).length>0,J=Object.keys(Z).length>0;if(Q!==J)return!1;if(!Q&&!J){if(Y==="*"||Y==="**")return!0;if(Y.includes("*")||Y.includes("{")||Y.includes("?"))return p$.isMatch($,Y,{dot:!0,bash:!0});return $===Y}for(let[G,q]of Object.entries(X)){let K=Z[G];if(K===void 0)return!1;if(q.includes("*")||q.includes("{")||q.includes("?")){if(q==="*"||q==="**")continue;if(!p$.isMatch(K,q,{dot:!0,bash:!0}))return!1}else if(K!==q)return!1}return!0}parseParamPairs($){let Y={},Z=this.smartSplit($,",");for(let X of Z){let Q=this.findTopLevelDelimiter(X,":");if(Q>0){let J=X.slice(0,Q).trim(),G=X.slice(Q+1).trim();Y[J]=G}}return Y}smartSplit($,Y){let Z=[],X="",Q=0,J=0,G=0,q=!1,K="",W=!1;for(let O=0;O<$.length;O++){let U=$[O];if(W){X+=U,W=!1;continue}if(U==="\\"){X+=U,W=!0;continue}if(!q&&U==="{")Q++;else if(!q&&U==="}")Q--;else if(!q&&U==="(")J++;else if(!q&&U===")")J--;else if(!q&&U==="[")G++;else if(!q&&U==="]")G--;if((U==='"'||U==="'")&&!q){q=!0,K=U,X+=U;continue}else if(q&&U===K){q=!1,K="",X+=U;continue}if(U===Y&&Q===0&&J===0&&G===0&&!q)Z.push(X.trim()),X="";else X+=U}if(X)Z.push(X.trim());return Z}findTopLevelDelimiter($,Y){let Z=0,X=0,Q=0,J=!1,G="",q=!1;for(let K=0;K<$.length;K++){let W=$[K];if(q){q=!1;continue}if(W==="\\"){q=!0;continue}if(!J&&W==="{")Z++;else if(!J&&W==="}")Z--;else if(!J&&W==="(")X++;else if(!J&&W===")")X--;else if(!J&&W==="[")Q++;else if(!J&&W==="]")Q--;if((W==='"'||W==="'")&&!J){J=!0,G=W;continue}else if(J&&W===G){J=!1,G="";continue}if(W===Y&&Z===0&&X===0&&Q===0&&!J)return K}return-1}extractToolName($){let Y=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Y?Y[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}}}import{nanoid as tY}from"nanoid";import{devtools as eY,subscribeWithSelector as $7}from"zustand/middleware";import{createStore as Y7}from"zustand/vanilla";var rY={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,todos:[],awaitingSecondCtrlC:!1},I6=($)=>({...rY,actions:{setInitializationStatus:(Y)=>{$((Z)=>({app:{...Z.app,initializationStatus:Y}}))},setInitializationError:(Y)=>{$((Z)=>({app:{...Z.app,initializationError:Y}}))},setActiveModal:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:Y}}))},showSessionSelector:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:"sessionSelector",sessionSelectorData:Y}}))},showModelEditWizard:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:"modelEditWizard",modelEditorTarget:Y}}))},closeModal:()=>{$((Y)=>({app:{...Y.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTodos:(Y)=>{$((Z)=>({app:{...Z.app,todos:Y}}))},updateTodo:(Y)=>{$((Z)=>({app:{...Z.app,todos:Z.app.todos.map((X)=>X.id===Y.id?Y:X)}}))},setAwaitingSecondCtrlC:(Y)=>{$((Z)=>({app:{...Z.app,awaitingSecondCtrlC:Y}}))}}});var nY={isProcessing:!1,abortController:null,pendingCommands:[]},D6=($,Y)=>({...nY,actions:{setProcessing:(Z)=>{$((X)=>({command:{...X.command,isProcessing:Z}}))},createAbortController:()=>{let Z=new AbortController;return $((X)=>({command:{...X.command,abortController:Z}})),Z},clearAbortController:()=>{$((Z)=>({command:{...Z.command,abortController:null}}))},abort:()=>{let{abortController:Z}=Y().command;if(Z&&!Z.signal.aborted)Z.abort();Y().session.actions.setThinking(!1),$((X)=>({command:{...X.command,isProcessing:!1,abortController:null,pendingCommands:[]}}))},enqueueCommand:(Z)=>{$((X)=>({command:{...X.command,pendingCommands:[...X.command.pendingCommands,Z]}}))},dequeueCommand:()=>{let{pendingCommands:Z}=Y().command;if(Z.length===0)return;let[X,...Q]=Z;return $((J)=>({command:{...J.command,pendingCommands:Q}})),X},clearQueue:()=>{$((Z)=>({command:{...Z.command,pendingCommands:[]}}))}}});var aY={config:null},k6=($)=>({...aY,actions:{setConfig:(Y)=>{$((Z)=>({config:{...Z.config,config:Y}}))},updateConfig:(Y)=>{$((Z)=>{if(!Z.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Y)}`);return{config:{...Z.config,config:{...Z.config.config,...Y}}}})}}});var oY={currentFocus:"main-input",previousFocus:null},M6=($)=>({...oY,actions:{setFocus:(Y)=>{$((Z)=>({focus:{...Z.focus,currentFocus:Y,previousFocus:Z.focus.currentFocus}}))},restorePreviousFocus:()=>{$((Y)=>({focus:{...Y.focus,currentFocus:Y.focus.previousFocus||"main-input",previousFocus:null}}))}}});import{nanoid as sY}from"nanoid";var i8={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000},l8={sessionId:sY(),messages:[],isThinking:!1,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...i8}},v6=($,Y)=>({...l8,actions:{addMessage:(Z)=>{$((X)=>({session:{...X.session,messages:[...X.session.messages,Z],error:null}}))},addUserMessage:(Z)=>{let X={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:Z,timestamp:Date.now()};Y().session.actions.addMessage(X)},addAssistantMessage:(Z)=>{let X={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Z,timestamp:Date.now()};Y().session.actions.addMessage(X)},addToolMessage:(Z,X)=>{let Q={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:Z,timestamp:Date.now(),metadata:X};Y().session.actions.addMessage(Q)},setThinking:(Z)=>{$((X)=>({session:{...X.session,isThinking:Z}}))},setCompacting:(Z)=>{$((X)=>({session:{...X.session,isCompacting:Z}}))},setCommand:(Z)=>{$((X)=>({session:{...X.session,currentCommand:Z}}))},setError:(Z)=>{$((X)=>({session:{...X.session,error:Z}}))},clearMessages:()=>{$((Z)=>({session:{...Z.session,messages:[],error:null}}))},resetSession:()=>{$((Z)=>({session:{...Z.session,...l8,sessionId:Z.session.sessionId,isActive:!0}}))},restoreSession:(Z,X)=>{$((Q)=>({session:{...Q.session,sessionId:Z,messages:X,error:null,isActive:!0}}))},updateTokenUsage:(Z)=>{$((X)=>({session:{...X.session,tokenUsage:{...X.session.tokenUsage,...Z}}}))},resetTokenUsage:()=>{$((Z)=>({session:{...Z.session,tokenUsage:{...i8}}}))}}});var g$=Y7()(eY($7((...$)=>({session:v6(...$),app:I6(...$),config:k6(...$),focus:M6(...$),command:D6(...$)})),{name:"BladeStore",enabled:!0})),s=()=>g$.getState(),Z7=g$.subscribe,o=()=>s().session.actions,Y1=()=>s().app.actions;var F0=()=>s().config.config,K$=null;async function w2(){if(F0()!==null)return;if(K$)return K$;return K$=(async()=>{try{let Z=await V0.getInstance().initialize();s().config.actions.setConfig(Z)}catch(Y){throw K$=null,Error(`❌ Store 未初始化且无法自动初始化
|
|
29
|
+
`)}}function L2($,Y={}){let Z={...$};if(Y.fallbackModel!==void 0)Z.fallbackModel=Y.fallbackModel;if(Y.debug!==void 0)Z.debug=Y.debug===""?!0:Y.debug;if(Y.yolo===!0)Z.permissionMode="yolo";else if(Y.permissionMode!==void 0)Z.permissionMode=Y.permissionMode;if(Y.maxTurns!==void 0)Z.maxTurns=Y.maxTurns;return Z.systemPrompt=Y.systemPrompt,Z.appendSystemPrompt=Y.appendSystemPrompt,Z.resumeSessionId=Y.sessionId,Z.forkSession=Y.forkSession,Z.allowedTools=Y.allowedTools,Z.disallowedTools=Y.disallowedTools,Z.mcpConfigPaths=Y.mcpConfig,Z.strictMcpConfig=Y.strictMcpConfig,Z.addDirs=Y.addDir,Z.outputFormat=Y.outputFormat,Z.inputFormat=Y.inputFormat,Z.print=Y.print,Z.includePartialMessages=Y.includePartialMessages,Z.replayUserMessages=Y.replayUserMessages,Z.agentsConfig=Y.agents,Z.settingSources=Y.settingSources,Z}import{Mutex as l8}from"async-mutex";import{merge as nY}from"lodash-es";import{promises as w2}from"node:fs";import i8 from"node:os";import y1 from"node:path";import oY from"write-file-atomic";import{promises as dY}from"node:fs";import cY from"node:os";import u8 from"node:path";import lY from"pino";var c8;((Q)=>{Q[Q.DEBUG=0]="DEBUG";Q[Q.INFO=1]="INFO";Q[Q.WARN=2]="WARN";Q[Q.ERROR=3]="ERROR"})(c8||={});var iY={[0]:"debug",[1]:"info",[2]:"warn",[3]:"error"};async function rY(){let $=u8.join(cY.homedir(),".blade","logs");return await dY.mkdir($,{recursive:!0}),u8.join($,"blade.log")}var p$=null,g$=null;async function aY(){if(p$)return p$;if(g$)return g$;return g$=(async()=>{let $=await rY();return p$=lY({level:"debug",transport:{target:"pino/file",options:{destination:$}}}),p$})(),g$}function d8(){p$=null,g$=null}class P0{static globalDebugConfig=null;enabled;minLevel;category;pinoLogger=null;constructor($={}){if($.enabled!==void 0)this.enabled=$.enabled;else if(P0.globalDebugConfig!==null)this.enabled=Boolean(P0.globalDebugConfig);else this.enabled=!1;this.minLevel=$.minLevel??0,this.category=$.category??"General",this.initPino()}async initPino(){try{let $=await aY();this.pinoLogger=$.child({category:this.category})}catch($){console.error("[Logger] Failed to initialize pino:",$)}}static setGlobalDebug($){P0.globalDebugConfig=$,d8()}static clearGlobalDebug(){P0.globalDebugConfig=null,d8()}setEnabled($){this.enabled=$}parseDebugFilter($){if(!$)return{enabled:!1};if($===!0||$==="true"||$==="1")return{enabled:!0};let Y=String($).trim();if(!Y)return{enabled:!0};if(Y.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:Y.split(",").map((Q)=>Q.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:Y.split(",").map((X)=>X.trim()).filter(Boolean)}}}shouldLogCategory($){if(!$)return!0;let Y=this.category.toLowerCase();if($.mode==="include")return $.categories.some((Z)=>Y.includes(Z.toLowerCase()));return!$.categories.some((Z)=>Y.includes(Z.toLowerCase()))}shouldLogToConsole($){if(P0.globalDebugConfig!==null){let{enabled:Y,filter:Z}=this.parseDebugFilter(P0.globalDebugConfig);if(!Y)return!1;if($<this.minLevel)return!1;return this.shouldLogCategory(Z)}return this.enabled&&$>=this.minLevel}log($,...Y){let Z=Y.map((X)=>typeof X==="object"?JSON.stringify(X):String(X)).join(" ");if(this.pinoLogger){let X=iY[$];this.pinoLogger[X](Z)}if(this.shouldLogToConsole($)){let X=c8[$],Q=`[${this.category}] [${X}]`;console.error(Q,...Y)}}debug(...$){this.log(0,...$)}info(...$){this.log(1,...$)}warn(...$){this.log(2,...$)}error(...$){this.log(3,...$)}}function Y0($,Y){return new P0({...Y,category:$})}var OK=new P0({category:"General"});var r8=Y0("Service"),E1={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},enabledMcpjsonServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},disabledMcpjsonServers:{target:"settings",defaultScope:"project",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},fallbackModel:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},AK=new Set(Object.entries(E1).filter(([$,Y])=>Y.persistable).map(([$])=>$)),RK=new Set(Object.entries(E1).filter(([$,Y])=>!Y.persistable).map(([$])=>$)),bK=new Set(Object.entries(E1).filter(([$,Y])=>Y.target==="config").map(([$])=>$)),VK=new Set(Object.entries(E1).filter(([$,Y])=>Y.target==="settings").map(([$])=>$));class V1{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!V1.instance)V1.instance=new V1;return V1.instance}static resetInstance(){if(V1.instance)for(let $ of V1.instance.timers.values())clearTimeout($);V1.instance=null}async save($,Y={}){this.validatePersistableFields($);let Z=this.groupUpdatesByTarget($,Y.scope);if(Y.immediate)await Promise.all(Array.from(Z.entries()).map(([X,Q])=>this.flushTarget(X,Q)));else for(let[X,Q]of Z)this.scheduleSave(X,Q)}async flush(){for(let Y of this.timers.values())clearTimeout(Y);this.timers.clear();let $=Array.from(this.pendingUpdates.entries()).map(([Y,Z])=>this.flushTarget(Y,Z));this.pendingUpdates.clear(),await Promise.all($)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule($,Y={}){let Z=Y.scope??"local",X=this.resolveFilePath("settings",Z);await this.flushTargetWithModifier(X,(Q)=>{let J=Q.permissions??{allow:[],ask:[],deny:[]},q={allow:this.dedupeArray([...J.allow||[],$]),ask:J.ask||[],deny:J.deny||[]};return{...Q,permissions:q}})}async appendLocalPermissionRule($,Y={}){await this.appendPermissionRule($,{...Y,scope:"local"})}validatePersistableFields($){for(let Y of Object.keys($)){let Z=E1[Y];if(!Z)throw Error(`Unknown config field: ${Y}`);if(!Z.persistable)throw Error(`Field "${Y}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget($,Y){let Z=new Map;for(let[X,Q]of Object.entries($)){let J=E1[X];if(!J)continue;let q=Y??J.defaultScope,G=this.resolveFilePath(J.target,q);if(!Z.has(G))Z.set(G,{});Z.get(G)[X]=Q}return Z}resolveFilePath($,Y){if($==="config")return Y==="global"?y1.join(i8.homedir(),".blade","config.json"):y1.join(process.cwd(),".blade","config.json");switch(Y){case"local":return y1.join(process.cwd(),".blade","settings.local.json");case"project":return y1.join(process.cwd(),".blade","settings.json");case"global":return y1.join(i8.homedir(),".blade","settings.json");default:return y1.join(process.cwd(),".blade","settings.local.json")}}scheduleSave($,Y){let Z=this.pendingUpdates.get($)??{},X=this.mergePendingUpdates(Z,Y);this.pendingUpdates.set($,X);let Q=this.timers.get($);if(Q)clearTimeout(Q);let J=setTimeout(async()=>{let q=this.pendingUpdates.get($);if(q){this.pendingUpdates.delete($),this.timers.delete($);try{await this.flushTarget($,q),this.lastSaveError=null}catch(G){let K=G instanceof Error?G:Error(String(G));this.lastSaveError=K,r8.error(`Failed to save config to ${$}:`,K.message),r8.error("Stack trace:",K.stack)}}},this.debounceDelay);this.timers.set($,J)}mergePendingUpdates($,Y){let Z={...$};for(let[X,Q]of Object.entries(Y)){let J=E1[X];if(!J){Z[X]=Q;continue}switch(J.mergeStrategy){case"replace":Z[X]=Q;break;case"append-dedupe":this.applyAppendDedupe(Z,X,Q);break;case"deep-merge":this.applyDeepMerge(Z,X,Q);break}}return Z}async flushTarget($,Y){let Z=this.fileLocks.get($);if(!Z)Z=new l8,this.fileLocks.set($,Z);await Z.runExclusive(async()=>{await this.performWrite($,Y)})}async flushTargetWithModifier($,Y){let Z=this.fileLocks.get($);if(!Z)Z=new l8,this.fileLocks.set($,Z);await Z.runExclusive(async()=>{await w2.mkdir(y1.dirname($),{recursive:!0});let X={};try{let J=await w2.readFile($,"utf-8");X=JSON.parse(J)}catch{X={}}let Q=Y(X);await this.atomicWrite($,Q)})}async performWrite($,Y){await w2.mkdir(y1.dirname($),{recursive:!0});let Z={};try{let Q=await w2.readFile($,"utf-8");Z=JSON.parse(Q)}catch{Z={}}let X={...Z};for(let[Q,J]of Object.entries(Y)){let q=E1[Q];if(!q){X[Q]=J;continue}switch(q.mergeStrategy){case"replace":X[Q]=J;break;case"append-dedupe":this.applyAppendDedupe(X,Q,J);break;case"deep-merge":this.applyDeepMerge(X,Q,J);break}}await this.atomicWrite($,X)}applyAppendDedupe($,Y,Z){if(Y==="permissions"&&typeof Z==="object"&&Z!==null){let X=$[Y]??{allow:[],ask:[],deny:[]},Q=Z;$[Y]={allow:this.dedupeArray([...X.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...X.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...X.deny||[],...Q.deny||[]])}}else if(Array.isArray(Z)){let X=Array.isArray($[Y])?$[Y]:[];$[Y]=this.dedupeArray([...X,...Z])}else $[Y]=Z}applyDeepMerge($,Y,Z){if(typeof Z==="object"&&Z!==null&&!Array.isArray(Z)){let X=typeof $[Y]==="object"&&$[Y]!==null?$[Y]:{};$[Y]=nY({},X,Z)}else $[Y]=Z}dedupeArray($){return Array.from(new Set($))}async atomicWrite($,Y){await oY($,JSON.stringify(Y,null,2),{mode:384,encoding:"utf-8"})}}function D0(){return V1.getInstance()}import m$ from"picomatch";class i1{config;constructor($){this.config=$}check($){let Y=i1.buildSignature($),Z=this.matchRules(Y,this.config.deny);if(Z)return{result:"deny",matchedRule:Z.rule,matchType:Z.type,reason:`工具调用被拒绝规则阻止: ${Z.rule}`};let X=this.matchRules(Y,this.config.allow);if(X)return{result:"allow",matchedRule:X.rule,matchType:X.type,reason:`工具调用符合允许规则: ${X.rule}`};let Q=this.matchRules(Y,this.config.ask);if(Q)return{result:"ask",matchedRule:Q.rule,matchType:Q.type,reason:`工具调用需要用户确认: ${Q.rule}`};return{result:"ask",reason:"工具调用未匹配任何规则,默认需要确认"}}static buildSignature($){let{toolName:Y,params:Z,tool:X}=$;try{if(X?.extractSignatureContent){let Q=X.extractSignatureContent(Z);return Q?`${Y}(${Q})`:Y}return Y}catch(Q){return console.warn(`Failed to build signature for ${Y}:`,Q instanceof Error?Q.message:Q),Y}}static abstractPattern($){let{toolName:Y,params:Z,tool:X}=$;try{if(X?.abstractPermissionRule){let Q=X.abstractPermissionRule(Z);if(Q==="")return"";return Q?`${Y}(${Q})`:Y}return Y}catch(Q){return console.warn(`Failed to abstract pattern for ${Y}:`,Q instanceof Error?Q.message:Q),Y}}matchRules($,Y){for(let Z of Y){let X=this.matchRule($,Z);if(X)return{rule:Z,type:X}}return null}matchRule($,Y){if($===Y)return"exact";if(Y==="*"||Y==="**")return"wildcard";let Z=this.extractToolName($),X=this.extractToolName(Y);if(!Z||!X)return null;if(X.includes("*")){if(!m$.isMatch(Z,X,{dot:!0,bash:!0}))return null}else if(Z!==X)return null;if(Y===X)return"prefix";if(Y.includes("*")){let Q=this.extractParams($),J=this.extractParams(Y);if(J==="*"||J==="**")return"wildcard";if(this.matchParams(Q,J))return J.includes("**")?"glob":"wildcard";if(m$.isMatch($,Y,{dot:!0,bash:!0}))return Y.includes("**")?"glob":"wildcard"}return null}extractParams($){let Y=$.match(/\(([\s\S]*)\)$/);return Y?Y[1]:""}matchParams($,Y){if(!$||!Y)return!1;let Z=this.parseParamPairs($),X=this.parseParamPairs(Y),Q=Object.keys(X).length>0,J=Object.keys(Z).length>0;if(Q!==J)return!1;if(!Q&&!J){if(Y==="*"||Y==="**")return!0;if(Y.includes("*")||Y.includes("{")||Y.includes("?"))return m$.isMatch($,Y,{dot:!0,bash:!0});return $===Y}for(let[q,G]of Object.entries(X)){let K=Z[q];if(K===void 0)return!1;if(G.includes("*")||G.includes("{")||G.includes("?")){if(G==="*"||G==="**")continue;if(!m$.isMatch(K,G,{dot:!0,bash:!0}))return!1}else if(K!==G)return!1}return!0}parseParamPairs($){let Y={},Z=this.smartSplit($,",");for(let X of Z){let Q=this.findTopLevelDelimiter(X,":");if(Q>0){let J=X.slice(0,Q).trim(),q=X.slice(Q+1).trim();Y[J]=q}}return Y}smartSplit($,Y){let Z=[],X="",Q=0,J=0,q=0,G=!1,K="",W=!1;for(let O=0;O<$.length;O++){let U=$[O];if(W){X+=U,W=!1;continue}if(U==="\\"){X+=U,W=!0;continue}if(!G&&U==="{")Q++;else if(!G&&U==="}")Q--;else if(!G&&U==="(")J++;else if(!G&&U===")")J--;else if(!G&&U==="[")q++;else if(!G&&U==="]")q--;if((U==='"'||U==="'")&&!G){G=!0,K=U,X+=U;continue}else if(G&&U===K){G=!1,K="",X+=U;continue}if(U===Y&&Q===0&&J===0&&q===0&&!G)Z.push(X.trim()),X="";else X+=U}if(X)Z.push(X.trim());return Z}findTopLevelDelimiter($,Y){let Z=0,X=0,Q=0,J=!1,q="",G=!1;for(let K=0;K<$.length;K++){let W=$[K];if(G){G=!1;continue}if(W==="\\"){G=!0;continue}if(!J&&W==="{")Z++;else if(!J&&W==="}")Z--;else if(!J&&W==="(")X++;else if(!J&&W===")")X--;else if(!J&&W==="[")Q++;else if(!J&&W==="]")Q--;if((W==='"'||W==="'")&&!J){J=!0,q=W;continue}else if(J&&W===q){J=!1,q="";continue}if(W===Y&&Z===0&&X===0&&Q===0&&!J)return K}return-1}extractToolName($){let Y=$.match(/^([A-Za-z0-9_]+)(\(|$)/);return Y?Y[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}}}import{nanoid as X7}from"nanoid";import{devtools as Q7,subscribeWithSelector as J7}from"zustand/middleware";import{createStore as q7}from"zustand/vanilla";var tY={initializationStatus:"idle",initializationError:null,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null,todos:[],awaitingSecondCtrlC:!1},v6=($)=>({...tY,actions:{setInitializationStatus:(Y)=>{$((Z)=>({app:{...Z.app,initializationStatus:Y}}))},setInitializationError:(Y)=>{$((Z)=>({app:{...Z.app,initializationError:Y}}))},setActiveModal:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:Y}}))},showSessionSelector:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:"sessionSelector",sessionSelectorData:Y}}))},showModelEditWizard:(Y)=>{$((Z)=>({app:{...Z.app,activeModal:"modelEditWizard",modelEditorTarget:Y}}))},closeModal:()=>{$((Y)=>({app:{...Y.app,activeModal:"none",sessionSelectorData:void 0,modelEditorTarget:null}}))},setTodos:(Y)=>{$((Z)=>({app:{...Z.app,todos:Y}}))},updateTodo:(Y)=>{$((Z)=>({app:{...Z.app,todos:Z.app.todos.map((X)=>X.id===Y.id?Y:X)}}))},setAwaitingSecondCtrlC:(Y)=>{$((Z)=>({app:{...Z.app,awaitingSecondCtrlC:Y}}))}}});var eY={isProcessing:!1,abortController:null,pendingCommands:[]},M6=($,Y)=>({...eY,actions:{setProcessing:(Z)=>{$((X)=>({command:{...X.command,isProcessing:Z}}))},createAbortController:()=>{let Z=new AbortController;return $((X)=>({command:{...X.command,abortController:Z}})),Z},clearAbortController:()=>{$((Z)=>({command:{...Z.command,abortController:null}}))},abort:()=>{let{abortController:Z}=Y().command;if(Z&&!Z.signal.aborted)Z.abort();Y().session.actions.setThinking(!1),$((X)=>({command:{...X.command,isProcessing:!1,abortController:null,pendingCommands:[]}}))},enqueueCommand:(Z)=>{$((X)=>({command:{...X.command,pendingCommands:[...X.command.pendingCommands,Z]}}))},dequeueCommand:()=>{let{pendingCommands:Z}=Y().command;if(Z.length===0)return;let[X,...Q]=Z;return $((J)=>({command:{...J.command,pendingCommands:Q}})),X},clearQueue:()=>{$((Z)=>({command:{...Z.command,pendingCommands:[]}}))}}});var $7={config:null},y6=($)=>({...$7,actions:{setConfig:(Y)=>{$((Z)=>({config:{...Z.config,config:Y}}))},updateConfig:(Y)=>{$((Z)=>{if(!Z.config.config)throw Error(`[ConfigSlice] Config not initialized. Cannot update: ${JSON.stringify(Y)}`);return{config:{...Z.config,config:{...Z.config.config,...Y}}}})}}});var Y7={currentFocus:"main-input",previousFocus:null},E6=($)=>({...Y7,actions:{setFocus:(Y)=>{$((Z)=>({focus:{...Z.focus,currentFocus:Y,previousFocus:Z.focus.currentFocus}}))},restorePreviousFocus:()=>{$((Y)=>({focus:{...Y.focus,currentFocus:Y.focus.previousFocus||"main-input",previousFocus:null}}))}}});import{nanoid as Z7}from"nanoid";var n8={inputTokens:0,outputTokens:0,totalTokens:0,maxContextTokens:200000},a8={sessionId:Z7(),messages:[],isThinking:!1,isCompacting:!1,currentCommand:null,error:null,isActive:!0,tokenUsage:{...n8}},j6=($,Y)=>({...a8,actions:{addMessage:(Z)=>{$((X)=>({session:{...X.session,messages:[...X.session.messages,Z],error:null}}))},addUserMessage:(Z)=>{let X={id:`user-${Date.now()}-${Math.random()}`,role:"user",content:Z,timestamp:Date.now()};Y().session.actions.addMessage(X)},addAssistantMessage:(Z)=>{let X={id:`assistant-${Date.now()}-${Math.random()}`,role:"assistant",content:Z,timestamp:Date.now()};Y().session.actions.addMessage(X)},addToolMessage:(Z,X)=>{let Q={id:`tool-${Date.now()}-${Math.random()}`,role:"tool",content:Z,timestamp:Date.now(),metadata:X};Y().session.actions.addMessage(Q)},setThinking:(Z)=>{$((X)=>({session:{...X.session,isThinking:Z}}))},setCompacting:(Z)=>{$((X)=>({session:{...X.session,isCompacting:Z}}))},setCommand:(Z)=>{$((X)=>({session:{...X.session,currentCommand:Z}}))},setError:(Z)=>{$((X)=>({session:{...X.session,error:Z}}))},clearMessages:()=>{$((Z)=>({session:{...Z.session,messages:[],error:null}}))},resetSession:()=>{$((Z)=>({session:{...Z.session,...a8,sessionId:Z.session.sessionId,isActive:!0}}))},restoreSession:(Z,X)=>{$((Q)=>({session:{...Q.session,sessionId:Z,messages:X,error:null,isActive:!0}}))},updateTokenUsage:(Z)=>{$((X)=>({session:{...X.session,tokenUsage:{...X.session.tokenUsage,...Z}}}))},resetTokenUsage:()=>{$((Z)=>({session:{...Z.session,tokenUsage:{...n8}}}))}}});var u$=q7()(Q7(J7((...$)=>({session:j6(...$),app:v6(...$),config:y6(...$),focus:E6(...$),command:M6(...$)})),{name:"BladeStore",enabled:!0})),s=()=>u$.getState(),G7=u$.subscribe,o=()=>s().session.actions,Z1=()=>s().app.actions;var F0=()=>s().config.config,W$=null;async function A2(){if(F0()!==null)return;if(W$)return W$;return W$=(async()=>{try{let Z=await V0.getInstance().initialize();s().config.actions.setConfig(Z)}catch(Y){throw W$=null,Error(`❌ Store 未初始化且无法自动初始化
|
|
30
30
|
|
|
31
31
|
`+`原因: ${Y instanceof Error?Y.message:"未知错误"}
|
|
32
32
|
|
|
33
33
|
`+`请确保:
|
|
34
34
|
`+`1. 配置文件格式正确 (~/.blade/config.json)
|
|
35
35
|
`+`2. 运行 blade 进行首次配置
|
|
36
|
-
`+"3. 配置文件权限正确")}finally{
|
|
36
|
+
`+"3. 配置文件权限正确")}finally{W$=null}})(),W$}var d$=()=>s().config.config?.models??[],R2=()=>{let $=F0();if(!$)return;let Y=$.currentModelId;return $.models.find((X)=>X.id===Y)??$.models[0]},H1=()=>s().config.config?.mcpServers??{};var e=()=>({setPermissionMode:async($)=>{s().config.actions.updateConfig({permissionMode:$})},setTheme:async($,Y={})=>{s().config.actions.updateConfig({theme:$}),await D0().save({theme:$},{scope:"global",...Y})},setLanguage:async($,Y={})=>{s().config.actions.updateConfig({language:$}),await D0().save({language:$},{scope:"global",...Y})},setDebug:async($,Y={})=>{s().config.actions.updateConfig({debug:$}),await D0().save({debug:$},{scope:"global",...Y})},setTemperature:async($,Y={})=>{s().config.actions.updateConfig({temperature:$}),await D0().save({temperature:$},{scope:"global",...Y})},updateConfig:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");let X={...Z};s().config.actions.updateConfig($);try{await D0().save($,Y)}catch(Q){throw s().config.actions.setConfig(X),Q}},flush:async()=>{await D0().flush()},appendPermissionAllowRule:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");let X=Z.permissions?.allow||[];if(!X.includes($)){let Q=[...X,$];s().config.actions.updateConfig({permissions:{...Z.permissions,allow:Q}})}await D0().appendPermissionRule($,Y)},appendLocalPermissionAllowRule:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");let X=Z.permissions?.allow||[];if(!X.includes($)){let Q=[...X,$];s().config.actions.updateConfig({permissions:{...Z.permissions,allow:Q}})}await D0().appendLocalPermissionRule($,Y)},setCurrentModel:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");if(!Z.models.find((Q)=>Q.id===$))throw Error(`Model not found: ${$}`);s().config.actions.updateConfig({currentModelId:$}),await D0().save({currentModelId:$},{scope:"global",...Y})},addModel:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");let X="id"in $?$:{id:X7(),...$},J={models:[...Z.models,X]};if(Z.models.length===0)J.currentModelId=X.id;return s().config.actions.updateConfig(J),await D0().save(J,{scope:"global",...Y}),X},updateModel:async($,Y,Z={})=>{let X=F0();if(!X)throw Error("Config not initialized");let Q=X.models.findIndex((q)=>q.id===$);if(Q===-1)throw Error(`Model not found: ${$}`);let J=[...X.models];J[Q]={...J[Q],...Y},s().config.actions.updateConfig({models:J}),await D0().save({models:J},{scope:"global",...Z})},removeModel:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");if(Z.models.length===1)throw Error("Cannot remove the only model");let X=Z.models.filter((J)=>J.id!==$),Q={models:X};if(Z.currentModelId===$)Q.currentModelId=X[0].id;s().config.actions.updateConfig(Q),await D0().save(Q,{scope:"global",...Y})},addMcpServer:async($,Y,Z={})=>{let X=F0();if(!X)throw Error("Config not initialized");let J={...X.mcpServers??{},[$]:Y};s().config.actions.updateConfig({mcpServers:J}),await D0().save({mcpServers:J},{scope:"project",...Z})},removeMcpServer:async($,Y={})=>{let Z=F0();if(!Z)throw Error("Config not initialized");let Q={...Z.mcpServers??{}};delete Q[$],s().config.actions.updateConfig({mcpServers:Q}),await D0().save({mcpServers:Q},{scope:"project",...Y})},resetProjectChoices:async($={})=>{if(!F0())throw Error("Config not initialized");let Z={enabledMcpjsonServers:[],disabledMcpjsonServers:[]};s().config.actions.updateConfig(Z),await D0().save(Z,{scope:"project",...$})}});var b2=Y0("General"),o8=($)=>{if($.yolo){if($.permissionMode&&$.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");$.permissionMode="yolo"}if(Array.isArray($.allowedTools)&&Array.isArray($.disallowedTools)){let Y=$.allowedTools.filter((Z)=>$.disallowedTools.includes(Z));if(Y.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${Y.join(", ")}`)}},s8=async($)=>{try{let Z=await V0.getInstance().initialize();if(s().config.actions.setConfig(Z),$.debug)b2.info("[CLI] Store 已初始化")}catch(Y){b2.error("[CLI] ❌ 配置初始化失败,无法继续执行命令",Y instanceof Error?Y.message:Y),console.error(`
|
|
37
37
|
❌ 配置初始化失败
|
|
38
38
|
`),console.error("原因:",Y instanceof Error?Y.message:"未知错误"),console.error(`
|
|
39
39
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
40
|
-
`),process.exit(1)}if(typeof $.settingSources==="string"){let Y=$.settingSources.split(",").map((Z)=>Z.trim());if($.debug)
|
|
40
|
+
`),process.exit(1)}if(typeof $.settingSources==="string"){let Y=$.settingSources.split(",").map((Z)=>Z.trim());if($.debug)b2.info(`Loading configuration from: ${Y.join(", ")}`)}if($.continue&&$.resume)throw Error("Cannot use both --continue and --resume flags simultaneously")},t8=($)=>{if($.outputFormat&&$.outputFormat!=="text"&&!$.print)throw Error("--output-format can only be used with --print flag");if($.inputFormat==="stream-json"&&$.print)b2.warn("⚠️ Warning: stream-json input format may not work as expected with --print")};var e8={command:"doctor",describe:"Check the health of your Blade installation",handler:async()=>{console.log(`\uD83D\uDD0D Running Blade health check...
|
|
41
41
|
`);let $=0;try{await V0.getInstance().initialize(),console.log("✅ Configuration: OK")}catch(X){console.log("❌ Configuration: FAILED"),console.log(` Error: ${X instanceof Error?X.message:"未知错误"}`),$++}let Y=process.version;if(parseInt(Y.slice(1).split(".")[0])>=18)console.log(`✅ Node.js version: ${Y}`);else console.log(`⚠️ Node.js version: ${Y} (recommended: v18+)`),$++;try{let X=await import("fs/promises"),Q=process.cwd();await X.access(Q,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("✅ File system permissions: OK")}catch(X){console.log("❌ File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),$++}try{await import("ink"),console.log("✅ Dependencies: OK")}catch(X){console.log("❌ Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),$++}if(console.log(`
|
|
42
|
-
\uD83D\uDCCA Health Check Summary:`),$===0)console.log("\uD83C\uDF89 All checks passed! Blade is ready to use.");else console.log(`⚠️ Found ${$} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};var
|
|
42
|
+
\uD83D\uDCCA Health Check Summary:`),$===0)console.log("\uD83C\uDF89 All checks passed! Blade is ready to use.");else console.log(`⚠️ Found ${$} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};var $9={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:($)=>{return $.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async($)=>{console.log(`\uD83D\uDCE6 Installing Blade ${$.target}...`);try{if($.force)console.log("\uD83D\uDD04 Force reinstall enabled");console.log("⬇️ Downloading..."),console.log("\uD83D\uDD27 Installing..."),console.log("✅ Installation completed successfully")}catch(Y){console.error(`❌ Installation failed: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}};import{EventEmitter as L7}from"events";import{z as c0}from"zod";function c$($){return $==="readonly"}class P6{toolName;params;context;aborted=!1;result;_internal={};constructor($,Y,Z){this.toolName=$;this.params=Y;this.context=Z}shouldAbort(){return this.aborted||(this.context.signal?.aborted??!1)}abort($){this.aborted=!0,this.result={success:!1,llmContent:`Tool execution aborted: ${$||"Unknown reason"}`,displayContent:`执行已中止: ${$||"未知原因"}`,error:{type:"execution_error",message:$||"Execution aborted"}}}setResult($){this.result=$}getResult(){if(!this.result)throw Error("Tool execution result not set");return this.result}}class Y9 extends Error{issues;type;constructor($,Y,Z="validation_error"){super($);this.issues=Y;this.type=Z;this.name="ToolValidationError"}}function K7($){let{code:Y}=$,Z=$.received;switch(Y){case"invalid_type":return`类型错误:期望 ${$.expected},实际收到 ${Z}`;case"too_small":{let{minimum:X,inclusive:Q}=$;if($.type==="string")return`长度不能少于 ${X} 个字符`;if($.type==="number")return`不能小于${Q?"等于":""} ${X}`;if($.type==="array")return`数组长度不能少于 ${X}`;return"值太小"}case"too_big":{let{maximum:X,inclusive:Q}=$;if($.type==="string")return`长度不能超过 ${X} 个字符`;if($.type==="number")return`不能大于${Q?"等于":""} ${X}`;if($.type==="array")return`数组长度不能超过 ${X}`;return"值太大"}case"invalid_string":{let X=$.validation;if(X==="email")return"必须是有效的电子邮件地址";if(X==="url")return"必须是有效的 URL";if(X==="uuid")return"必须是有效的 UUID";if(typeof X==="object"&&X.includes)return`必须包含 "${X.includes}"`;if(typeof X==="object"&&X.startsWith)return`必须以 "${X.startsWith}" 开头`;if(typeof X==="object"&&X.endsWith)return`必须以 "${X.endsWith}" 结尾`;return"字符串格式不正确"}case"invalid_enum_value":return`必须是以下值之一:${$.options.join(", ")}`;case"invalid_literal":return`必须是字面量值:${$.expected}`;case"unrecognized_keys":return`包含未知的参数:${$.keys.join(", ")}`;case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return $.message||"自定义验证失败";default:return $.message||"验证失败"}}function W7($){let Y=$.issues.map((X)=>{let Q=X.path.join("."),J=K7(X),q=X.received;return{field:Q||"root",message:J,value:q}}),Z=Y.length===1?`参数验证失败 [${Y[0].field}]: ${Y[0].message}`:`参数验证失败 (${Y.length} 个错误):
|
|
43
43
|
${Y.map((X)=>` - ${X.field}: ${X.message}`).join(`
|
|
44
|
-
`)}`;return new
|
|
44
|
+
`)}`;return new Y9(Z,Y)}function Z9($,Y){let Z=$.safeParse(Y);if(!Z.success)throw W7(Z.error);return Z.data}import{zodToJsonSchema as U7}from"zod-to-json-schema";function S6($){return U7($,{target:"jsonSchema7",$refStrategy:"none"})}class T6{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor($,Y,Z,X,Q){this.toolName=$;this.params=Y;this.executeFn=Z;this.descriptionFn=X;this.affectedPathsFn=Q}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute($,Y,Z){let X={signal:$,updateOutput:Y,...Z};return this.executeFn(this.params,X)}}function n($){return{name:$.name,displayName:$.displayName,kind:$.kind,isReadOnly:$.isReadOnly??c$($.kind),isConcurrencySafe:$.isConcurrencySafe??!0,strict:$.strict??!1,description:$.description,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],getFunctionDeclaration(){let Y=S6($.schema),Z=$.description.short;if($.description.long)Z+=`
|
|
45
45
|
|
|
46
46
|
${$.description.long}`;if($.description.usageNotes&&$.description.usageNotes.length>0)Z+=`
|
|
47
47
|
|
|
@@ -51,12 +51,12 @@ ${$.description.usageNotes.map((X)=>`- ${X}`).join(`
|
|
|
51
51
|
|
|
52
52
|
Important:
|
|
53
53
|
${$.description.important.map((X)=>`⚠️ ${X}`).join(`
|
|
54
|
-
`)}`;return{name:$.name,description:Z,parameters:Y}},getMetadata(){return{name:$.name,displayName:$.displayName,kind:$.kind,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],description:$.description,schema:
|
|
54
|
+
`)}`;return{name:$.name,description:Z,parameters:Y}},getMetadata(){return{name:$.name,displayName:$.displayName,kind:$.kind,version:$.version||"1.0.0",category:$.category,tags:$.tags||[],description:$.description,schema:S6($.schema)}},build(Y){let Z=Z9($.schema,Y);return new T6($.name,Z,$.execute)},async execute(Y,Z){return this.build(Y).execute(Z||new AbortController().signal)},extractSignatureContent:$.extractSignatureContent?(Y)=>$.extractSignatureContent(Y):void 0,abstractPermissionRule:$.abstractPermissionRule?(Y)=>$.abstractPermissionRule(Y):void 0}}function V2($,Y,Z,X){let Q;try{Q=l$(Z.inputSchema)}catch(q){console.warn(`[createMcpTool] Schema 转换失败,使用降级 schema: ${Z.name}`,q),Q=c0.any()}let J=X||Z.name;return n({name:J,displayName:`${Y}: ${Z.name}`,kind:"execute",schema:Q,description:{short:Z.description||`MCP Tool: ${Z.name}`,important:[`From MCP server: ${Y}`,"Executes external tools; user confirmation required"]},category:"MCP tool",tags:["mcp","external",Y],async execute(q,G){try{let K=await $.callTool(Z.name,q),W="",O="";if(K.content&&Array.isArray(K.content)){for(let U of K.content)if(U.type==="text"&&U.text)W+=U.text,O+=U.text;else if(U.type==="image")O+=`[图片: ${U.mimeType||"unknown"}]
|
|
55
55
|
`,W+=`[image: ${U.mimeType||"unknown"}]
|
|
56
56
|
`;else if(U.type==="resource")O+=`[资源: ${U.mimeType||"unknown"}]
|
|
57
57
|
`,W+=`[resource: ${U.mimeType||"unknown"}]
|
|
58
58
|
`}if(K.isError)return{success:!1,llmContent:W||"MCP tool execution failed",displayContent:`❌ ${O||"MCP工具执行失败"}`,error:{type:"execution_error",message:W||"MCP tool execution failed"}};return{success:!0,llmContent:W||"Execution succeeded",displayContent:`✅ MCP工具 ${Z.name} 执行成功
|
|
59
|
-
${O}`,metadata:{serverName:Y,toolName:Z.name,mcpResult:K}}}catch(K){return{success:!1,llmContent:`MCP tool execution failed: ${K.message}`,displayContent:`❌ ${K.message}`,error:{type:"execution_error",message:K.message}}}}})}function
|
|
59
|
+
${O}`,metadata:{serverName:Y,toolName:Z.name,mcpResult:K}}}catch(K){return{success:!1,llmContent:`MCP tool execution failed: ${K.message}`,displayContent:`❌ ${K.message}`,error:{type:"execution_error",message:K.message}}}}})}function l$($){if($.type==="object"||$.properties){let Y={},Z=$.required||[];if($.properties){for(let[X,Q]of Object.entries($.properties))if(typeof Q==="object"&&Q!==null){let J=l$(Q);if(!Z.includes(X))J=J.optional();Y[X]=J}}return c0.object(Y)}if($.type==="array"&&$.items){if(typeof $.items==="object"&&!Array.isArray($.items)&&$.items!==null)return c0.array(l$($.items));return c0.array(c0.any())}if($.type==="string"){let Y=c0.string();if($.minLength!==void 0)Y=Y.min($.minLength);if($.maxLength!==void 0)Y=Y.max($.maxLength);if($.pattern)Y=Y.regex(new RegExp($.pattern));if($.enum)return c0.enum($.enum);return Y}if($.type==="number"||$.type==="integer"){let Y=c0.number();if($.minimum!==void 0)Y=Y.min($.minimum);if($.maximum!==void 0)Y=Y.max($.maximum);return Y}if($.type==="boolean")return c0.boolean();if($.oneOf&&$.oneOf.length>0){let Y=$.oneOf.filter((Z)=>typeof Z==="object"&&Z!==null).map((Z)=>l$(Z));if(Y.length>=2)return c0.union(Y)}if($.anyOf&&$.anyOf.length>0){let Y=$.anyOf.filter((Z)=>typeof Z==="object"&&Z!==null).map((Z)=>l$(Z));if(Y.length>=2)return c0.union(Y)}return c0.any()}import{Client as F7}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as z7}from"@modelcontextprotocol/sdk/client/sse.js";import{StdioClientTransport as N7}from"@modelcontextprotocol/sdk/client/stdio.js";import{EventEmitter as B7}from"events";import*as r$ from"crypto";import*as J9 from"http";import{spawn as H7}from"child_process";import{URL as X9}from"url";import{promises as C6}from"fs";import O7 from"os";import f6 from"path";class D2{tokenFilePath;constructor(){let $=O7.homedir(),Y=f6.join($,".blade");this.tokenFilePath=f6.join(Y,"mcp-oauth-tokens.json")}async ensureConfigDir(){let $=f6.dirname(this.tokenFilePath);try{await C6.mkdir($,{recursive:!0})}catch(Y){}}async loadAllCredentials(){let $=new Map;try{let Y=await C6.readFile(this.tokenFilePath,"utf-8"),Z=JSON.parse(Y);for(let X of Z)$.set(X.serverName,X)}catch(Y){if(Y.code!=="ENOENT")console.warn("[OAuthTokenStorage] 加载令牌失败:",Y)}return $}async saveAllCredentials($){await this.ensureConfigDir();let Y=Array.from($.values());await C6.writeFile(this.tokenFilePath,JSON.stringify(Y,null,2),{mode:384})}async saveToken($,Y,Z,X){let Q=await this.loadAllCredentials(),J={serverName:$,token:Y,clientId:Z,tokenUrl:X,updatedAt:Date.now()};Q.set($,J),await this.saveAllCredentials(Q)}async getCredentials($){return(await this.loadAllCredentials()).get($)||null}async deleteCredentials($){let Y=await this.loadAllCredentials();Y.delete($),await this.saveAllCredentials(Y)}async listServers(){let $=await this.loadAllCredentials();return Array.from($.keys())}isTokenExpired($){if(!$.expiresAt)return!1;let Y=300000;return Date.now()>=$.expiresAt-Y}}var i$=7777,h6="/oauth/callback",Q9=200;class I2{tokenStorage;constructor($=new D2){this.tokenStorage=$}generatePKCEParams(){let $=r$.randomBytes(32).toString("base64url"),Y=r$.createHash("sha256").update($).digest("base64url"),Z=r$.randomBytes(16).toString("base64url");return{codeVerifier:$,codeChallenge:Y,state:Z}}buildAuthorizationUrl($,Y){let Z=$.redirectUri||`http://localhost:${i$}${h6}`,X=new URLSearchParams({client_id:$.clientId,response_type:"code",redirect_uri:Z,state:Y.state,code_challenge:Y.codeChallenge,code_challenge_method:"S256"});if($.scopes&&$.scopes.length>0)X.append("scope",$.scopes.join(" "));let Q=new X9($.authorizationUrl);return X.forEach((J,q)=>{Q.searchParams.append(q,J)}),Q.toString()}async startCallbackServer($){return new Promise((Y,Z)=>{let X=J9.createServer((Q,J)=>{try{let q=new X9(Q.url,`http://localhost:${i$}`);if(q.pathname!==h6){J.writeHead(404),J.end("Not found");return}let G=q.searchParams.get("code"),K=q.searchParams.get("state"),W=q.searchParams.get("error");if(W){J.writeHead(Q9,{"Content-Type":"text/html"}),J.end(`
|
|
60
60
|
<html>
|
|
61
61
|
<body>
|
|
62
62
|
<h1>Authentication Failed</h1>
|
|
@@ -64,7 +64,7 @@ ${O}`,metadata:{serverName:Y,toolName:Z.name,mcpResult:K}}}catch(K){return{succe
|
|
|
64
64
|
<p>You can close this window.</p>
|
|
65
65
|
</body>
|
|
66
66
|
</html>
|
|
67
|
-
`),X.close(),Z(Error(`OAuth error: ${W}`));return}if(!
|
|
67
|
+
`),X.close(),Z(Error(`OAuth error: ${W}`));return}if(!G||!K){J.writeHead(400),J.end("Missing code or state parameter");return}if(K!==$){J.writeHead(400),J.end("Invalid state parameter"),X.close(),Z(Error("State mismatch - possible CSRF attack"));return}J.writeHead(Q9,{"Content-Type":"text/html"}),J.end(`
|
|
68
68
|
<html>
|
|
69
69
|
<body>
|
|
70
70
|
<h1>Authentication Successful!</h1>
|
|
@@ -72,32 +72,32 @@ ${O}`,metadata:{serverName:Y,toolName:Z.name,mcpResult:K}}}catch(K){return{succe
|
|
|
72
72
|
<script>window.close();</script>
|
|
73
73
|
</body>
|
|
74
74
|
</html>
|
|
75
|
-
`),X.close(),Y(
|
|
75
|
+
`),X.close(),Y(G)}catch(q){X.close(),Z(q)}});X.on("error",Z),X.listen(i$,()=>{console.log(`[OAuth] Callback server listening on port ${i$}`)}),setTimeout(()=>{X.close(),Z(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken($,Y,Z){let X=$.redirectUri||`http://localhost:${i$}${h6}`,Q=new URLSearchParams({grant_type:"authorization_code",code:Y,redirect_uri:X,code_verifier:Z,client_id:$.clientId});if($.clientSecret)Q.append("client_secret",$.clientSecret);let J=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!J.ok){let q=await J.text();throw Error(`Token exchange failed: ${J.status} - ${q}`)}return await J.json()}async refreshAccessToken($,Y){let Z=new URLSearchParams({grant_type:"refresh_token",refresh_token:Y,client_id:$.clientId});if($.clientSecret)Z.append("client_secret",$.clientSecret);if($.scopes&&$.scopes.length>0)Z.append("scope",$.scopes.join(" "));let X=await fetch($.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()});if(!X.ok){let Q=await X.text();throw Error(`Token refresh failed: ${X.status} - ${Q}`)}return await X.json()}async authenticate($,Y){if(!Y.clientId||!Y.authorizationUrl||!Y.tokenUrl)throw Error("Missing required OAuth configuration");let Z=this.generatePKCEParams(),X=this.buildAuthorizationUrl(Y,Z);console.log(`
|
|
76
76
|
[OAuth] Opening browser for authentication...`),console.log(`
|
|
77
|
-
If the browser does not open automatically, copy and paste this URL:`),console.log(X),console.log("");let Q=this.startCallbackServer(Z.state);try{await this.openAuthorizationUrl(X)}catch(K){console.warn("[OAuth] Failed to open browser automatically:",K)}let J=await Q;console.log("[OAuth] Authorization code received, exchanging for tokens...");let G=await this.exchangeCodeForToken(Y,J,Z.codeVerifier),q={accessToken:G.access_token,tokenType:G.token_type||"Bearer",refreshToken:G.refresh_token,scope:G.scope};if(G.expires_in)q.expiresAt=Date.now()+G.expires_in*1000;return await this.tokenStorage.saveToken($,q,Y.clientId,Y.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl($){let{command:Y,args:Z}=this.getBrowserCommand($);await new Promise((X,Q)=>{let J=q7(Y,Z,{stdio:"ignore"});J.once("error",Q),J.once("close",(G)=>{if(G===0||G===null)X();else Q(Error(`Failed to open browser (exit code ${G})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,Y){let Z=await this.tokenStorage.getCredentials($);if(!Z)return null;let{token:X}=Z;if(!this.tokenStorage.isTokenExpired(X))return X.accessToken;if(X.refreshToken&&Y.clientId&&Z.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let Q=await this.refreshAccessToken(Y,X.refreshToken),J={accessToken:Q.access_token,tokenType:Q.token_type,refreshToken:Q.refresh_token||X.refreshToken,scope:Q.scope||X.scope};if(Q.expires_in)J.expiresAt=Date.now()+Q.expires_in*1000;return await this.tokenStorage.saveToken($,J,Y.clientId,Z.tokenUrl),J.accessToken}catch(Q){console.error("[OAuth] Failed to refresh token:",Q),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as K7}from"events";class C6 extends K7{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,Y={}){super();this.client=$,this.config={interval:Y.interval??30000,timeout:Y.timeout??1e4,enabled:Y.enabled??!1,failureThreshold:Y.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let Y={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",Y),Y}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let Y=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,Y.message);let Z;if(this.consecutiveFailures>=this.config.failureThreshold)Z="unhealthy",this.emit("unhealthy",this.consecutiveFailures,Y),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Q)=>{console.error("[HealthMonitor] 重连失败:",Q)});else Z="degraded";this.setStatus(Z);let X={status:Z,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:Y};return this.emit("healthCheck",X),X}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((Z,X)=>{setTimeout(()=>X(Error("Health check timeout")),this.config.timeout)}),Y=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([Y,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let Y=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,Y)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function X9($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let Y=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Q)=>Y.includes(Q)))return{type:"config_error",isRetryable:!1,originalError:$};if(Y.includes("unauthorized")||Y.includes("401")||Y.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Q)=>Y.includes(Q)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class f6 extends H7{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor($,Y,Z){super();this.config=$;if(this.serverName=Y||"default",$.oauth?.enabled)this.oauthProvider=new V2;if(Z?.enabled)this.healthMonitor=new C6(this,Z),this.healthMonitor.on("unhealthy",(X,Q)=>{this.emit("unhealthy",X,Q)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,Y=1000){if(this.status!=="disconnected")throw Error("客户端已连接或正在连接中");let Z=null;for(let X=1;X<=$;X++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Q){Z=Q;let J=X9(Q);if(!J.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",J.type),Q;if(X<$){let G=Y*Math.pow(2,X-1);console.warn(`[McpClient] 连接失败(${X}/${$}),${G}ms 后重试...`),await new Promise((q)=>setTimeout(q,G))}}throw Z||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new W7({name:P8(),version:F2()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let Y=this.sdkClient.getServerVersion();if(this.serverInfo={name:Y?.name||"Unknown",version:Y?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(Y){if(console.error("[McpClient] 重连失败:",Y),X9(Y).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,Y={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:Y})}catch(Z){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,Z),Z}}async createTransport(){let{type:$,command:Y,args:Z,env:X,url:Q,headers:J,oauth:G}=this.config,q={...J};if(G?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let K=await this.oauthProvider.getValidToken(this.serverName,G);if(!K){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let W=await this.oauthProvider.authenticate(this.serverName,G);q.Authorization=`Bearer ${W.accessToken}`}else q.Authorization=`Bearer ${K}`}catch(K){throw console.error("[McpClient] OAuth 认证失败:",K),Error(`OAuth 认证失败: ${K instanceof Error?K.message:String(K)}`)}if($==="stdio"){if(!Y)throw Error("stdio 传输需要 command 参数");let K={};for(let[W,O]of Object.entries(process.env))if(O!==void 0)K[W]=O;return new O7({command:Y,args:Z||[],env:{...K,...X},stderr:"ignore"})}else if($==="sse"){if(!Q)throw Error("sse 传输需要 url 参数");return new U7(new URL(Q),{requestInit:{headers:q}})}else if($==="http"){if(!Q)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:K}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new K(new URL(Q),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let Y of $.tools)this.tools.set(Y.name,Y);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let Y=this.status;this.status=$,this.emit("statusChanged",$,Y)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,Y){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class v0 extends _7{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!v0.instance)v0.instance=new v0;return v0.instance}async registerServer($,Y){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let Z=new f6(Y,$,Y.healthCheck),X={config:Y,client:Z,status:"disconnected",tools:[]};this.setupClientEventHandlers(Z,X,$),this.servers.set($,X),this.emit("serverRegistered",$,X);try{await this.connectServer($)}catch(Q){console.warn(`MCP服务器 "${$}" 连接失败:`,Q)}}async unregisterServer($){let Y=this.servers.get($);if(!Y)return;try{await Y.client.disconnect()}catch(Z){console.warn(`断开MCP服务器 "${$}" 时出错:`,Z)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let Y=this.servers.get($);if(!Y)throw Error(`MCP服务器 "${$}" 未注册`);if(Y.status==="connected")return;try{Y.status="connecting",await Y.client.connect(),Y.connectedAt=new Date,Y.lastError=void 0,Y.tools=Y.client.availableTools}catch(Z){throw Y.lastError=Z,Y.status="error",Z}}async disconnectServer($){let Y=this.servers.get($);if(!Y)return;await Y.client.disconnect(),Y.connectedAt=void 0}async getAvailableTools(){let $=[],Y=new Map;for(let[Z,X]of this.servers)if(X.status==="connected")for(let Q of X.tools){let J=Y.get(Q.name)||0;Y.set(Q.name,J+1)}for(let[Z,X]of this.servers)if(X.status==="connected")for(let Q of X.tools){let G=(Y.get(Q.name)||0)>1?`${Z}__${Q.name}`:Q.name,q=R2(X.client,Z,Q,G);$.push(q)}return $}async findTool($){for(let[Y,Z]of this.servers)if(Z.status==="connected"){let X=Z.tools.find((Q)=>Q.name===$);if(X)return R2(Z.client,Y,X)}return null}getToolsByServer($){let Y=this.servers.get($);if(!Y||Y.status!=="connected")return[];return Y.tools.map((Z)=>R2(Y.client,$,Z))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[Y,Z]of this.servers)if(Z.status==="connected")$.push(this.refreshServerTools(Y));await Promise.allSettled($)}async refreshServerTools($){let Y=this.servers.get($);if(!Y||Y.status!=="connected")return;try{let Z=Y.client.availableTools,X=Y.tools.length;Y.tools=Z,this.emit("toolsUpdated",$,Z,X)}catch(Z){console.warn(`刷新服务器 "${$}" 工具列表失败:`,Z)}}setupClientEventHandlers($,Y,Z){$.on("connected",(X)=>{Y.status="connected",Y.connectedAt=new Date,Y.tools=$.availableTools,this.emit("serverConnected",Z,X)}),$.on("disconnected",()=>{Y.status="disconnected",Y.connectedAt=void 0,Y.tools=[],this.emit("serverDisconnected",Z)}),$.on("error",(X)=>{Y.status="error",Y.lastError=X,this.emit("serverError",Z,X)}),$.on("toolsUpdated",(X)=>{let Q=Y.tools.length;Y.tools=X,this.emit("toolsUpdated",Z,X,Q)}),$.on("statusChanged",(X,Q)=>{Y.status=X,this.emit("serverStatusChanged",Z,X,Q)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers($){let Y=Object.entries($).map(([Z,X])=>this.registerServer(Z,X).catch((Q)=>{return console.warn(`注册MCP服务器 "${Z}" 失败:`,Q),Q}));await Promise.allSettled(Y)}getStatistics(){let $=0,Y=0,Z=0;for(let X of this.servers.values())if(X.status==="connected")$++,Y+=X.tools.length;else if(X.status==="error")Z++;return{totalServers:this.servers.size,connectedServers:$,errorServers:Z,totalTools:Y,isDiscovering:this.isDiscovering}}}function F7(){console.log(`
|
|
77
|
+
If the browser does not open automatically, copy and paste this URL:`),console.log(X),console.log("");let Q=this.startCallbackServer(Z.state);try{await this.openAuthorizationUrl(X)}catch(K){console.warn("[OAuth] Failed to open browser automatically:",K)}let J=await Q;console.log("[OAuth] Authorization code received, exchanging for tokens...");let q=await this.exchangeCodeForToken(Y,J,Z.codeVerifier),G={accessToken:q.access_token,tokenType:q.token_type||"Bearer",refreshToken:q.refresh_token,scope:q.scope};if(q.expires_in)G.expiresAt=Date.now()+q.expires_in*1000;return await this.tokenStorage.saveToken($,G,Y.clientId,Y.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),G}async openAuthorizationUrl($){let{command:Y,args:Z}=this.getBrowserCommand($);await new Promise((X,Q)=>{let J=H7(Y,Z,{stdio:"ignore"});J.once("error",Q),J.once("close",(q)=>{if(q===0||q===null)X();else Q(Error(`Failed to open browser (exit code ${q})`))})})}getBrowserCommand($){if(process.platform==="darwin")return{command:"open",args:[$]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",$]};return{command:"xdg-open",args:[$]}}async getValidToken($,Y){let Z=await this.tokenStorage.getCredentials($);if(!Z)return null;let{token:X}=Z;if(!this.tokenStorage.isTokenExpired(X))return X.accessToken;if(X.refreshToken&&Y.clientId&&Z.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${$}`);let Q=await this.refreshAccessToken(Y,X.refreshToken),J={accessToken:Q.access_token,tokenType:Q.token_type,refreshToken:Q.refresh_token||X.refreshToken,scope:Q.scope||X.scope};if(Q.expires_in)J.expiresAt=Date.now()+Q.expires_in*1000;return await this.tokenStorage.saveToken($,J,Y.clientId,Z.tokenUrl),J.accessToken}catch(Q){console.error("[OAuth] Failed to refresh token:",Q),await this.tokenStorage.deleteCredentials($)}return null}}import{EventEmitter as _7}from"events";class x6 extends _7{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor($,Y={}){super();this.client=$,this.config={interval:Y.interval??30000,timeout:Y.timeout??1e4,enabled:Y.enabled??!1,failureThreshold:Y.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let $=this.client.connectionStatus;if($==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let Y={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",Y),Y}else throw Error(`连接状态异常: ${$}`)}catch($){this.consecutiveFailures++;let Y=$;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,Y.message);let Z;if(this.consecutiveFailures>=this.config.failureThreshold)Z="unhealthy",this.emit("unhealthy",this.consecutiveFailures,Y),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Q)=>{console.error("[HealthMonitor] 重连失败:",Q)});else Z="degraded";this.setStatus(Z);let X={status:Z,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:Y};return this.emit("healthCheck",X),X}finally{this.isChecking=!1}}async pingServer(){let $=new Promise((Z,X)=>{setTimeout(()=>X(Error("Health check timeout")),this.config.timeout)}),Y=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([Y,$])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise(($)=>setTimeout($,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch($){throw console.error("[HealthMonitor] 重连失败:",$),$}}setStatus($){if(this.currentStatus!==$){let Y=this.currentStatus;this.currentStatus=$,this.emit("statusChanged",$,Y)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function q9($){if(!($ instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String($))};let Y=$.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Q)=>Y.includes(Q)))return{type:"config_error",isRetryable:!1,originalError:$};if(Y.includes("unauthorized")||Y.includes("401")||Y.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:$};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Q)=>Y.includes(Q)))return{type:"network_temporary",isRetryable:!0,originalError:$};return{type:"unknown",isRetryable:!0,originalError:$}}class p6 extends B7{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor($,Y,Z){super();this.config=$;if(this.serverName=Y||"default",$.oauth?.enabled)this.oauthProvider=new I2;if(Z?.enabled)this.healthMonitor=new x6(this,Z),this.healthMonitor.on("unhealthy",(X,Q)=>{this.emit("unhealthy",X,Q)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry($=3,Y=1000){if(this.status!=="disconnected")throw Error("客户端已连接或正在连接中");let Z=null;for(let X=1;X<=$;X++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Q){Z=Q;let J=q9(Q);if(!J.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",J.type),Q;if(X<$){let q=Y*Math.pow(2,X-1);console.warn(`[McpClient] 连接失败(${X}/${$}),${q}ms 后重试...`),await new Promise((G)=>setTimeout(G,q))}}throw Z||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new F7({name:f8(),version:N2()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let $=await this.createTransport();await this.sdkClient.connect($);let Y=this.sdkClient.getServerVersion();if(this.serverInfo={name:Y?.name||"Unknown",version:Y?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch($){throw this.setStatus("error"),this.emit("error",$),$}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let $=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${$}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(Y){if(console.error("[McpClient] 重连失败:",Y),q9(Y).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},$)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch($){console.warn("[McpClient] 断开连接时出错:",$)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool($,Y={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has($))throw Error(`工具 "${$}" 不存在`);try{return await this.sdkClient.callTool({name:$,arguments:Y})}catch(Z){throw console.error(`[McpClient] 调用工具 "${$}" 失败:`,Z),Z}}async createTransport(){let{type:$,command:Y,args:Z,env:X,url:Q,headers:J,oauth:q}=this.config,G={...J};if(q?.enabled&&this.oauthProvider&&($==="sse"||$==="http"))try{let K=await this.oauthProvider.getValidToken(this.serverName,q);if(!K){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let W=await this.oauthProvider.authenticate(this.serverName,q);G.Authorization=`Bearer ${W.accessToken}`}else G.Authorization=`Bearer ${K}`}catch(K){throw console.error("[McpClient] OAuth 认证失败:",K),Error(`OAuth 认证失败: ${K instanceof Error?K.message:String(K)}`)}if($==="stdio"){if(!Y)throw Error("stdio 传输需要 command 参数");let K={};for(let[W,O]of Object.entries(process.env))if(O!==void 0)K[W]=O;return new N7({command:Y,args:Z||[],env:{...K,...X},stderr:"ignore"})}else if($==="sse"){if(!Q)throw Error("sse 传输需要 url 参数");return new z7(new URL(Q),{requestInit:{headers:G}})}else if($==="http"){if(!Q)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:K}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new K(new URL(Q),{requestInit:{headers:G}})}throw Error(`不支持的传输类型: ${$}`)}async loadTools(){if(!this.sdkClient)return;try{let $=await this.sdkClient.listTools();if(this.tools.clear(),$.tools)for(let Y of $.tools)this.tools.set(Y.name,Y);this.emit("toolsUpdated",this.availableTools)}catch($){throw console.error("[McpClient] 加载工具失败:",$),$}}setStatus($){let Y=this.status;this.status=$,this.emit("statusChanged",$,Y)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer($){return this.connect()}async disconnectFromServer($){return this.disconnect()}async listResources($){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools($){return this.availableTools}async readResource($,Y){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:$})).contents?.[0]||{uri:$,text:""}}}class I0 extends L7{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!I0.instance)I0.instance=new I0;return I0.instance}async registerServer($,Y){if(this.servers.has($))throw Error(`MCP服务器 "${$}" 已经注册`);let Z=new p6(Y,$,Y.healthCheck),X={config:Y,client:Z,status:"disconnected",tools:[]};this.setupClientEventHandlers(Z,X,$),this.servers.set($,X),this.emit("serverRegistered",$,X);try{await this.connectServer($)}catch(Q){console.warn(`MCP服务器 "${$}" 连接失败:`,Q)}}async unregisterServer($){let Y=this.servers.get($);if(!Y)return;try{await Y.client.disconnect()}catch(Z){console.warn(`断开MCP服务器 "${$}" 时出错:`,Z)}this.servers.delete($),this.emit("serverUnregistered",$)}async connectServer($){let Y=this.servers.get($);if(!Y)throw Error(`MCP服务器 "${$}" 未注册`);if(Y.status==="connected")return;try{Y.status="connecting",await Y.client.connect(),Y.connectedAt=new Date,Y.lastError=void 0,Y.tools=Y.client.availableTools}catch(Z){throw Y.lastError=Z,Y.status="error",Z}}async disconnectServer($){let Y=this.servers.get($);if(!Y)return;await Y.client.disconnect(),Y.connectedAt=void 0}async getAvailableTools(){let $=[],Y=new Map;for(let[Z,X]of this.servers)if(X.status==="connected")for(let Q of X.tools){let J=Y.get(Q.name)||0;Y.set(Q.name,J+1)}for(let[Z,X]of this.servers)if(X.status==="connected")for(let Q of X.tools){let q=(Y.get(Q.name)||0)>1?`${Z}__${Q.name}`:Q.name,G=V2(X.client,Z,Q,q);$.push(G)}return $}async findTool($){for(let[Y,Z]of this.servers)if(Z.status==="connected"){let X=Z.tools.find((Q)=>Q.name===$);if(X)return V2(Z.client,Y,X)}return null}getToolsByServer($){let Y=this.servers.get($);if(!Y||Y.status!=="connected")return[];return Y.tools.map((Z)=>V2(Y.client,$,Z))}getServerStatus($){return this.servers.get($)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let $=[];for(let[Y,Z]of this.servers)if(Z.status==="connected")$.push(this.refreshServerTools(Y));await Promise.allSettled($)}async refreshServerTools($){let Y=this.servers.get($);if(!Y||Y.status!=="connected")return;try{let Z=Y.client.availableTools,X=Y.tools.length;Y.tools=Z,this.emit("toolsUpdated",$,Z,X)}catch(Z){console.warn(`刷新服务器 "${$}" 工具列表失败:`,Z)}}setupClientEventHandlers($,Y,Z){$.on("connected",(X)=>{Y.status="connected",Y.connectedAt=new Date,Y.tools=$.availableTools,this.emit("serverConnected",Z,X)}),$.on("disconnected",()=>{Y.status="disconnected",Y.connectedAt=void 0,Y.tools=[],this.emit("serverDisconnected",Z)}),$.on("error",(X)=>{Y.status="error",Y.lastError=X,this.emit("serverError",Z,X)}),$.on("toolsUpdated",(X)=>{let Q=Y.tools.length;Y.tools=X,this.emit("toolsUpdated",Z,X,Q)}),$.on("statusChanged",(X,Q)=>{Y.status=X,this.emit("serverStatusChanged",Z,X,Q)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers($){let Y=Object.entries($).map(([Z,X])=>this.registerServer(Z,X).catch((Q)=>{return console.warn(`注册MCP服务器 "${Z}" 失败:`,Q),Q}));await Promise.allSettled(Y)}getStatistics(){let $=0,Y=0,Z=0;for(let X of this.servers.values())if(X.status==="connected")$++,Y+=X.tools.length;else if(X.status==="error")Z++;return{totalServers:this.servers.size,connectedServers:$,errorServers:Z,totalTools:Y,isDiscovering:this.isDiscovering}}async disconnectAll(){let $=[];for(let[Y,Z]of this.servers)if(Z.status==="connected")$.push(Z.client.disconnect().catch((X)=>{console.warn(`断开 MCP 服务器 "${Y}" 时出错:`,X)}));await Promise.allSettled($),this.servers.clear()}}function w7(){console.log(`
|
|
78
78
|
blade mcp
|
|
79
79
|
`),console.log(`管理 MCP 服务器
|
|
80
80
|
`),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp add-json <name> <json> 从 JSON 字符串添加服务器"),console.log(` blade mcp reset-project-choices 重置项目级 .mcp.json 确认记录
|
|
81
81
|
`),console.log("Options:"),console.log(` -h, --help 显示帮助信息 [boolean]
|
|
82
82
|
`),console.log("Examples:"),console.log(" blade mcp list"),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add api --transport http http://localhost:3000"),console.log(` blade mcp remove github
|
|
83
83
|
`),console.log(`使用 blade mcp <command> --help 查看各子命令的详细帮助
|
|
84
|
-
`)}function
|
|
84
|
+
`)}function A7($){return $.reduce((Y,Z)=>{let[X,...Q]=Z.split("=");return Y[X]=Q.join("="),Y},{})}function R7($){return $.reduce((Y,Z)=>{let[X,...Q]=Z.split(":");return Y[X.trim()]=Q.join(":").trim(),Y},{})}var b7={command:"add <name> [commandOrUrl] [args...]",describe:"添加 MCP 服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("commandOrUrl",{type:"string",describe:"stdio: 命令 | http/sse: URL"}).positional("args",{type:"string",array:!0,describe:"stdio 命令参数",default:[]}).option("transport",{alias:"t",choices:["stdio","sse","http"],default:"stdio",describe:"传输类型"}).option("env",{alias:"e",type:"array",describe:"环境变量 (KEY=value)"}).option("header",{alias:"H",type:"array",describe:"HTTP 头 (Key: Value)"}).option("timeout",{type:"number",describe:"超时时间(毫秒)"}).example([["$0 mcp add github -- npx -y @modelcontextprotocol/server-github","Add stdio server (recommended)"],["$0 mcp add github npx @modelcontextprotocol/server-github -e GITHUB_TOKEN=xxx","Add stdio server with env"],['$0 mcp add api --transport http http://localhost:3000 -H "Auth: Bearer token"',"Add HTTP server"]])},handler:async($)=>{try{let{name:Y,commandOrUrl:Z,args:X,transport:Q,env:J,header:q,timeout:G}=$;if($["--"]&&$["--"].length>0)Z=$["--"][0],X=$["--"].slice(1);if(!Y||!Z)console.error("❌ 缺少必需参数: name 和 commandOrUrl"),console.log(`
|
|
85
85
|
\uD83D\uDCA1 用法:`),console.log(" blade mcp add <name> <command> [args...]"),console.log(" blade mcp add <name> -- <command> [args...]"),console.log(`
|
|
86
|
-
示例:`),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add github -- npx -y @modelcontextprotocol/server-github"),process.exit(1);let K={type:Q};if(Q==="stdio"){if(K.command=Z,K.args=X||[],J&&Array.isArray(J))K.env=
|
|
86
|
+
示例:`),console.log(" blade mcp add github npx -y @modelcontextprotocol/server-github"),console.log(" blade mcp add github -- npx -y @modelcontextprotocol/server-github"),process.exit(1);let K={type:Q};if(Q==="stdio"){if(K.command=Z,K.args=X||[],J&&Array.isArray(J))K.env=A7(J)}else if(K.url=Z,q&&Array.isArray(q))K.headers=R7(q);if(G)K.timeout=G;await e().addMcpServer(Y,K),console.log(`✅ MCP 服务器 "${Y}" 已添加到当前项目`),console.log(` 项目路径: ${process.cwd()}`)}catch(Y){console.error(`❌ 添加失败: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}},V7={command:"remove <name>",describe:"删除 MCP 服务器",aliases:["rm"],builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).example([["$0 mcp remove github","Remove the specified MCP server"]])},handler:async($)=>{try{if(!H1()[$.name])console.error(`❌ 服务器 "${$.name}" 不存在`),process.exit(1);await e().removeMcpServer($.name),console.log(`✅ MCP 服务器 "${$.name}" 已删除`)}catch(Y){console.error(`❌ 删除失败: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}},D7={command:"list",describe:"列出所有 MCP 服务器并检查健康状态",aliases:["ls"],handler:async()=>{try{let $=H1();if(console.log(`
|
|
87
87
|
当前项目: ${process.cwd()}
|
|
88
88
|
`),Object.keys($).length===0){console.log("暂无配置的 MCP 服务器");return}console.log(`检查 MCP 服务器健康状态...
|
|
89
|
-
`);let Y=
|
|
89
|
+
`);let Y=I0.getInstance(),Z=Object.entries($).map(async([Q,J])=>{try{let q=Y.getServerStatus(Q);if(!q)await Y.registerServer(Q,J),q=Y.getServerStatus(Q);else if(q.status==="disconnected")await Y.connectServer(Q);return{name:Q,config:J,serverInfo:q}}catch(q){return{name:Q,config:J,serverInfo:null,error:q}}}),X=await Promise.all(Z);for(let{name:Q,config:J,serverInfo:q,error:G}of X){let K=q?.status||"disconnected",W=K==="connected"?"✓":"✗",O=K==="connected"?"Connected":"Failed";if(console.log(`${Q}: ${J.type==="stdio"?J.command:J.url} - ${W} ${O}`),G&&K!=="connected")console.log(` 错误: ${G instanceof Error?G.message:String(G)}`)}console.log("");for(let{name:Q}of X)try{await Y.unregisterServer(Q)}catch(J){}process.exit(0)}catch($){console.error(`❌ 列表获取失败: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}},I7={command:"get <name>",describe:"获取服务器详情",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).example([["$0 mcp get github","Get details of the specified server"]])},handler:async($)=>{try{let Z=H1()[$.name];if(!Z)console.error(`❌ 服务器 "${$.name}" 不存在`),process.exit(1);console.log(`
|
|
90
90
|
服务器: ${$.name}
|
|
91
|
-
`),console.log(JSON.stringify(Z,null,2))}catch(Y){console.error(`❌ 获取失败: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}},
|
|
91
|
+
`),console.log(JSON.stringify(Z,null,2))}catch(Y){console.error(`❌ 获取失败: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}},k7={command:"add-json <name> <json>",describe:"从 JSON 字符串添加服务器",builder:($)=>{return $.positional("name",{type:"string",describe:"服务器名称",demandOption:!0}).positional("json",{type:"string",describe:"JSON 配置字符串",demandOption:!0}).example([[`$0 mcp add-json my-server '{"type":"stdio","command":"npx","args":["-y","@example/server"]}'`,"Add server from JSON string"]])},handler:async($)=>{try{let Y=JSON.parse($.json);if(!Y.type)throw Error('配置必须包含 "type" 字段');await e().addMcpServer($.name,Y),console.log(`✅ MCP 服务器 "${$.name}" 已添加`),console.log(` 项目路径: ${process.cwd()}`)}catch(Y){console.error(`❌ 添加失败: ${Y instanceof Error?Y.message:"未知错误"}`),process.exit(1)}}},v7={command:"reset-project-choices",describe:"重置项目级 .mcp.json 确认记录",handler:async()=>{try{await e().resetProjectChoices(),console.log("✅ 已重置当前项目的 .mcp.json 确认记录"),console.log(` 项目路径: ${process.cwd()}`)}catch($){console.error(`❌ 重置失败: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}},G9={command:"mcp",describe:"管理 MCP 服务器",builder:($)=>{return $.command(b7).command(V7).command(D7).command(I7).command(k7).command(v7).demandCommand(0).help(!1).option("help",{alias:"h",type:"boolean",describe:"显示帮助信息"})},handler:($)=>{let Y=["add","remove","list","ls","get","add-json","reset-project-choices"];if(!$._.some((X)=>Y.includes(X))||$.help)w7(),process.exit(0)}};import*as J5 from"os";import*as q5 from"path";import{nanoid as U$}from"nanoid";import K9 from"openai";var m=Y0("Chat");class v2{config;client;constructor($){this.config=$;if(m.debug("\uD83D\uDE80 [ChatService] Initializing ChatService"),m.debug("⚙️ [ChatService] Config:",{model:$.model,baseUrl:$.baseUrl,temperature:$.temperature,maxContextTokens:$.maxContextTokens,timeout:$.timeout,hasApiKey:!!$.apiKey}),!$.baseUrl)throw m.error("❌ [ChatService] baseUrl is required in ChatConfig"),Error("baseUrl is required in ChatConfig");if(!$.apiKey)throw m.error("❌ [ChatService] apiKey is required in ChatConfig"),Error("apiKey is required in ChatConfig");if(!$.model)throw m.error("❌ [ChatService] model is required in ChatConfig"),Error("model is required in ChatConfig");this.client=new K9({apiKey:$.apiKey,baseURL:$.baseUrl,timeout:$.timeout??180000,maxRetries:3}),m.debug("✅ [ChatService] ChatService initialized successfully")}async chat($,Y,Z){let X=Date.now();m.debug("\uD83D\uDE80 [ChatService] Starting chat request"),m.debug("\uD83D\uDCDD [ChatService] Messages count:",$.length),m.debug("\uD83D\uDCDD [ChatService] Messages preview:",$.map((G)=>({role:G.role,contentLength:G.content.length})));let Q=$.map((G)=>{if(G.role==="tool")return{role:"tool",content:G.content,tool_call_id:G.tool_call_id};if(G.role==="assistant"&&G.tool_calls)return{role:"assistant",content:G.content||null,tool_calls:G.tool_calls};return{role:G.role,content:G.content}}),J=Y?.map((G)=>({type:"function",function:{name:G.name,description:G.description,parameters:G.parameters}}));if(m.debug("\uD83D\uDD27 [ChatService] Tools count:",J?.length||0),J&&J.length>0)m.debug("\uD83D\uDD27 [ChatService] Available tools:",J.map((G)=>G.type==="function"?G.function.name:"unknown"));let q={model:this.config.model,messages:Q,tools:J,tool_choice:J&&J.length>0?"auto":void 0,max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0};m.debug("\uD83D\uDCE4 [ChatService] Request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,tool_choice:q.tool_choice,max_tokens:q.max_tokens,temperature:q.temperature});try{let G=await this.client.chat.completions.create(q,{signal:Z}),K=Date.now()-X;if(m.debug("\uD83D\uDCE5 [ChatService] Response received in",K,"ms"),!G)throw m.error("❌ [ChatService] API returned null/undefined response"),Error("API returned null/undefined response");if(!G.choices||!Array.isArray(G.choices))throw m.error("❌ [ChatService] Invalid API response format - missing choices array"),m.error("❌ [ChatService] Response object:",JSON.stringify(G,null,2)),Error(`Invalid API response: missing choices array. Response: ${JSON.stringify(G)}`);if(G.choices.length===0)throw m.error("❌ [ChatService] API returned empty choices array"),Error("API returned empty choices array");m.debug("\uD83D\uDCCA [ChatService] Response usage:",G.usage),m.debug("\uD83D\uDCCA [ChatService] Response choices count:",G.choices.length);let W=G.choices[0];if(!W)throw m.error("❌ [ChatService] No completion choice returned"),Error("No completion choice returned");if(m.debug("\uD83D\uDCDD [ChatService] Response choice:",{finishReason:W.finish_reason,contentLength:W.message.content?.length||0,hasToolCalls:!!W.message.tool_calls,toolCallsCount:W.message.tool_calls?.length||0}),W.message.tool_calls)m.debug("\uD83D\uDD27 [ChatService] Tool calls:",W.message.tool_calls.map((H)=>({id:H.id,type:H.type,functionName:H.type==="function"?H.function?.name:"unknown",functionArgsLength:H.type==="function"?H.function?.arguments?.length||0:0})));let O=W.message.tool_calls?.filter((H)=>H.type==="function"),U={content:W.message.content||"",toolCalls:O,usage:{promptTokens:G.usage?.prompt_tokens||0,completionTokens:G.usage?.completion_tokens||0,totalTokens:G.usage?.total_tokens||0}};return m.debug("✅ [ChatService] Chat completed successfully"),m.debug("\uD83D\uDCCA [ChatService] Final response:",{contentLength:U.content.length,toolCallsCount:U.toolCalls?.length||0,usage:U.usage}),U}catch(G){let K=Date.now()-X;throw m.error("❌ [ChatService] Chat request failed after",K,"ms"),m.error("❌ [ChatService] Error details:",G),G}}async*streamChat($,Y,Z){let X=Date.now();m.debug("\uD83D\uDE80 [ChatService] Starting chat stream request"),m.debug("\uD83D\uDCDD [ChatService] Messages count:",$.length),m.debug("\uD83D\uDCDD [ChatService] Messages preview:",$.map((G)=>({role:G.role,contentLength:G.content.length})));let Q=$.map((G)=>{if(G.role==="tool")return{role:"tool",content:G.content,tool_call_id:G.tool_call_id};if(G.role==="assistant"&&G.tool_calls)return{role:"assistant",content:G.content||null,tool_calls:G.tool_calls};return{role:G.role,content:G.content}}),J=Y?.map((G)=>({type:"function",function:{name:G.name,description:G.description,parameters:G.parameters}}));if(m.debug("\uD83D\uDD27 [ChatService] Stream tools count:",J?.length||0),J&&J.length>0)m.debug("\uD83D\uDD27 [ChatService] Stream available tools:",J.map((G)=>G.type==="function"?G.function.name:"unknown"));let q={model:this.config.model,messages:Q,tools:J,tool_choice:J&&J.length>0?"auto":"none",max_tokens:this.config.maxOutputTokens??32768,temperature:this.config.temperature??0,stream:!0};m.debug("\uD83D\uDCE4 [ChatService] Stream request params:",{model:q.model,messagesCount:q.messages.length,toolsCount:q.tools?.length||0,tool_choice:q.tool_choice,max_tokens:q.max_tokens,temperature:q.temperature,stream:q.stream});try{let G=await this.client.chat.completions.create(q,{signal:Z}),K=Date.now()-X;m.debug("\uD83D\uDCE5 [ChatService] Stream started in",K,"ms");let W=0,O="",U=!1;for await(let H of G){if(W++,!H||!H.choices||!Array.isArray(H.choices)){m.warn("⚠️ [ChatService] Invalid chunk format in stream",W);continue}let _=H.choices[0]?.delta;if(!_){m.warn("⚠️ [ChatService] Empty delta in chunk",W);continue}if(_.content)O+=_.content;if(_.tool_calls&&!U)U=!0,m.debug("\uD83D\uDD27 [ChatService] Tool calls detected in stream");let z=H.choices[0]?.finish_reason;if(z)m.debug("\uD83C\uDFC1 [ChatService] Stream finished with reason:",z),m.debug("\uD83D\uDCCA [ChatService] Stream summary:",{totalChunks:W,totalContentLength:O.length,hadToolCalls:U,duration:Date.now()-X+"ms"});yield{content:_.content||void 0,toolCalls:_.tool_calls,finishReason:z||void 0}}m.debug("✅ [ChatService] Stream completed successfully")}catch(G){let K=Date.now()-X;throw m.error("❌ [ChatService] Stream request failed after",K,"ms"),m.error("❌ [ChatService] Stream error details:",G),G}}getConfig(){return{...this.config}}updateConfig($){m.debug("\uD83D\uDD04 [ChatService] Updating configuration"),m.debug("\uD83D\uDD04 [ChatService] New config:",{model:$.model,baseUrl:$.baseUrl,temperature:$.temperature,maxContextTokens:$.maxContextTokens,timeout:$.timeout,hasApiKey:!!$.apiKey});let Y={...this.config};this.config={...this.config,...$},this.client=new K9({apiKey:this.config.apiKey,baseURL:this.config.baseUrl,timeout:this.config.timeout??180000,maxRetries:2}),m.debug("✅ [ChatService] Configuration updated successfully"),m.debug("\uD83D\uDCCA [ChatService] Config changes:",{modelChanged:Y.model!==this.config.model,baseUrlChanged:Y.baseUrl!==this.config.baseUrl,temperatureChanged:Y.temperature!==this.config.temperature,maxContextTokensChanged:Y.maxContextTokens!==this.config.maxContextTokens,timeoutChanged:Y.timeout!==this.config.timeout,apiKeyChanged:Y.apiKey!==this.config.apiKey})}}var M7=Y0("Service");function M2($){switch($.provider){case"openai-compatible":return new v2($);case"anthropic":throw Error(`❌ Anthropic provider 暂未实现
|
|
92
92
|
|
|
93
93
|
`+`请使用 "openai-compatible" 提供商,或者:
|
|
94
94
|
`+`1. 等待官方实现
|
|
95
95
|
`+`2. 贡献代码实现此功能: https://github.com/echoVic/blade-code
|
|
96
|
-
`);default:return
|
|
97
|
-
`),J=Q.length,
|
|
98
|
-
`),
|
|
96
|
+
`);default:return M7.warn(`⚠️ 未知的 provider: ${$.provider}, 回退到 openai-compatible`),new v2($)}}import{readFile as y7}from"node:fs/promises";class y2{static MAX_FILES=5;static MAX_LINES_PER_FILE=1000;static analyzeFiles($){let Y=new Map;return $.forEach((X,Q)=>{if(this.extractFilePathsFromContent(X.content||"").forEach((q)=>{this.updateFileReference(Y,q,Q,!1)}),X.tool_calls&&Array.isArray(X.tool_calls))X.tool_calls.forEach((q)=>{let G=this.extractFilePathsFromToolCall(q),K=q.type==="function"&&"function"in q?q.function?.name:"",W=["Write","Edit"].includes(K||"");G.forEach((O)=>{this.updateFileReference(Y,O,Q,W)})})}),Array.from(Y.values()).sort((X,Q)=>{if(X.wasModified!==Q.wasModified)return X.wasModified?-1:1;if(X.mentions!==Q.mentions)return Q.mentions-X.mentions;return Q.lastMentioned-X.lastMentioned}).slice(0,this.MAX_FILES)}static async readFilesContent($){let Y=[];for(let Z of $)try{let X=await y7(Z,"utf-8"),Q=X.split(`
|
|
97
|
+
`),J=Q.length,q=X,G=!1,K=J;if(J>this.MAX_LINES_PER_FILE)q=Q.slice(0,this.MAX_LINES_PER_FILE).join(`
|
|
98
|
+
`),q+=`
|
|
99
99
|
|
|
100
|
-
... (truncated ${J-this.MAX_LINES_PER_FILE} lines)`,
|
|
100
|
+
... (truncated ${J-this.MAX_LINES_PER_FILE} lines)`,G=!0,K=this.MAX_LINES_PER_FILE;Y.push({path:Z,content:q,truncated:G,lines:J,includedLines:K})}catch(X){console.warn(`[FileAnalyzer] 无法读取文件: ${Z}`,X)}return Y}static extractFilePathsFromContent($){let Y=new Set,Z=/```(?:\w+)?\s*\n?([\s\S]*?)```/g,X=Array.from($.matchAll(Z));for(let J of X){let q=J[1];this.extractPathsFromText(q).forEach((K)=>Y.add(K))}return this.extractPathsFromText($).forEach((J)=>Y.add(J)),Array.from(Y)}static extractPathsFromText($){let Y=[],Z=[/(?:src|tests?|docs?|lib|config|scripts?|bin|utils?|components?|services?|hooks?)\/[\w\-/.]+\.[\w]+/g,/(?:package|tsconfig|vite\.config|webpack\.config|next\.config|babel\.config)\.[\w]+/g,/(?:\.\.?\/|\/)[a-zA-Z0-9\-_/.]+\.[\w]+/g];for(let X of Z){let Q=Array.from($.matchAll(X));for(let J of Q){let q=J[0];if(q=q.replace(/[,。;:!?""''()【】《》]$/g,""),q=q.replace(/[,.;:!?"'()[\]<>]$/g,""),this.isValidFilePath(q))Y.push(q)}}return Y}static extractFilePathsFromToolCall($){let Y=[];try{let Z=$.function?.name,X=typeof $.function?.arguments==="string"?JSON.parse($.function.arguments):$.function?.arguments||{};if(["Read","Write","Edit","Glob","Grep","NotebookEdit","mcp__github__get_file_contents","mcp__github__create_or_update_file"].includes(Z)){let J=["file_path","path","notebook_path","filePath"];for(let q of J)if(X[q]&&typeof X[q]==="string")Y.push(X[q])}}catch(Z){}return Y}static updateFileReference($,Y,Z,X){let Q=$.get(Y);if(Q)Q.mentions++,Q.lastMentioned=Z,Q.wasModified=Q.wasModified||X;else $.set(Y,{path:Y,mentions:1,lastMentioned:Z,wasModified:X})}static isValidFilePath($){if(!$.includes("/"))return!1;let Y=$.split("/"),Z=Y[Y.length-1];if(!Z.includes("."))return!1;let X=["ts","tsx","js","jsx","json","md","py","java","go","rs","c","cpp","h","css","scss","html","xml","yaml","yml","toml","sh","bash","sql","graphql","vue","svelte"],Q=Z.split(".").pop()?.toLowerCase();if(!Q||!X.includes(Q))return!1;return!0}}import{encodingForModel as W9}from"js-tiktoken";class r1{static encodingCache=new Map;static countTokens($,Y){let Z=this.getEncoding(Y),X=0;for(let Q of $){if(X+=4,Q.role)X+=Z.encode(Q.role).length;if(Q.content)if(typeof Q.content==="string")X+=Z.encode(Q.content).length;else X+=Z.encode(JSON.stringify(Q.content)).length;if(Q.tool_calls&&Array.isArray(Q.tool_calls))X+=this.countToolCallTokens(Q.tool_calls,Z);if(Q.name)X+=Z.encode(Q.name).length}return X}static getTokenLimit($){return $}static shouldCompact($,Y,Z,X=0.8){let Q=this.countTokens($,Y),J=Math.floor(Z*X);return Q>=J}static getEncoding($){if(!this.encodingCache.has($))try{let Y=W9($);this.encodingCache.set($,Y)}catch{try{let Y=W9("gpt-4");this.encodingCache.set($,Y)}catch{console.warn(`[TokenCounter] 无法为模型 ${$} 获取 encoding,使用粗略估算`),this.encodingCache.set($,{encode:(Y)=>{return Array(Math.ceil(Y.length/4))}})}}return this.encodingCache.get($)}static countToolCallTokens($,Y){let Z=0;for(let X of $){if(Z+=4,X.function?.name)Z+=Y.encode(X.function.name).length;if(X.function?.arguments){let Q=typeof X.function.arguments==="string"?X.function.arguments:JSON.stringify(X.function.arguments);Z+=Y.encode(Q).length}if(X.id)Z+=Y.encode(X.id).length}return Z}static clearCache(){this.encodingCache.clear()}static estimateTokens($){let Y=($.match(/[\u4e00-\u9fa5]/g)||[]).length,Z=$.length-Y;return Math.ceil(Y/1.5+Z/4)}}class O${static THRESHOLD_PERCENT=0.8;static RETAIN_PERCENT=0.2;static FALLBACK_RETAIN_PERCENT=0.3;static async compact($,Y){let Z=Y.actualPreTokens??r1.countTokens($,Y.modelName),X=Y.actualPreTokens?"actual (from LLM usage)":"estimated";console.log(`[CompactionService] preTokens source: ${X}`);try{console.log("[CompactionService] 开始压缩,消息数:",$.length),console.log("[CompactionService] 压缩前 tokens:",Z);let J=y2.analyzeFiles($).map((N)=>N.path);console.log("[CompactionService] 提取重点文件:",J);let q=await y2.readFilesContent(J);console.log("[CompactionService] 成功读取文件:",q.length);let G=await this.generateSummary($,q,Y);console.log("[CompactionService] 生成总结,长度:",G.length);let K=Math.ceil($.length*this.RETAIN_PERCENT),W=$.slice(-K),O=new Set;for(let N of W)if(N.role==="assistant"&&N.tool_calls)for(let A of N.tool_calls)O.add(A.id);let U=W.filter((N)=>{if(N.role==="tool"&&N.tool_call_id)return O.has(N.tool_call_id);return!0});console.log("[CompactionService] 保留消息数:",K),console.log("[CompactionService] 过滤后保留消息数:",U.length);let H=U$(),_=this.createBoundaryMessage(H,Y.trigger,Z),z=U$(),F=this.createSummaryMessage(z,G),w=[F,...U],L=r1.countTokens(w,Y.modelName);return console.log("[CompactionService] 压缩完成!"),console.log("[CompactionService] Token 变化:",Z,"→",L,`(-${((1-L/Z)*100).toFixed(1)}%)`),{success:!0,summary:G,preTokens:Z,postTokens:L,filesIncluded:J,compactedMessages:w,boundaryMessage:_,summaryMessage:F}}catch(Q){return console.error("[CompactionService] 压缩失败,使用降级策略",Q),this.fallbackCompact($,Y,Z,Q)}}static async generateSummary($,Y,Z){let X=this.buildCompactionPrompt($,Y);console.log("[CompactionService] 使用压缩模型:",Z.modelName);let q=(await M2({apiKey:Z.apiKey||process.env.BLADE_API_KEY||"",baseUrl:Z.baseURL||process.env.BLADE_BASE_URL||"https://api.openai.com/v1",model:Z.modelName,temperature:0.3,maxOutputTokens:8000,timeout:60000,provider:"openai-compatible"}).chat([{role:"user",content:X}])).content||"",G=q.match(/<summary>([\s\S]*?)<\/summary>/);if(!G)return console.warn("[CompactionService] 总结格式不正确,使用完整响应"),q;return G[1].trim()}static buildCompactionPrompt($,Y){let Z=$.map((J,q)=>{let G=J.role||"unknown",K=typeof J.content==="string"?J.content:JSON.stringify(J.content),W=5000,O=K.length>5000?K.substring(0,5000)+"...":K;return`[${q+1}] ${G}: ${O}`}).join(`
|
|
101
101
|
|
|
102
102
|
`),X=Y.map((J)=>{return`### ${J.path}
|
|
103
103
|
\`\`\`
|
|
@@ -170,14 +170,14 @@ ${Y.length>0?`## Important Files
|
|
|
170
170
|
|
|
171
171
|
${X}`:""}
|
|
172
172
|
|
|
173
|
-
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Y,Z){return{id:
|
|
173
|
+
Please provide your summary following the structure specified above, with both <analysis> and <summary> sections.`}static createBoundaryMessage($,Y,Z){return{id:U$(),role:"system",content:"Conversation compacted",metadata:{type:"system",subtype:"compact_boundary",parentId:$,compactMetadata:{trigger:Y,preTokens:Z}}}}static createSummaryMessage($,Y){return{id:U$(),role:"user",content:Y,metadata:{parentId:$,isCompactSummary:!0}}}static fallbackCompact($,Y,Z,X){let Q=Math.ceil($.length*this.FALLBACK_RETAIN_PERCENT),J=$.slice(-Q),q=new Set;for(let F of J)if(F.role==="assistant"&&F.tool_calls)for(let w of F.tool_calls)q.add(w.id);let G=J.filter((F)=>{if(F.role==="tool"&&F.tool_call_id)return q.has(F.tool_call_id);return!0}),K=U$(),W=this.createBoundaryMessage(K,Y.trigger,Z),O=X instanceof Error?X.message:String(X),U=U$(),H=this.createSummaryMessage(U,`[Automatic compaction failed; using fallback]
|
|
174
174
|
|
|
175
175
|
An error occurred during compaction. Retained the latest ${Q} messages (~30%).
|
|
176
176
|
|
|
177
177
|
Error: ${O}
|
|
178
178
|
|
|
179
|
-
The conversation can continue, but consider retrying compaction later with /compact.`),_=[H,...
|
|
180
|
-
\uD83D\uDCE6 发现新的 MCP 服务器: ${$}`),console.log(` 类型: ${Y.type}`),Y.type==="stdio")console.log(` 命令: ${Y.command} ${Y.args?.join(" ")||""}`);else console.log(` URL: ${Y.url}`);let{approve:X}=await Z.prompt([{type:"confirm",name:"approve",message:"是否启用此服务器?",default:!1}]);return X}catch(Z){return console.error(`⚠️ 无法启动交互式确认,默认拒绝服务器: ${$}`),!1}}import{promises as
|
|
179
|
+
The conversation can continue, but consider retrying compaction later with /compact.`),_=[H,...G],z=r1.countTokens(_,Y.modelName);return{success:!1,summary:H.content,preTokens:Z,postTokens:z,filesIncluded:[],compactedMessages:_,boundaryMessage:W,summaryMessage:H,error:O}}}import{promises as g6}from"fs";import*as a$ from"path";async function U9($={}){let{interactive:Y=!0,silent:Z=!1,mcpConfig:X,strictMcpConfig:Q=!1}=$,J=0;if(X&&X.length>0){if(!Z)console.log(`\uD83D\uDCE6 加载来自 --mcp-config 的配置 (${X.length} 个源)`);for(let G of X){let K=await E7(G,{interactive:Y,silent:Z,sourceType:"cli-param"});J+=K}if(!Z&&J>0)console.log(`✅ 从 --mcp-config 加载了 ${J} 个服务器`)}if(Q){if(!Z)console.log("\uD83D\uDD12 严格模式已启用,跳过项目级 .mcp.json");return J}let q=a$.join(process.cwd(),".mcp.json");try{await g6.access(q)}catch{return J}try{let G=await g6.readFile(q,"utf-8"),K=JSON.parse(G);if(!K.mcpServers||typeof K.mcpServers!=="object"){if(!Z)console.warn("⚠️ .mcp.json 格式不正确:缺少 mcpServers 字段");return J}let W=F0();if(!W)return console.warn("⚠️ 配置未初始化"),J;let O=W.enabledMcpjsonServers||[],U=W.disabledMcpjsonServers||[],H=0,_=[...O];for(let[z,F]of Object.entries(K.mcpServers)){if(U.includes(z)){if(!Z)console.log(`⏭️ 跳过已拒绝的服务器: ${z}`);continue}if(O.includes(z)){if(await e().addMcpServer(z,F),H++,!Z)console.log(`✅ 加载服务器: ${z}`);continue}if(!Y){if(!Z)console.log(`⏭️ 跳过未确认的服务器: ${z} (非交互模式)`);continue}if(await O9(z,F)){if(await e().addMcpServer(z,F),_.push(z),H++,!Z)console.log(`✅ 已启用服务器: ${z}`)}else if(U.push(z),!Z)console.log(`❌ 已拒绝服务器: ${z}`)}if(Y)await e().updateConfig({enabledMcpjsonServers:_,disabledMcpjsonServers:U});return J+=H,J}catch(G){if(!Z)console.error("❌ 加载 .mcp.json 失败:",G);return J}}async function E7($,Y){let{interactive:Z,silent:X,sourceType:Q}=Y;try{let J;if($.trim().startsWith("{"))try{let G=JSON.parse($);J=G.mcpServers||G}catch(G){if(!X)console.error(`❌ 解析 JSON 字符串失败: ${$.slice(0,50)}...`);return 0}else{let G=a$.isAbsolute($)?$:a$.join(process.cwd(),$);try{let K=await g6.readFile(G,"utf-8"),W=JSON.parse(K);J=W.mcpServers||W}catch(K){if(!X)console.error(`❌ 加载配置文件失败: ${G}`),console.error(` 错误: ${K instanceof Error?K.message:String(K)}`);return 0}}if(!J||typeof J!=="object"){if(!X)console.warn("⚠️ 配置格式不正确:缺少 mcpServers 对象");return 0}let q=0;for(let[G,K]of Object.entries(J))try{if(Q==="cli-param"){if(await e().addMcpServer(G,K),q++,!X)console.log(` ✅ ${G}`)}else if(Z?await O9(G,K):!1){if(await e().addMcpServer(G,K),q++,!X)console.log(` ✅ ${G}`)}}catch(W){if(!X)console.error(` ❌ 加载服务器 ${G} 失败:`,W)}return q}catch(J){if(!X)console.error("❌ 加载配置源失败:",J);return 0}}async function O9($,Y){try{let{default:Z}=await import("inquirer");if(console.log(`
|
|
180
|
+
\uD83D\uDCE6 发现新的 MCP 服务器: ${$}`),console.log(` 类型: ${Y.type}`),Y.type==="stdio")console.log(` 命令: ${Y.command} ${Y.args?.join(" ")||""}`);else console.log(` URL: ${Y.url}`);let{approve:X}=await Z.prompt([{type:"confirm",name:"approve",message:"是否启用此服务器?",default:!1}]);return X}catch(Z){return console.error(`⚠️ 无法启动交互式确认,默认拒绝服务器: ${$}`),!1}}import{promises as _9}from"fs";import T7 from"path";import{execSync as j7}from"child_process";import*as _$ from"os";import*as H$ from"path";function P7(){let $=process.cwd(),Y=S7($);return{workingDirectory:$,projectRoot:Y,platform:`${_$.platform()} (${_$.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:_$.homedir()}}function E2(){let $=P7();return`# Environment Context
|
|
181
181
|
|
|
182
182
|
## Working Directory
|
|
183
183
|
**Current**: \`${$.workingDirectory}\`
|
|
@@ -195,7 +195,7 @@ When using file tools (read, write, edit), provide **absolute paths**:
|
|
|
195
195
|
- ❌ Incorrect: \`/package.json\` (root directory)
|
|
196
196
|
- ❌ Incorrect: \`package.json\` (relative path without context)
|
|
197
197
|
|
|
198
|
-
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function
|
|
198
|
+
**Always use** \`${$.workingDirectory}/\` as the base for file paths.`}function S7($){let Y=$;while(Y!==H$.dirname(Y)){if(H9(H$.join(Y,".git")))return Y;if(H9(H$.join(Y,"package.json")))return Y;Y=H$.dirname(Y)}return $}function H9($){try{return j7(`test -e "${$}"`,{stdio:"ignore"}),!0}catch{return!1}}var m6=`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.
|
|
199
199
|
|
|
200
200
|
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.
|
|
201
201
|
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.
|
|
@@ -343,7 +343,7 @@ assistant: Clients are marked as failed in the \`connectToServer\` function in s
|
|
|
343
343
|
</example>
|
|
344
344
|
|
|
345
345
|
# Language Requirement
|
|
346
|
-
IMPORTANT: Always respond in Chinese (Simplified Chinese). Translate all your responses to Chinese before sending them to the user.`;var
|
|
346
|
+
IMPORTANT: Always respond in Chinese (Simplified Chinese). Translate all your responses to Chinese before sending them to the user.`;var u6=`You are in **PLAN MODE** - a read-only research phase for designing implementation plans.
|
|
347
347
|
|
|
348
348
|
## Core Objective
|
|
349
349
|
|
|
@@ -383,70 +383,70 @@ Your plan should include:
|
|
|
383
383
|
3. **Steps** - Detailed implementation steps with file paths
|
|
384
384
|
4. **Testing** - How to verify changes
|
|
385
385
|
5. **Risks** - Potential issues and mitigations
|
|
386
|
-
`;function
|
|
386
|
+
`;function d6($){return`<system-reminder>Plan mode is active. You MUST NOT make any file changes or run non-readonly tools. Research only, then call ExitPlanMode with your plan.</system-reminder>
|
|
387
387
|
|
|
388
|
-
`+$}async function
|
|
388
|
+
`+$}async function j2($={}){let{projectPath:Y,replaceDefault:Z,append:X,mode:Q,includeEnvironment:J=!0}=$,q=[],G=[];if(J){let U=E2();if(U)q.push(U),G.push({name:"environment",loaded:!0,length:U.length})}let K=Q==="plan",W=K?u6:Z??m6;if(q.push(W),G.push({name:K?"plan_mode_prompt":Z?"replace_default":"default",loaded:!0,length:W.length}),Y){let U=await C7(Y);if(U)q.push(U),G.push({name:"blade_md",loaded:!0,length:U.length});else G.push({name:"blade_md",loaded:!1})}if(X?.trim())q.push(X.trim()),G.push({name:"append",loaded:!0,length:X.trim().length});return{prompt:q.join(`
|
|
389
389
|
|
|
390
390
|
---
|
|
391
391
|
|
|
392
|
-
`),sources:
|
|
393
|
-
`),Q=Y,J=!1,
|
|
394
|
-
`);let O=Array.from({length:W-
|
|
392
|
+
`),sources:G}}async function C7($){let Y=T7.join($,"BLADE.md");try{return(await _9.readFile(Y,"utf-8")).trim()||null}catch{return null}}import z9 from"fast-glob";import*as F$ from"fs/promises";import*as N9 from"path";import*as P2 from"fs/promises";import*as y0 from"path";var F9=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class a1 extends Error{code;constructor($,Y){super($);this.code=Y;this.name="PathSecurityError"}}class S2{static normalize($,Y){let Z=y0.isAbsolute($)?$:y0.resolve(Y,$),X=y0.normalize(Z),Q=y0.normalize(Y);if(!X.startsWith(Q))throw new a1(`Path outside workspace: ${$} (resolved to ${X}, workspace: ${Q})`,"PATH_OUTSIDE_WORKSPACE");return X}static checkRestricted($){let Y=$.split(y0.sep);for(let Z of F9)if(Y.includes(Z))throw new a1(`Access denied: "${Z}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new a1(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,Y){this.checkTraversal($);let Z=this.normalize($,Y);this.checkRestricted(Z);try{await P2.access(Z)}catch(X){throw new a1(`Path not found: ${$}`,"PATH_NOT_FOUND")}return Z}static async resolveSymlink($,Y){try{let Z=await P2.realpath($),X=y0.normalize(Y);if(!Z.startsWith(X))throw new a1(`Symlink points outside workspace: ${$} -> ${Z}`,"SYMLINK_OUTSIDE_WORKSPACE");return Z}catch(Z){if(Z instanceof a1)throw Z;return $}}static getRelativePath($,Y){return y0.relative(Y,$)}static isWithinWorkspace($,Y){let Z=y0.normalize($),X=y0.normalize(Y);return Z.startsWith(X)}static isRestricted($){let Y=$.split(y0.sep);return F9.some((Z)=>Y.includes(Z))}}class T2{static PATTERN=/@"([^"]+)"|@([^\s]+)/g;static LINE_RANGE_PATTERN=/#L(\d+)(?:-(\d+))?$/;static GLOB_PATTERN=/[*?[\]]/;static extract($){let Y=[],Z;this.PATTERN.lastIndex=0;while((Z=this.PATTERN.exec($))!==null){let X=Z[0],Q=Z[1]||Z[2],J=this.parseLineRange(Q);if(J)Q=Q.replace(this.LINE_RANGE_PATTERN,"");let q=this.GLOB_PATTERN.test(Q);Y.push({raw:X,path:Q.trim(),lineRange:J,startIndex:Z.index,endIndex:Z.index+X.length,isGlob:q})}return Y}static parseLineRange($){let Y=$.match(this.LINE_RANGE_PATTERN);if(!Y)return;let Z=parseInt(Y[1],10),X=Y[2]?parseInt(Y[2],10):void 0;return{start:Z,end:X}}static hasAtMentions($){return $.includes("@")}static isValidPath($){if(!$||$.trim().length===0)return!1;let Y=["<",">","|","\x00"];for(let Z of Y)if($.includes(Z))return!1;return!0}static removeAtMentions($){return this.PATTERN.lastIndex=0,$.replace(this.PATTERN,"")}}var X1=Y0("Prompts");class c6{fileCache=new Map;options;constructor($){this.options={maxFileSize:1048576,maxLines:2000,maxTokens:32000,...$},X1.debug("AttachmentCollector initialized",{maxFileSize:this.options.maxFileSize,maxLines:this.options.maxLines})}async collect($){if(!T2.hasAtMentions($))return[];let Y=T2.extract($);if(Y.length===0)return[];X1.debug(`Found ${Y.length} @ mentions`);let Z=Y.map((Q)=>this.processOne(Q));return(await Promise.allSettled(Z)).map((Q,J)=>{if(Q.status==="fulfilled")return Q.value;else{let q=Y[J],G=Q.reason instanceof Error?Q.reason.message:String(Q.reason);return X1.warn(`Failed to process @${q.path}:`,G),{type:"error",path:q.path,content:"",error:G}}})}async processOne($){if($.isGlob)return X1.debug(`Processing glob pattern: ${$.path}`),await this.processGlob($.path);let Y=await S2.validatePath($.path,this.options.cwd),Z=await S2.resolveSymlink(Y,this.options.cwd);if((await F$.stat(Z)).isDirectory())return X1.debug(`Processing directory: ${$.path}`),await this.renderDirectoryTree(Z,$.path);return X1.debug(`Processing file: ${$.path}`,{lineRange:$.lineRange}),await this.readFile(Z,$.path,$.lineRange)}async readFile($,Y,Z){let X=this.fileCache.get($);if(X&&Date.now()-X.timestamp<60000)return X1.debug(`Cache hit: ${Y}`),this.formatFileAttachment(Y,X.content,Z);let Q=await F$.stat($);if(Q.size>this.options.maxFileSize)throw Error(`File too large: ${Math.round(Q.size/1024/1024)}MB (max ${Math.round(this.options.maxFileSize/1024/1024)}MB)`);let J;try{J=await F$.readFile($,"utf-8")}catch(q){throw Error(`Cannot read file as text: ${Y}. It may be a binary file.`)}return this.fileCache.set($,{content:J,timestamp:Date.now()}),this.formatFileAttachment(Y,J,Z)}formatFileAttachment($,Y,Z){let X=Y.split(`
|
|
393
|
+
`),Q=Y,J=!1,q=Z;if(Z){let G=Math.max(0,Z.start-1),K=Z.end?Z.end:Z.start;if(G>=X.length)throw Error(`Line range start (${Z.start}) exceeds file length (${X.length} lines)`);let W=Math.min(K,X.length);Q=X.slice(G,W).join(`
|
|
394
|
+
`);let O=Array.from({length:W-G},(H,_)=>G+_+1);Q=Q.split(`
|
|
395
395
|
`).map((H,_)=>`${O[_]}: ${H}`).join(`
|
|
396
|
-
`),
|
|
396
|
+
`),q={start:Z.start,end:W}}else if(X.length>this.options.maxLines)Q=X.slice(0,this.options.maxLines).join(`
|
|
397
397
|
`),Q+=`
|
|
398
398
|
|
|
399
|
-
[... truncated ${X.length-this.options.maxLines} lines ...]`,J=!0;return{type:"file",path:$,content:Q,metadata:{size:Y.length,lines:X.length,truncated:J,lineRange:
|
|
399
|
+
[... truncated ${X.length-this.options.maxLines} lines ...]`,J=!0;return{type:"file",path:$,content:Q,metadata:{size:Y.length,lines:X.length,truncated:J,lineRange:q}}}async renderDirectoryTree($,Y){let Z=await z9("**/*",{cwd:$,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Z.length===0)return{type:"directory",path:Y,content:"(empty directory)"};X1.debug(`Found ${Z.length} files in directory: ${Y}`);let X=this.buildFileTree(Z),Q=this.printTree(X,Y),J=500,q=Z.length>J?`
|
|
400
400
|
|
|
401
|
-
[... and ${Z.length-J} more files]`:"";return{type:"directory",path:Y,content:Q+
|
|
402
|
-
`)}async processGlob($){let Y=await
|
|
401
|
+
[... and ${Z.length-J} more files]`:"";return{type:"directory",path:Y,content:Q+q,metadata:{lines:Z.length,truncated:Z.length>J}}}buildFileTree($){let Y=new Map;for(let Z of $){let X=Z.split("/"),Q=Y;for(let J=0;J<X.length;J++){let q=X[J],G=J===X.length-1;if(!Q.has(q))Q.set(q,G?null:new Map);if(!G)Q=Q.get(q)}}return Y}printTree($,Y,Z="",X=!0){let Q=[];if(Z==="")Q.push(`${Y}/`);let J=Array.from($.entries()).sort((q,G)=>{let K=q[1]instanceof Map,W=G[1]instanceof Map;if(K!==W)return W?1:-1;return q[0].localeCompare(G[0])});return J.forEach(([q,G],K)=>{let W=K===J.length-1,O=W?"└── ":"├── ",U=G instanceof Map;if(Q.push(`${Z}${O}${q}${U?"/":""}`),U&&G.size>0){let H=Z+(W?" ":"│ ");Q.push(this.printTree(G,"",H,W))}}),Q.filter((q)=>q).join(`
|
|
402
|
+
`)}async processGlob($){let Y=await z9($,{cwd:this.options.cwd,dot:!1,followSymbolicLinks:!1,onlyFiles:!0,unique:!0,ignore:["node_modules/**",".git/**","dist/**","build/**",".next/**",".cache/**","coverage/**"]});if(Y.length===0)return{type:"error",path:$,content:"",error:`No files matched pattern: ${$}`};X1.debug(`Glob pattern "${$}" matched ${Y.length} files`);let Z=30,X=Y.slice(0,Z),J=(await Promise.allSettled(X.map(async(W)=>{let O=N9.join(this.options.cwd,W);try{let U=await F$.readFile(O,"utf-8"),H=U.split(`
|
|
403
403
|
`),_=200,z=U,F=!1;if(H.length>200)z=H.slice(0,200).join(`
|
|
404
404
|
`),z+=`
|
|
405
405
|
|
|
406
|
-
[... truncated ${H.length-200} lines ...]`,F=!0;return{path:W,content:z,lines:H.length,truncated:F}}catch(U){return{path:W,content:`[Error: ${U instanceof Error?U.message:"unknown error"}]`,lines:0,truncated:!1}}}))).map((W)=>W.status==="fulfilled"?W.value:null).filter((W)=>W!==null),
|
|
406
|
+
[... truncated ${H.length-200} lines ...]`,F=!0;return{path:W,content:z,lines:H.length,truncated:F}}catch(U){return{path:W,content:`[Error: ${U instanceof Error?U.message:"unknown error"}]`,lines:0,truncated:!1}}}))).map((W)=>W.status==="fulfilled"?W.value:null).filter((W)=>W!==null),G=J.map((W)=>`--- ${W.path} (${W.lines} lines${W.truncated?", truncated":""}) ---
|
|
407
407
|
${W.content}`).join(`
|
|
408
408
|
|
|
409
409
|
`),K=Y.length>Z?`
|
|
410
410
|
|
|
411
|
-
[... and ${Y.length-Z} more files matched]`:"";return{type:"file",path:$,content:
|
|
412
|
-
`),J=1;for(let
|
|
411
|
+
[... and ${Y.length-Z} more files matched]`:"";return{type:"file",path:$,content:G+K,metadata:{lines:J.reduce((W,O)=>W+O.lines,0),truncated:Y.length>Z||J.some((W)=>W.truncated)}}}clearExpiredCache(){let $=Date.now(),Y=0;for(let[Z,X]of this.fileCache.entries())if($-X.timestamp>60000)this.fileCache.delete(Z),Y++;if(Y>0)X1.debug(`Cleared ${Y} expired cache entries`)}clearCache(){this.fileCache.clear(),X1.debug("Cleared all cache")}getCacheStats(){return{size:this.fileCache.size,keys:Array.from(this.fileCache.keys())}}}import*as o9 from"os";import*as s9 from"path";import{promises as n6}from"fs";import{extname as h7}from"path";import{z as f2}from"zod";import{isAbsolute as B9}from"path";import{z as L0}from"zod";var G0={filePath:($)=>L0.string().min(1,"File path is required").refine((Y)=>B9(Y),{message:"Path must be absolute"}).describe($?.description||"Absolute file path"),encoding:()=>L0.enum(["utf8","base64","binary"]).default("utf8").describe("File encoding"),timeout:($=1000,Y=300000,Z=30000)=>L0.number().int("Must be an integer").min($,`Cannot be less than ${$}ms`).max(Y,`Cannot exceed ${Y}ms`).default(Z).describe(`Timeout in milliseconds (default ${Z}ms)`),pattern:($)=>L0.string().min(1,"Pattern is required").describe($?.description||"Regex or glob pattern"),glob:($)=>L0.string().min(1,"Glob pattern is required").describe($?.description||'Glob pattern (e.g., "*.js", "**/*.ts")'),lineNumber:($)=>L0.number().int("Line number must be an integer").min($?.min??0,`Line number cannot be less than ${$?.min??0}`).describe($?.description||"Line number"),lineLimit:($)=>L0.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:()=>L0.string().min(1,"Working directory is required").refine(($)=>B9($),{message:"Path must be absolute"}).describe("Absolute working directory"),environment:()=>L0.record(L0.string(),L0.string()).describe("Environment variables (key-value)").optional(),outputMode:($,Y)=>{let Z=L0.enum($);return Y?Z.default(Y):Z},flag:($)=>L0.boolean().default($?.defaultValue??!1).describe($?.description||"Boolean flag"),url:($)=>L0.string().url("Must be a valid URL").describe($?.description||"URL"),port:()=>L0.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:($)=>L0.string().min(1,"Command is required").describe($?.description||"Command to execute"),sessionId:()=>L0.string().min(1,"Session ID is required").uuid("Must be a valid UUID").optional().describe("Session identifier (UUID)"),nonNegativeInt:($)=>L0.number().int("Must be an integer").min(0,"Cannot be negative").describe($?.description||"Non-negative integer"),positiveInt:($)=>L0.number().int("Must be an integer").min(1,"Must be greater than 0").describe($?.description||"Positive integer")};import*as l6 from"diff";function L9($,Y,Z=4){if($===Y)return null;let X=l6.createPatch("file",$,Y,"","",{context:Z}),Q=X.split(`
|
|
412
|
+
`),J=1;for(let q of Q){let G=q.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(G){J=parseInt(G[1],10);break}}return`
|
|
413
413
|
<<<DIFF>>>
|
|
414
414
|
${JSON.stringify({patch:X,startLine:Math.max(1,J-Z),matchLine:J})}
|
|
415
415
|
<<</DIFF>>>
|
|
416
|
-
`}function
|
|
416
|
+
`}function w9($,Y,Z,X,Q=4){let J=$.indexOf(Z);if(J===-1)return null;let G=$.substring(0,J).split(`
|
|
417
417
|
`).length-1,K=$.split(`
|
|
418
418
|
`),W=Y.split(`
|
|
419
419
|
`),O=Z.split(`
|
|
420
420
|
`),U=X.split(`
|
|
421
|
-
`),H=Math.max(0,
|
|
422
|
-
`),
|
|
423
|
-
`),
|
|
421
|
+
`),H=Math.max(0,G-Q),_=Math.min(K.length,G+O.length+Q),z=Math.min(W.length,G+U.length+Q),F=K.slice(H,_).join(`
|
|
422
|
+
`),w=W.slice(H,z).join(`
|
|
423
|
+
`),L=l6.createPatch("file",F,w,"","",{context:Q});return`
|
|
424
424
|
<<<DIFF>>>
|
|
425
|
-
${JSON.stringify({patch:
|
|
425
|
+
${JSON.stringify({patch:L,startLine:H+1,matchLine:G+1})}
|
|
426
426
|
<<</DIFF>>>
|
|
427
|
-
`}function
|
|
427
|
+
`}function A9($){return $.replace(/\\+(n|t|r|'|"|`|\\|\n)/g,(Y,Z)=>{switch(Z){case"n":return`
|
|
428
428
|
`;case"t":return"\t";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
|
|
429
429
|
`:return`
|
|
430
|
-
`;default:return Y}})}function
|
|
431
|
-
`);if(Z.length===1)return null;let Q=Z[0].match(/^(\s+)/);if(!Q)return null;let J=Q[1],
|
|
430
|
+
`;default:return Y}})}function R9($,Y){let Z=Y.split(`
|
|
431
|
+
`);if(Z.length===1)return null;let Q=Z[0].match(/^(\s+)/);if(!Q)return null;let J=Q[1],G=Z.map((W)=>{if(W.startsWith(J))return W.slice(J.length);return W}).join(`
|
|
432
432
|
`),K=$.split(`
|
|
433
433
|
`);for(let W=0;W<=K.length-Z.length;W++){let O=K[W].match(/^(\s+)/),U=O?O[1]:"",H=K.slice(W,W+Z.length);if(H.map((F)=>{if(F.startsWith(U))return F.slice(U.length);return F}).join(`
|
|
434
|
-
`)===
|
|
435
|
-
`)}return null}import{promises as
|
|
434
|
+
`)===G)return H.join(`
|
|
435
|
+
`)}return null}import{promises as C2}from"node:fs";var n$=Y0("Tool");class T0{static instance=null;accessedFiles=new Map;constructor(){}static getInstance(){if(!T0.instance)T0.instance=new T0;return T0.instance}async recordFileRead($,Y){try{let Z=await C2.stat($),X={filePath:$,accessTime:Date.now(),mtime:Z.mtimeMs,sessionId:Y,lastOperation:"read"};this.accessedFiles.set($,X),n$.debug(`记录文件读取: ${$}`)}catch(Z){n$.warn(`记录文件读取失败: ${$}`,Z)}}async recordFileEdit($,Y,Z="edit"){try{let X=await C2.stat($),Q={filePath:$,accessTime:Date.now(),mtime:X.mtimeMs,sessionId:Y,lastOperation:Z};this.accessedFiles.set($,Q),n$.debug(`记录文件${Z==="edit"?"编辑":"写入"}: ${$}`)}catch(X){n$.warn(`记录文件${Z==="edit"?"编辑":"写入"}失败: ${$}`,X)}}hasFileBeenRead($,Y){let Z=this.accessedFiles.get($);if(!Z)return!1;if(Y&&Z.sessionId!==Y)return!1;return!0}async checkFileModification($){let Y=this.accessedFiles.get($);if(!Y)return{modified:!1,message:"文件未被跟踪"};try{let Z=await C2.stat($);if(Math.abs(Z.mtimeMs-Y.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(Y.accessTime).toISOString()}, 当前修改时间: ${Z.mtime.toISOString()})`};return{modified:!1}}catch(Z){if(Z.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${Z.message}`}}}async checkExternalModification($){let Y=this.accessedFiles.get($);if(!Y)return{isExternal:!1,message:"文件未被跟踪"};try{let Z=await C2.stat($);if(Z.mtimeMs-Y.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(Y.accessTime).toISOString()} (${Y.lastOperation}) 之后被外部程序修改(当前修改时间: ${Z.mtime.toISOString()})`};return{isExternal:!1}}catch(Z){if(Z.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return n$.warn(`检查文件外部修改失败: ${$}`,Z),{isExternal:!1,message:`无法检查文件状态: ${Z.message}`}}}getFileRecord($){return this.accessedFiles.get($)}clearFileRecord($){this.accessedFiles.delete($)}clearAll(){this.accessedFiles.clear()}clearSession($){for(let[Y,Z]of this.accessedFiles.entries())if(Z.sessionId===$)this.accessedFiles.delete(Y)}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){T0.instance=null}}N$();import*as D9 from"node:crypto";import{promises as _1}from"node:fs";import*as s1 from"node:path";class o${sessionId;enableCheckpoints;maxSnapshots;snapshotDir;trackedFileBackups=new Map;snapshots=[];constructor($){this.sessionId=$.sessionId,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let Y=j1();this.snapshotDir=s1.join(Y,"file-history",this.sessionId)}async initialize(){if(!this.enableCheckpoints)return;try{await _1.mkdir(this.snapshotDir,{recursive:!0}),console.log(`[SnapshotManager] 初始化快照目录: ${this.snapshotDir}`)}catch($){throw console.warn("[SnapshotManager] 创建快照目录失败:",$),$}}async createSnapshot($,Y){if(!this.enableCheckpoints)return console.log("[SnapshotManager] 检查点已禁用,跳过快照创建"),{backupFileName:"",version:0,backupTime:new Date};try{await _1.access($)}catch{return console.warn(`[SnapshotManager] 文件不存在,跳过快照: ${$}`),{backupFileName:"",version:0,backupTime:new Date}}let Z=this.trackedFileBackups.get($),X=Z?Z.version+1:1,Q=this.generateFileHash($,X),J=s1.join(this.snapshotDir,`${Q}@v${X}`);try{let q=await _1.readFile($,{encoding:"utf-8"});await _1.writeFile(J,q,{encoding:"utf-8"});let G={backupFileName:Q,version:X,backupTime:new Date};return this.trackedFileBackups.set($,G),this.snapshots.push({messageId:Y,backupFileName:Q,timestamp:new Date,filePath:$}),console.log(`[SnapshotManager] 创建快照: ${$} -> ${Q}@v${X}`),await this.cleanupOldSnapshots($),G}catch(q){throw console.error(`[SnapshotManager] 创建快照失败: ${$}`,q),q}}async restoreSnapshot($,Y){let Z=this.snapshots.slice().reverse().find((J)=>J.messageId===Y&&J.filePath===$);if(!Z)throw Error(`未找到快照: messageId=${Y}, filePath=${$}`);let X=this.trackedFileBackups.get($);if(!X)throw Error(`未找到文件追踪信息: ${$}`);let Q=s1.join(this.snapshotDir,`${Z.backupFileName}@v${X.version}`);try{let J=await _1.readFile(Q,{encoding:"utf-8"});await _1.writeFile($,J,{encoding:"utf-8"}),console.log(`[SnapshotManager] 恢复快照: ${$} <- ${Z.backupFileName}@v${X.version}`)}catch(J){throw console.error(`[SnapshotManager] 恢复快照失败: ${$}`,J),J}}async listSnapshots($){return this.snapshots.filter((Y)=>Y.filePath===$)}async cleanupOldSnapshots($){let Y=this.snapshots.filter((Q)=>Q.filePath===$);if(Y.length<=this.maxSnapshots)return;let X=Y.sort((Q,J)=>Q.timestamp.getTime()-J.timestamp.getTime()).slice(0,Y.length-this.maxSnapshots);for(let Q of X){let J=this.trackedFileBackups.get(Q.filePath);if(!J)continue;let q=s1.join(this.snapshotDir,`${Q.backupFileName}@v${J.version}`);try{await _1.unlink(q),console.log(`[SnapshotManager] 删除旧快照: ${q}`)}catch(K){console.warn(`[SnapshotManager] 删除快照失败: ${q}`,K)}let G=this.snapshots.indexOf(Q);if(G>-1)this.snapshots.splice(G,1)}}async cleanup($=0){try{let Y=await _1.readdir(this.snapshotDir);if(Y.length<=$)return;let Z=await Promise.all(Y.map(async(Q)=>{let J=s1.join(this.snapshotDir,Q),q=await _1.stat(J);return{file:Q,mtime:q.mtime.getTime()}}));Z.sort((Q,J)=>J.mtime-Q.mtime);let X=Z.slice($);for(let{file:Q}of X){let J=s1.join(this.snapshotDir,Q);await _1.unlink(J),console.log(`[SnapshotManager] 清理快照: ${J}`)}}catch(Y){console.warn("[SnapshotManager] 清理快照失败:",Y)}}generateFileHash($,Y){let Z=D9.createHash("md5");return Z.update(`${$}:${Y}`),Z.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var o6=n({name:"Edit",displayName:"File Edit",kind:"write",strict:!0,isConcurrencySafe:!1,schema:f2.object({file_path:G0.filePath({description:"Absolute path of the file to edit"}),old_string:f2.string().min(1,"old_string cannot be empty").describe("String to replace"),new_string:f2.string().describe("Replacement string (can be empty)"),replace_all:f2.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($,Y){let{file_path:Z,old_string:X,new_string:Q,replace_all:J}=$,{updateOutput:q,sessionId:G,messageId:K}=Y,W=Y.signal??new AbortController().signal;try{q?.("Starting to read file...");let O;try{O=await n6.readFile(Z,"utf8")}catch(R){if(R.code==="ENOENT")return{success:!1,llmContent:`File not found: ${Z}`,displayContent:`❌ 文件不存在: ${Z}`,error:{type:"execution_error",message:"文件不存在"}};throw R}if(W.throwIfAborted(),G){let R=T0.getInstance();if(!R.hasFileBeenRead(Z,G))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.",displayContent:`❌ 编辑失败:必须先使用 Read 工具读取文件
|
|
436
436
|
|
|
437
|
-
请先用 Read 工具查看文件内容,再进行编辑。`,error:{type:"validation_error",message:"File not read before edit"}};let
|
|
437
|
+
请先用 Read 工具查看文件内容,再进行编辑。`,error:{type:"validation_error",message:"File not read before edit"}};let B=await R.checkExternalModification(Z);if(B.isExternal)return{success:!1,llmContent:`The file has been modified by an external program since you last read it. You must use the Read tool again to see the current content before editing.
|
|
438
438
|
|
|
439
|
-
Details: ${
|
|
439
|
+
Details: ${B.message}`,displayContent:`❌ 编辑失败:文件已被外部程序修改
|
|
440
440
|
|
|
441
|
-
${
|
|
441
|
+
${B.message}
|
|
442
442
|
|
|
443
|
-
\uD83D\uDCA1 请重新使用 Read 工具读取最新内容后再编辑`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:
|
|
444
|
-
`),
|
|
445
|
-
`),p=["⚠️ 编辑暂停:需要更精确的定位","",`在文件中找到 ${_.length} 处相似代码:`,...
|
|
446
|
-
`);return{success:!1,llmContent:C,displayContent:p,error:{type:"validation_error",message:"old_string is not unique",details:{matches:
|
|
447
|
-
\uD83D\uDCDD 替换了 ${Q} 个匹配项`,!J&&X>1)
|
|
448
|
-
\uD83D\uDCCA 文件大小${K}个字符`}if(Y)
|
|
449
|
-
`),Q=X.length,J=
|
|
443
|
+
\uD83D\uDCA1 请重新使用 Read 工具读取最新内容后再编辑`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:B.message}}}}if(G&&K)try{let R=new o$({sessionId:G});await R.initialize(),await R.createSnapshot(Z,K)}catch(R){console.warn("[EditTool] 创建快照失败:",R)}if(X===Q)return{success:!1,llmContent:"New string is identical; no replacement needed",displayContent:"⚠️ 新字符串与旧字符串相同,无需进行替换",error:{type:"validation_error",message:"新旧字符串相同"}};let U=x7(O,X);if(!U.matched){let R=m7(O,X,Z);return{success:!1,llmContent:R.llmContent,displayContent:R.displayContent,error:{type:"execution_error",message:"未找到匹配内容",details:R.metadata}}}let H=U.matched;if(U.strategy!=="exact")console.log(`[SmartEdit] 使用策略: ${U.strategy}`);let _=p7(O,H);if(_.length>1&&!J){let R=O.split(`
|
|
444
|
+
`),B=0,D=[];for(let y=0;y<R.length;y++){let M=R[y],i=B,S=B+M.length;for(let U1 of _)if(U1>=i&&U1<S){let Q0=Math.max(0,y-1),_0=Math.min(R.length-1,y+1),q$=R.slice(Q0,_0+1).map((C$)=>C$.trim()).join(" ").slice(0,80);D.push({line:y+1,column:U1-i+1,context:q$})}B=S+1}let C=[`⚠️ EDIT PAUSED: old_string matches ${_.length} locations (must be unique).`,"","**Matches found at:**",...D.map((y,M)=>` ${M+1}. Line ${y.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 ${_.length} occurrences`,"","\uD83E\uDD16 **Auto-retry expected** - This usually resolves in 1-2 attempts."].join(`
|
|
445
|
+
`),p=["⚠️ 编辑暂停:需要更精确的定位","",`在文件中找到 ${_.length} 处相似代码:`,...D.map((y,M)=>` • 第 ${y.line} 行 (匹配 ${M+1}/${_.length})`),"","AI 正在自动调整,添加更多上下文以精确定位...","通常需要 1-2 次尝试即可成功","","\uD83D\uDCA1 如果多次失败,可能需要:"," • 包含函数/类名等独特标识符"," • 添加目标代码前后 3-5 行完整上下文",` • 或使用 replace_all=true 同时替换所有 ${_.length} 处匹配`].join(`
|
|
446
|
+
`);return{success:!1,llmContent:C,displayContent:p,error:{type:"validation_error",message:"old_string is not unique",details:{matches:D.map((y)=>({line:y.line,column:y.column})),count:_.length}}}}else q?.(`找到 ${_.length} 个匹配项,开始替换...`);let z,F;if(J)z=O.split(H).join(Q),F=_.length;else{let R=O.indexOf(H);z=O.substring(0,R)+Q+O.substring(R+H.length),F=1}if(W.throwIfAborted(),await n6.writeFile(Z,z,"utf8"),G)await T0.getInstance().recordFileEdit(Z,G,"edit");let w=await n6.stat(Z),L=w9(O,z,H,Q,4),N=Z.split("/").pop()||Z,A=F===1?`替换 1 处匹配到 ${N}`:`替换 ${F} 处匹配到 ${N}`,V={file_path:Z,matches_found:_.length,replacements_made:F,replace_all:J,old_string_length:X.length,new_string_length:Q.length,original_size:O.length,new_size:z.length,size_diff:z.length-O.length,last_modified:w.mtime.toISOString(),snapshot_created:!!(G&&K),session_id:G,message_id:K,diff_snippet:L,summary:A},E=g7(V,L);return{success:!0,llmContent:{file_path:Z,replacements:F,total_matches:_.length},displayContent:E,metadata:V}}catch(O){if(O.name==="AbortError")return{success:!1,llmContent:"File edit aborted",displayContent:"⚠️ 文件编辑被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File edit failed: ${O.message}`,displayContent:`❌ 编辑文件失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"文件操作",tags:["file","edit","replace","modify"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Y=h7($.file_path);return Y?`**/*${Y}`:"**/*"}});function I9($){return $.replaceAll("‘","'").replaceAll("’","'").replaceAll("“",'"').replaceAll("”",'"')}function x7($,Y){if($.includes(Y))return{matched:Y,strategy:"exact"};let Z=I9(Y),Q=I9($).indexOf(Z);if(Q!==-1)return{matched:$.substring(Q,Q+Y.length),strategy:"normalize_quotes"};let J=A9(Y);if(J!==Y&&$.includes(J))return{matched:J,strategy:"unescape"};let q=R9($,Y);if(q)return{matched:q,strategy:"flexible"};return{matched:null,strategy:"failed"}}function p7($,Y){if(Y.length===0)return[];let Z=[],X=$.indexOf(Y);while(X!==-1)Z.push(X),X=$.indexOf(Y,X+Y.length);return Z}function g7($,Y){let{file_path:Z,matches_found:X,replacements_made:Q,replace_all:J,size_diff:q}=$,G=`✅ 成功编辑文件: ${Z}`;if(G+=`
|
|
447
|
+
\uD83D\uDCDD 替换了 ${Q} 个匹配项`,!J&&X>1)G+=` (共找到 ${X} 个匹配项)`;if(q!==0){let K=q>0?`增加${q}`:`减少${Math.abs(q)}`;G+=`
|
|
448
|
+
\uD83D\uDCCA 文件大小${K}个字符`}if(Y)G+=Y;return G}function m7($,Y,Z){let X=$.split(`
|
|
449
|
+
`),Q=X.length,J=u7($,Y,3),q=0,G=Math.min(20,Q);if(J.length>0){let _=J[0];q=Math.max(0,_.lineNumber-10),G=Math.min(Q,_.lineNumber+10)}let W=X.slice(q,G).map((_,z)=>{return` ${(q+z+1).toString().padStart(4)}: ${_}`}).join(`
|
|
450
450
|
`),O=`String not found in file.
|
|
451
451
|
|
|
452
452
|
File: ${Z}
|
|
@@ -456,10 +456,10 @@ Total lines: ${Q}
|
|
|
456
456
|
... (truncated)`:Y;if(O+=`You tried to match:
|
|
457
457
|
${U}
|
|
458
458
|
|
|
459
|
-
`,J.length>0)O+=`File content around possible matches (lines ${
|
|
459
|
+
`,J.length>0)O+=`File content around possible matches (lines ${q+1}-${G}):
|
|
460
460
|
${W}
|
|
461
461
|
|
|
462
|
-
`;else O+=`File content preview (lines ${
|
|
462
|
+
`;else O+=`File content preview (lines ${q+1}-${G}):
|
|
463
463
|
${W}
|
|
464
464
|
|
|
465
465
|
`;if(J.length>0)O+=`Possible similar matches found:
|
|
@@ -486,20 +486,20 @@ Common issues:
|
|
|
486
486
|
`});else H+=`
|
|
487
487
|
⚠️ 未找到相似的匹配项
|
|
488
488
|
`;return H+=`
|
|
489
|
-
\uD83D\uDCC4 文件内容摘录 (${
|
|
489
|
+
\uD83D\uDCC4 文件内容摘录 (${q+1}-${G} 行):
|
|
490
490
|
${W}
|
|
491
491
|
`,H+=`
|
|
492
492
|
\uD83D\uDD27 建议:
|
|
493
493
|
`,H+=` 1. 使用 Read 工具重新读取文件
|
|
494
494
|
`,H+=` 2. 检查空格、换行符、引号是否完全匹配
|
|
495
|
-
`,H+=" 3. 提供更多上下文代码确保唯一性",{llmContent:O,displayContent:H,metadata:{searchStringLength:Y.length,fuzzyMatches:J.map((_)=>({line:_.lineNumber,similarity:_.similarity,preview:_.text.substring(0,100)})),excerptRange:[
|
|
495
|
+
`,H+=" 3. 提供更多上下文代码确保唯一性",{llmContent:O,displayContent:H,metadata:{searchStringLength:Y.length,fuzzyMatches:J.map((_)=>({line:_.lineNumber,similarity:_.similarity,preview:_.text.substring(0,100)})),excerptRange:[q+1,G],totalLines:Q}}}function u7($,Y,Z=3){let X=$.split(`
|
|
496
496
|
`),Q=Y.split(`
|
|
497
|
-
`);if(Q.length===1)return X.map((K,W)=>({text:K,lineNumber:W+1,similarity:
|
|
498
|
-
`),W=
|
|
499
|
-
`),V=X||0,E=Q!==void 0?V+Q:A.length,R=A.slice(V,E);_=R.map((
|
|
500
|
-
`),z.lines_read=R.length,z.total_lines=A.length,z.start_line=V+1,z.end_line=Math.min(E,A.length)}let F=Z.split("/").pop()||Z,
|
|
497
|
+
`);if(Q.length===1)return X.map((K,W)=>({text:K,lineNumber:W+1,similarity:k9(Y.trim(),K.trim())})).filter((K)=>K.similarity>0.5).sort((K,W)=>W.similarity-K.similarity).slice(0,Z);let J=Q.length,q=[];for(let G=0;G<=X.length-J;G++){let K=X.slice(G,G+J).join(`
|
|
498
|
+
`),W=k9(Y,K);if(W>0.5)q.push({text:K,lineNumber:G+1,similarity:W})}return q.sort((G,K)=>K.similarity-G.similarity).slice(0,Z)}function k9($,Y){let Z=(H)=>H.trim().replace(/\s+/g," ").replace(/[\u201c\u201d"]/g,'"').replace(/[\u2018\u2019']/g,"'"),X=Z($),Q=Z(Y);if(X===Q)return 1;let J=X.length,q=Q.length;if(J===0)return q===0?1:0;if(q===0)return 0;let G=200,K=X.substring(0,G),W=Q.substring(0,G),O=d7(K,W),U=Math.max(K.length,W.length);return 1-O/U}function d7($,Y){let Z=$.length,X=Y.length,Q=Array(Z+1).fill(null).map(()=>Array(X+1).fill(0));for(let J=0;J<=Z;J++)Q[J][0]=J;for(let J=0;J<=X;J++)Q[0][J]=J;for(let J=1;J<=Z;J++)for(let q=1;q<=X;q++){let G=$[J-1]===Y[q-1]?0:1;Q[J][q]=Math.min(Q[J-1][q]+1,Q[J][q-1]+1,Q[J-1][q-1]+G)}return Q[Z][X]}import{promises as h2}from"fs";import{extname as v9}from"path";import{z as c7}from"zod";var s6=n({name:"Read",displayName:"File Read",kind:"readonly",schema:c7.object({file_path:G0.filePath({description:"File path to read (must be absolute)"}),offset:G0.lineNumber({description:"Starting line number (0-based, text files only)"}).optional(),limit:G0.lineLimit({description:"Number of lines to read (text files only)"}).optional(),encoding:G0.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($,Y){let{file_path:Z,offset:X,limit:Q,encoding:J="utf8"}=$,{updateOutput:q,sessionId:G}=Y,K=Y.signal??new AbortController().signal;try{q?.("Starting file read...");try{await h2.access(Z)}catch(A){return{success:!1,llmContent:`File not found: ${Z}`,displayContent:`❌ 文件不存在: ${Z}`,error:{type:"execution_error",message:`File not found: ${Z}`}}}if(K.throwIfAborted(),G)await T0.getInstance().recordFileRead(Z,G);let W=await h2.stat(Z);if(W.isDirectory())return{success:!1,llmContent:`Cannot read a directory: ${Z}`,displayContent:`❌ 无法读取目录: ${Z}`,error:{type:"execution_error",message:"Target is a directory, not a file"}};let O=v9(Z).toLowerCase(),U=l7(O),H=i7(O),_,z={file_path:Z,file_size:W.size,file_type:O,last_modified:W.mtime.toISOString(),encoding:J};if(H&&J==="utf8")q?.("检测到二进制文件,使用 base64 编码..."),_=await h2.readFile(Z,"base64"),z.encoding="base64",z.is_binary=!0;else{let A=await h2.readFile(Z);if(J==="base64")_=A.toString("base64");else if(J==="binary")_=A.toString("binary");else _=A.toString("utf8")}if(K.throwIfAborted(),(X!==void 0||Q!==void 0)&&J==="utf8"&&U){let A=_.split(`
|
|
499
|
+
`),V=X||0,E=Q!==void 0?V+Q:A.length,R=A.slice(V,E);_=R.map((B,D)=>{let C=V+D+1,p=B.length>2000?`${B.substring(0,2000)}...`:B;return`${C.toString().padStart(6)}→${p}`}).join(`
|
|
500
|
+
`),z.lines_read=R.length,z.total_lines=A.length,z.start_line=V+1,z.end_line=Math.min(E,A.length)}let F=Z.split("/").pop()||Z,w=z.lines_read||z.total_lines,L=w?`读取 ${w} 行从 ${F}`:`读取 ${F}`;z.summary=L;let N=r7(Z,z);return{success:!0,llmContent:_,displayContent:N,metadata:z}}catch(W){if(W.name==="AbortError")return{success:!1,llmContent:"File read aborted",displayContent:"⚠️ 文件读取被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`File read failed: ${W.message}`,displayContent:`❌ 读取文件失败: ${W.message}`,error:{type:"execution_error",message:W.message,details:W}}}},version:"2.0.0",category:"文件操作",tags:["file","io","read"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Y=v9($.file_path);return Y?`**/*${Y}`:"**/*"}});function l7($){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 i7($){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($)}function r7($,Y){let Z=`✅ 成功读取文件: ${$}`;if(Y.file_size!==void 0)Z+=` (${a7(Y.file_size)})`;if(Y.lines_read!==void 0)Z+=`
|
|
501
501
|
\uD83D\uDCC4 读取了 ${Y.lines_read} 行 (第${Y.start_line}-${Y.end_line}行,共${Y.total_lines}行)`;if(Y.is_binary)Z+=`
|
|
502
|
-
\uD83D\uDD10 文件以 base64 编码显示`;return Z}function
|
|
502
|
+
\uD83D\uDD10 文件以 base64 编码显示`;return Z}function a7($){let Y=["B","KB","MB","GB"],Z=$,X=0;while(Z>=1024&&X<Y.length-1)Z/=1024,X++;return`${Z.toFixed(1)}${Y[X]}`}import{promises as s$}from"fs";import{dirname as n7,extname as M9}from"path";import{z as t6}from"zod";var e6=n({name:"Write",displayName:"File Write",kind:"write",strict:!0,isConcurrencySafe:!1,schema:t6.object({file_path:G0.filePath({description:"Absolute file path to write"}),content:t6.string().describe("Content to write"),encoding:G0.encoding(),create_directories:t6.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($,Y){let{file_path:Z,content:X,encoding:Q,create_directories:J}=$,{updateOutput:q,sessionId:G,messageId:K}=Y,W=Y.signal??new AbortController().signal;try{if(q?.("开始写入文件..."),J){let V=n7(Z);try{await s$.mkdir(V,{recursive:!0})}catch(E){if(E.code!=="EEXIST")throw E}}W.throwIfAborted();let O=!1,U=null;try{if(await s$.access(Z),O=!0,Q==="utf8")try{U=await s$.readFile(Z,"utf8")}catch(V){console.warn("[WriteTool] 读取旧文件内容失败:",V)}}catch{}if(O&&G){let V=T0.getInstance();if(!V.hasFileBeenRead(Z,G))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.",displayContent:`❌ 写入失败:必须先使用 Read 工具读取文件
|
|
503
503
|
|
|
504
504
|
文件 ${Z} 已存在,请先用 Read 工具查看其内容。`,error:{type:"validation_error",message:"File not read before write"}};let E=await V.checkExternalModification(Z);if(E.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.
|
|
505
505
|
|
|
@@ -507,25 +507,25 @@ Details: ${E.message}`,displayContent:`❌ 写入失败:文件已被外部程
|
|
|
507
507
|
|
|
508
508
|
${E.message}
|
|
509
509
|
|
|
510
|
-
\uD83D\uDCA1 请重新使用 Read 工具读取最新内容后再写入`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:E.message}}}}let H=!1;if(O&&
|
|
511
|
-
`).length:0,
|
|
510
|
+
\uD83D\uDCA1 请重新使用 Read 工具读取最新内容后再写入`,error:{type:"validation_error",message:"File modified externally",details:{externalModification:E.message}}}}let H=!1;if(O&&G&&K)try{let V=new o$({sessionId:G});await V.initialize(),await V.createSnapshot(Z,K),H=!0}catch(V){console.warn("[WriteTool] 创建快照失败:",V)}W.throwIfAborted();let _;if(Q==="base64")_=Buffer.from(X,"base64");else if(Q==="binary")_=Buffer.from(X,"binary");else _=Buffer.from(X,"utf8");if(await s$.writeFile(Z,_),G)await T0.getInstance().recordFileEdit(Z,G,"write");W.throwIfAborted();let z=await s$.stat(Z),F=Q==="utf8"?X.split(`
|
|
511
|
+
`).length:0,w=Z.split("/").pop()||Z,L=null;if(U&&Q==="utf8"&&U!==X){if(U.length<1048576&&X.length<1048576)L=L9(U,X,4)}let N={file_path:Z,content_size:X.length,file_size:z.size,encoding:Q,created_directories:J,snapshot_created:H,session_id:G,message_id:K,last_modified:z.mtime.toISOString(),has_diff:!!L,summary:Q==="utf8"?`写入 ${F} 行到 ${w}`:`写入 ${y9(z.size)} 到 ${w}`},A=o7(Z,N,X,L);return{success:!0,llmContent:{file_path:Z,size:z.size,modified:z.mtime.toISOString()},displayContent:A,metadata:N}}catch(O){if(O.name==="AbortError")return{success:!1,llmContent:"File write aborted",displayContent:"⚠️ 文件写入被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`File write failed: ${O.message}`,displayContent:`❌ 写入文件失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"文件操作",tags:["file","io","write","create"],extractSignatureContent:($)=>$.file_path,abstractPermissionRule:($)=>{let Y=M9($.file_path);return Y?`**/*${Y}`:"**/*"}});function o7($,Y,Z,X){let Q=`✅ 成功写入文件: ${$}`;if(Y.file_size!==void 0)Q+=` (${y9(Y.file_size)})`;if(Y.snapshot_created)Q+=`
|
|
512
512
|
\uD83D\uDCF8 已创建快照 (可回滚)`;if(Y.encoding!=="utf8")Q+=`
|
|
513
|
-
\uD83D\uDD10 使用编码: ${Y.encoding}`;if(X)Q+=X;if(Z&&Y.encoding==="utf8"&&!X){let J=
|
|
513
|
+
\uD83D\uDD10 使用编码: ${Y.encoding}`;if(X)Q+=X;if(Z&&Y.encoding==="utf8"&&!X){let J=s7($,Z);if(J)Q+=`
|
|
514
514
|
|
|
515
|
-
`+J}return Q}function
|
|
516
|
-
`);if(W.length>100)
|
|
517
|
-
`),K=!0;if(
|
|
515
|
+
`+J}return Q}function s7($,Y){let Z=M9($).toLowerCase(),Q={".ts":"typescript",".tsx":"tsx",".js":"javascript",".jsx":"jsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".cpp":"cpp",".h":"c",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".scala":"scala",".sh":"bash",".bash":"bash",".zsh":"zsh",".json":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".xml":"xml",".html":"html",".css":"css",".scss":"scss",".sass":"sass",".less":"less",".md":"markdown",".sql":"sql",".graphql":"graphql",".proto":"protobuf"}[Z]||"",J=100,q=5000,G=Y,K=!1,W=Y.split(`
|
|
516
|
+
`);if(W.length>100)G=W.slice(0,100).join(`
|
|
517
|
+
`),K=!0;if(G.length>5000)G=G.substring(0,5000),K=!0;let O=`\uD83D\uDCC4 文件内容:
|
|
518
518
|
|
|
519
519
|
`;if(O+="```"+Q+`
|
|
520
|
-
`,O+=
|
|
520
|
+
`,O+=G,!G.endsWith(`
|
|
521
521
|
`))O+=`
|
|
522
522
|
`;if(O+="```",K)O+=`
|
|
523
523
|
|
|
524
|
-
⚠️ 内容已截断(完整文件共 ${W.length} 行,${Y.length} 字符)`;return O}function
|
|
524
|
+
⚠️ 内容已截断(完整文件共 ${W.length} 行,${Y.length} 字符)`;return O}function y9($){let Y=["B","KB","MB","GB"],Z=$,X=0;while(Z>=1024&&X<Y.length-1)Z/=1024,X++;return`${Z.toFixed(1)}${Y[X]}`}import*as x2 from"fs/promises";import{z as B$}from"zod";var $4=n({name:"NotebookEdit",displayName:"Notebook Edit",kind:"write",schema:B$.object({notebook_path:B$.string().describe("The absolute path to the Jupyter notebook file to edit (must be absolute, not relative)"),cell_id:B$.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:B$.string().describe("The new source for the cell"),cell_type:B$.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:B$.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($,Y){let{notebook_path:Z,cell_id:X,new_source:Q,cell_type:J,edit_mode:q="replace"}=$;try{let G=await x2.readFile(Z,"utf-8"),K=JSON.parse(G);if(!K.cells||!Array.isArray(K.cells))return{success:!1,llmContent:"Invalid notebook format: no cells array found",displayContent:"Invalid notebook format",error:{type:"validation_error",message:"Invalid notebook format"}};let W=-1;if(X){if(W=K.cells.findIndex((U)=>U.id===X),W===-1&&q!=="insert")return{success:!1,llmContent:`Cell with ID "${X}" not found`,displayContent:"Cell not found",error:{type:"validation_error",message:`Cell ID "${X}" not found`}}}switch(q){case"replace":{if(W===-1)return{success:!1,llmContent:"Cell ID required for replace operation",displayContent:"Cell ID required",error:{type:"validation_error",message:"Cell ID required for replace"}};let U=K.cells[W];if(U.source=Q.split(`
|
|
525
525
|
`).map((H,_,z)=>_<z.length-1?H+`
|
|
526
526
|
`:H),J)U.cell_type=J;break}case"insert":{if(!J)return{success:!1,llmContent:"cell_type is required for insert operation",displayContent:"cell_type required",error:{type:"validation_error",message:"cell_type required for insert"}};let U={cell_type:J,source:Q.split(`
|
|
527
527
|
`).map((_,z,F)=>z<F.length-1?_+`
|
|
528
|
-
`:_),metadata:{},...J==="code"?{execution_count:null,outputs:[]}:{}},H=W===-1?0:W+1;K.cells.splice(H,0,U);break}case"delete":{if(W===-1)return{success:!1,llmContent:"Cell ID required for delete operation",displayContent:"Cell ID required",error:{type:"validation_error",message:"Cell ID required for delete"}};K.cells.splice(W,1);break}}await
|
|
528
|
+
`:_),metadata:{},...J==="code"?{execution_count:null,outputs:[]}:{}},H=W===-1?0:W+1;K.cells.splice(H,0,U);break}case"delete":{if(W===-1)return{success:!1,llmContent:"Cell ID required for delete operation",displayContent:"Cell ID required",error:{type:"validation_error",message:"Cell ID required for delete"}};K.cells.splice(W,1);break}}await x2.writeFile(Z,JSON.stringify(K,null,2));let O=q==="replace"?"replaced":q==="insert"?"inserted":"deleted";return{success:!0,llmContent:`Successfully ${O} cell in ${Z}`,displayContent:`Cell ${O} in notebook`,metadata:{notebook_path:Z,edit_mode:q,cell_id:X}}}catch(G){let K=G instanceof Error?G.message:"Unknown error";return{success:!1,llmContent:`Failed to edit notebook: ${K}`,displayContent:"Notebook edit failed",error:{type:"execution_error",message:K}}}}});import{z as t7}from"zod";var Y4=n({name:"EnterPlanMode",displayName:"Enter Plan Mode",kind:"readonly",schema:t7.object({}),description:{short:"Use this tool to enter plan mode for complex tasks requiring careful planning",long:`Use this tool when you encounter a complex task that requires careful planning and exploration before implementation. This tool transitions you into plan mode where you can thoroughly explore the codebase and design an implementation approach.
|
|
529
529
|
|
|
530
530
|
## When to Use This Tool
|
|
531
531
|
|
|
@@ -617,7 +617,7 @@ Begin your research now.`,displayContent:"✅ Entering Plan mode",metadata:{appr
|
|
|
617
617
|
|
|
618
618
|
`+"Proceed with the task directly without planning phase. You can still use search tools to understand the codebase as needed, but implement the solution directly.",displayContent:"⚠️ Plan mode declined, proceeding directly",metadata:{approved:!1,enterPlanMode:!1}}}catch(Z){return{success:!1,llmContent:`Confirmation flow error: ${Z instanceof Error?Z.message:"Unknown error"}`,displayContent:"❌ Failed to request confirmation",error:{type:"execution_error",message:"Confirmation flow error"}}}return{success:!0,llmContent:`Plan mode requested but no interactive confirmation available.
|
|
619
619
|
|
|
620
|
-
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,displayContent:"Plan mode (non-interactive)",metadata:{approved:null,enterPlanMode:!0}}}});import{z as
|
|
620
|
+
Proceeding with research phase. Use read-only tools to explore the codebase, then call ExitPlanMode with your implementation plan when ready.`,displayContent:"Plan mode (non-interactive)",metadata:{approved:null,enterPlanMode:!0}}}});import{z as E9}from"zod";import{promises as j9}from"node:fs";import*as Z4 from"node:path";import{homedir as e7}from"node:os";var X4=n({name:"ExitPlanMode",displayName:"Exit Plan Mode",kind:"readonly",schema:E9.object({plan:E9.string().describe("The complete implementation plan in markdown format")}),description:{short:"Use this tool when you are in plan mode and have finished creating your plan and are ready for user approval",long:`Use this tool when you are in plan mode and have finished creating your implementation plan and are ready for user approval.
|
|
621
621
|
|
|
622
622
|
## \uD83D\uDEA8 PREREQUISITES (MUST be satisfied before calling)
|
|
623
623
|
|
|
@@ -652,7 +652,7 @@ Before using this tool, ensure your plan is clear and unambiguous. If there are
|
|
|
652
652
|
1. Initial task: "Search for and understand the implementation of vim mode in the codebase" - Do not use the exit plan mode tool because you are not planning the implementation steps of a task.
|
|
653
653
|
2. Initial task: "Help me implement yank mode for vim" - Use the exit plan mode tool after you have finished planning the implementation steps of the task.
|
|
654
654
|
3. Initial task: "Add a new feature to handle user authentication" - If unsure about auth method (OAuth, JWT, etc.), use AskUserQuestion first, then use exit plan mode tool after clarifying the approach.
|
|
655
|
-
`},async execute($,Y){let Z=$.plan||"";if(Z&&Y.sessionId)try{let X=
|
|
655
|
+
`},async execute($,Y){let Z=$.plan||"";if(Z&&Y.sessionId)try{let X=Z4.join(e7(),".blade","plans");await j9.mkdir(X,{recursive:!0});let Q=Z4.join(X,`plan_${Y.sessionId}.md`);await j9.writeFile(Q,Z,"utf-8")}catch(X){console.warn("Failed to save plan file:",X)}if(Y.confirmationHandler)try{let X=await Y.confirmationHandler.requestConfirmation({type:"exitPlanMode",message:`The assistant has finished planning and is ready for your review.
|
|
656
656
|
|
|
657
657
|
`+`⚠️ Before approving, please verify:
|
|
658
658
|
`+`1. The assistant has written a detailed plan to the plan file
|
|
@@ -665,22 +665,22 @@ please reject and ask for a proper plan.`,details:"After approval, the assistant
|
|
|
665
665
|
`+(X.feedback||"No specific feedback provided.")+`
|
|
666
666
|
|
|
667
667
|
The agent has stopped and control is returned to the user. The user can now provide additional information or clarification.`,displayContent:"⚠️ 方案被拒绝,等待用户补充信息",metadata:{approved:!1,shouldExitLoop:!0,feedback:X.feedback,awaitingUserInput:!0}}}catch(X){return{success:!1,llmContent:`Confirmation flow error: ${X instanceof Error?X.message:"Unknown error"}`,displayContent:"❌ Confirmation failed",error:{type:"execution_error",message:"Confirmation flow error"}}}return{success:!0,llmContent:`✅ Plan mode exit requested. No interactive confirmation available.
|
|
668
|
-
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}});import
|
|
669
|
-
`)){let J=Q.trim();if(!J||J.startsWith("#"))continue;if(J.startsWith("!"))X.push(J.slice(1));else Z.push(J)}return{patterns:Z,negatePatterns:X}}catch(Y){return console.warn(`Failed to read .gitignore: ${Y}`),{patterns:[],negatePatterns:[]}}}var
|
|
670
|
-
`);for(let _ of H){let z=_.trim();if(!z||z.startsWith("#"))continue;let F=z.startsWith("!"),
|
|
668
|
+
`+"Proceeding with implementation.",displayContent:"Plan mode exit (non-interactive)",metadata:{approved:null}}}});import KZ from"fast-glob";import{stat as WZ}from"node:fs/promises";import{join as UZ,resolve as OZ}from"path";import{z as g2}from"zod";import $Z from"fast-glob";import{LRUCache as YZ}from"lru-cache";import{existsSync as ZZ,readFileSync as XZ}from"node:fs";import{readFile as QZ}from"node:fs/promises";import{dirname as JZ,join as S9}from"node:path";import t$ from"picomatch";var F1=["node_modules",".git","dist","build","out",".next",".nuxt",".cache",".parcel-cache","coverage",".nyc_output",".idea",".vscode",".vs","bower_components","jspm_packages"],Q4=["*.log","npm-debug.log*","yarn-debug.log*","pnpm-debug.log*","*.lock","package-lock.json","yarn.lock","pnpm-lock.yaml","*.tmp","*.temp","*.swp","*.bak","*~",".DS_Store","Thumbs.db","*.pid","*.seed"];function qZ($){if(!ZZ($))return{patterns:[],negatePatterns:[]};try{let Y=XZ($,"utf-8"),Z=[],X=[];for(let Q of Y.split(`
|
|
669
|
+
`)){let J=Q.trim();if(!J||J.startsWith("#"))continue;if(J.startsWith("!"))X.push(J.slice(1));else Z.push(J)}return{patterns:Z,negatePatterns:X}}catch(Y){return console.warn(`Failed to read .gitignore: ${Y}`),{patterns:[],negatePatterns:[]}}}var P9=new YZ({max:100,ttl:30000,updateAgeOnGet:!0});async function GZ($,Y){let Z=[...F1.map((K)=>`${K}/**`),...Y?.scanIgnore??[]],X=`${$}|${Z.join(",")}`,Q=P9.get(X);if(Q)return Q;let J=await $Z("**/.gitignore",{cwd:$,dot:!0,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:Z});J.sort((K,W)=>K.split("/").length-W.split("/").length);let q=[];for(let K of J){let W=JZ(K).replace(/\\/g,"/"),O=W==="."?"":W,H=(await QZ(S9($,K),"utf-8")).split(`
|
|
670
|
+
`);for(let _ of H){let z=_.trim();if(!z||z.startsWith("#"))continue;let F=z.startsWith("!"),L=(F?z.slice(1):z).trim();if(!L)continue;let N="";if(L.startsWith("/")){let A=L.slice(1).replace(/\\/g,"/");if(N=(O?O+"/":"")+A,q.push({type:F?"negate":"ignore",pattern:N}),L.endsWith("/")){let V=N+"**";q.push({type:F?"negate":"ignore",pattern:V});let E=N.replace(/\/$/,"");if(E!==N)q.push({type:F?"negate":"ignore",pattern:E})}}else{let A=L.replace(/\\/g,"/");if(A.includes("/")){if(N=(O?O+"/":"")+A,q.push({type:F?"negate":"ignore",pattern:N}),A.endsWith("/")){let V=N+"**";q.push({type:F?"negate":"ignore",pattern:V});let E=N.replace(/\/$/,"");if(E!==N)q.push({type:F?"negate":"ignore",pattern:E})}}else N=(O?O+"/**/":"**/")+A,q.push({type:F?"negate":"ignore",pattern:N})}}}let G=Y?.cacheTTL??30000;return P9.set(X,q,{ttl:G}),q}class p2{orderedRules=[];ignorePatterns=[];negatePatterns=[];constructor($={}){this.initialize($)}static async create($={}){let Y=new p2({...$,useGitignore:!1}),{cwd:Z=process.cwd(),useGitignore:X=!0,gitignoreScanMode:Q="root",customScanIgnore:J=[],cacheTTL:q}=$;if(X&&Q==="recursive"){let G=await GZ(Z,{scanIgnore:J,cacheTTL:q});for(let K of G)if(Y.orderedRules.push({type:K.type,matcher:t$(K.pattern,{dot:!0})}),K.type==="ignore")Y.ignorePatterns.push(K.pattern);else Y.negatePatterns.push(K.pattern)}return Y}initialize($){let{cwd:Y=process.cwd(),useGitignore:Z=!0,useDefaults:X=!0,customPatterns:Q=[]}=$,J=[],q=[];if(X){let G=[...F1.map((K)=>`${K}/**`),...F1,...Q4];J.push(...G);for(let K of G)this.orderedRules.push({type:"ignore",matcher:t$(K,{dot:!0})})}if(Z){let G=S9(Y,".gitignore"),{patterns:K,negatePatterns:W}=qZ(G);for(let O of K)this.orderedRules.push({type:"ignore",matcher:t$(O,{dot:!0})}),J.push(O);for(let O of W)this.orderedRules.push({type:"negate",matcher:t$(O,{dot:!0})}),q.push(O)}J.push(...Q);for(let G of Q)this.orderedRules.push({type:"ignore",matcher:t$(G,{dot:!0})});this.ignorePatterns=J,this.negatePatterns=q}shouldIgnore($){let Y=$.replace(/\\/g,"/"),Z=void 0;for(let X of this.orderedRules)if(X.matcher(Y))Z=X.type==="ignore";return Z===!0}shouldIgnoreDirectory($){let Y=$.replace(/\\/g,"/");return this.shouldIgnore(Y)||this.shouldIgnore(`${Y}/`)}filter($){return $.filter((Y)=>!this.shouldIgnore(Y))}getIgnorePatterns(){return this.ignorePatterns}getNegatePatterns(){return this.negatePatterns}}function J4($){let Y=Error($);return Y.name="AbortError",Y}var q4=n({name:"Glob",displayName:"File Pattern Match",kind:"readonly",schema:g2.object({pattern:G0.glob({description:"Glob pattern string (supports *, ?, ** wildcards)"}),path:g2.string().optional().describe("Search path (optional, defaults to cwd)"),max_results:G0.positiveInt({description:"Maximum number of results"}).max(1000,"At most 1000 results can be returned").default(100),include_directories:g2.boolean().default(!1).describe("Include directories in results"),case_sensitive:g2.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($,Y){let{pattern:Z,path:X=process.cwd(),max_results:Q,include_directories:J,case_sensitive:q}=$,{updateOutput:G}=Y,K=Y.signal??new AbortController().signal;try{G?.(`Searching in ${X} for pattern "${Z}"...`);let W=OZ(X);try{if(!(await WZ(W)).isDirectory())return{success:!1,llmContent:`Search path must be a directory: ${W}`,displayContent:`❌ 搜索路径必须是目录: ${W}`,error:{type:"validation_error",message:"搜索路径必须是目录"}}}catch(L){if(L.code==="ENOENT")return{success:!1,llmContent:`Search path does not exist: ${W}`,displayContent:`❌ 搜索路径不存在: ${W}`,error:{type:"execution_error",message:"搜索路径不存在"}};throw L}K.throwIfAborted();let O=await p2.create({cwd:W,useGitignore:!0,useDefaults:!0,gitignoreScanMode:"recursive",customScanIgnore:[],cacheTTL:30000}),{matches:U,wasTruncated:H}=await HZ(W,Z,{maxResults:Q,includeDirectories:J,caseSensitive:q,signal:K},O),_=_Z(U),z={search_path:W,pattern:Z,total_matches:U.length,returned_matches:U.length,max_results:Q,include_directories:J,case_sensitive:q,truncated:H},F=FZ(z),w;if(_.length>0)w=`${H?`Found at least ${_.length} file(s) matching "${Z}" (truncated)`:`Found ${_.length} file(s) matching "${Z}"`}:
|
|
671
671
|
|
|
672
|
-
`+_.map((
|
|
672
|
+
`+_.map((N)=>`- ${N.relative_path}`).join(`
|
|
673
673
|
`)+`
|
|
674
674
|
|
|
675
|
-
Use the relative_path values above for Read/Edit operations.`;else
|
|
676
|
-
\uD83D\uDCCB 显示前 ${Q} 个结果`;else
|
|
677
|
-
`).forEach((U,H)=>{if(J.test(U))Q.push({file_path:
|
|
678
|
-
`),X=[];switch(Y){case"files_with_matches":return Z.map((Q)=>({file_path:Q.trim()}));case"count":return Z.map((Q)=>{let[J,
|
|
679
|
-
\uD83D\uDD27 使用策略: ${J}`;switch(X){case"files_with_matches":
|
|
680
|
-
\uD83D\uDCC1 找到 ${Q} 个包含匹配内容的文件`;break;case"count":
|
|
681
|
-
\uD83D\uDD22 统计了 ${Q} 个文件的匹配数量`;break;case"content":
|
|
682
|
-
\uD83D\uDCDD 找到 ${Q} 个匹配行`;break}return
|
|
683
|
-
[error] ${J.message}`}),this.processes.set(Y,Q),Q}consumeOutput($){let Y=this.processes.get($);if(!Y)return;let Z={id:Y.id,command:Y.command,status:Y.status,stdout:Y.pendingStdout,stderr:Y.pendingStderr,exitCode:Y.exitCode,signal:Y.signal,pid:Y.pid,startedAt:Y.startTime,endedAt:Y.endTime,errorMessage:Y.errorMessage};return Y.pendingStdout="",Y.pendingStderr="",Z}getProcess($){return this.processes.get($)}kill($){let Y=this.processes.get($);if(!Y)return;if(Y.status!=="running"||!Y.process)return{success:!1,alreadyExited:!0,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal};if(!Y.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal};return Y.status="killed",Y.endTime=Date.now(),Y.process=void 0,{success:!0,alreadyExited:!1,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal}}}import{spawn as
|
|
675
|
+
Use the relative_path values above for Read/Edit operations.`;else w=`No files found matching "${Z}"`;return{success:!0,llmContent:w,displayContent:F,metadata:{...z,matches:_}}}catch(W){if(W.name==="AbortError")return{success:!1,llmContent:"File search aborted",displayContent:"⚠️ 文件搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${W.message}`,displayContent:`❌ 搜索失败: ${W.message}`,error:{type:"execution_error",message:W.message,details:W}}}},version:"2.0.0",category:"搜索工具",tags:["file","search","glob","pattern","wildcard"],extractSignatureContent:($)=>$.pattern,abstractPermissionRule:()=>"*"});async function HZ($,Y,Z,X){let Q=X.getIgnorePatterns(),J=[],q=!1;return await new Promise((G,K)=>{if(Z.signal.aborted){K(J4("文件搜索被用户中止"));return}let W=KZ.stream(Y,{cwd:$,dot:!0,followSymbolicLinks:!1,unique:!0,caseSensitiveMatch:Z.caseSensitive,objectMode:!0,stats:!0,onlyFiles:!Z.includeDirectories,ignore:Q}),O=!1,U=null,H=()=>{if(U){if(Z.signal.removeEventListener)Z.signal.removeEventListener("abort",U);else if("onabort"in Z.signal)Z.signal.onabort=null;U=null}},_=()=>{if(!O)O=!0,q=!0,W.destroy(),H(),G({matches:J,wasTruncated:q})},z=(F)=>{if(Z.signal.aborted){if(!O)O=!0,W.destroy(J4("文件搜索被用户中止"));return}if(J.length>=Z.maxResults){_();return}let w=F.path.replace(/\\/g,"/"),L=UZ($,w);if(X.shouldIgnore(w))return;let N=F.stats?F.stats.isDirectory():!1;if(N&&X.shouldIgnoreDirectory(w))return;let A=F.stats&&F.stats.isFile()?F.stats.size:void 0,V=F.stats?F.stats.mtime.toISOString():void 0;if(J.push({path:L,relative_path:w,is_directory:N,size:A,modified:V}),J.length>=Z.maxResults)_()};if(W.on("data",z),U=()=>{if(!O)O=!0,H(),W.destroy(J4("文件搜索被用户中止"))},Z.signal.addEventListener)Z.signal.addEventListener("abort",U);else if("onabort"in Z.signal)Z.signal.onabort=U;W.once("error",(F)=>{if(!O)O=!0,H(),K(F)}),W.once("end",()=>{if(!O)O=!0,H(),G({matches:J,wasTruncated:q})})})}function _Z($){return $.sort((Y,Z)=>{if(Y.is_directory!==Z.is_directory)return Y.is_directory?1:-1;if(Y.modified&&Z.modified)return new Date(Z.modified).getTime()-new Date(Y.modified).getTime();return Y.relative_path.localeCompare(Z.relative_path)})}function FZ($){let{search_path:Y,pattern:Z,total_matches:X,returned_matches:Q,truncated:J}=$,q;if(J)q=`✅ 在 ${Y} 中找到至少 ${X} 个匹配 "${Z}" 的文件(已截断)`,q+=`
|
|
676
|
+
\uD83D\uDCCB 显示前 ${Q} 个结果`;else q=`✅ 在 ${Y} 中找到 ${X} 个匹配 "${Z}" 的文件`;return q}import{execSync as G4,spawn as K4}from"child_process";import{existsSync as m2}from"fs";import{readdir as zZ,readFile as NZ}from"fs/promises";import{join as T9,relative as BZ}from"path";import LZ from"picomatch";import{z as P1}from"zod";function wZ(){let{platform:$,arch:Y}=process,Z={"darwin-arm64":"darwin-arm64/rg","darwin-x64":"darwin-x64/rg","linux-arm64":"linux-arm64/rg","linux-x64":"linux-x64/rg","win32-x64":"win32-x64/rg.exe"},X=`${$}-${Y}`,Q=Z[X];if(!Q)return null;let J=T9(process.cwd(),"vendor","ripgrep",Q);if(m2(J))return J;try{let q=new URL("../../../../vendor/ripgrep/"+Q,import.meta.url).pathname;if(m2(q))return q}catch{}return null}function C9(){try{let Y=process.platform==="win32"?"where rg":"command -v rg 2>/dev/null || which rg 2>/dev/null",Z=G4(Y,{encoding:"utf8",stdio:["pipe","pipe","ignore"]}).split(/\r?\n/)[0].trim();if(Z)return Z}catch{}let $=wZ();if($&&m2($))return $;try{let Y=A0("@vscode/ripgrep");if(Y?.rgPath&&m2(Y.rgPath))return Y.rgPath}catch{}return null}async function AZ($){try{return G4("git rev-parse --git-dir",{cwd:$,stdio:"ignore"}),!0}catch{return!1}}function RZ(){try{return G4("grep --version",{stdio:"ignore"}),!0}catch{return!1}}async function bZ($,Y,Z,X){let Q=C9();if(!Q)throw Error("ripgrep not available");return new Promise((J,q)=>{let G=K4(Q,$,{stdio:["pipe","pipe","pipe"]}),K="",W="";G.stdout.on("data",(U)=>{K+=U.toString()}),G.stderr.on("data",(U)=>{W+=U.toString()}),G.on("close",(U)=>{J({stdout:K,stderr:W,exitCode:U||0})}),G.on("error",(U)=>{q(U)});let O=()=>{G.kill("SIGTERM"),q(Error("搜索被用户中止"))};Z.addEventListener("abort",O),G.on("close",()=>{Z.removeEventListener("abort",O)})})}async function VZ($,Y,Z,X){let Q=["grep","-n"];if(Z.caseInsensitive)Q.push("-i");if(Z.contextLines!==void 0)Q.push(`-C${Z.contextLines}`);if(Q.push("-e",$),Z.glob)Q.push("--",Z.glob);return new Promise((J,q)=>{let G=K4("git",Q,{cwd:Y,stdio:["pipe","pipe","pipe"]}),K="",W="";G.stdout.on("data",(U)=>{K+=U.toString()}),G.stderr.on("data",(U)=>{W+=U.toString()}),G.on("close",(U)=>{J({stdout:K,stderr:W,exitCode:U||0})}),G.on("error",(U)=>{q(U)});let O=()=>{G.kill("SIGTERM"),q(Error("搜索被用户中止"))};X.addEventListener("abort",O),G.on("close",()=>{X.removeEventListener("abort",O)})})}async function DZ($,Y,Z,X){let Q=["-rn"];if(Z.caseInsensitive)Q.push("-i");if(Z.contextLines!==void 0)Q.push(`-C${Z.contextLines}`);for(let J of F1)Q.push("--exclude-dir="+J.replace(/^\./,""));return Q.push("-e",$,Y),new Promise((J,q)=>{let G=K4("grep",Q,{stdio:["pipe","pipe","pipe"]}),K="",W="";G.stdout.on("data",(U)=>{K+=U.toString()}),G.stderr.on("data",(U)=>{W+=U.toString()}),G.on("close",(U)=>{J({stdout:K,stderr:W,exitCode:U||0})}),G.on("error",(U)=>{q(U)});let O=()=>{G.kill("SIGTERM"),q(Error("搜索被用户中止"))};X.addEventListener("abort",O),G.on("close",()=>{X.removeEventListener("abort",O)})})}async function IZ($,Y,Z,X){let Q=[],J=new RegExp($,Z.caseInsensitive?"gi":"g"),q=await kZ(Y,X),G=0;for(let K of q){if(X.throwIfAborted(),f9(K))continue;if(Z.glob&&!vZ(K,Z.glob))continue;try{(await NZ(K,"utf-8")).split(`
|
|
677
|
+
`).forEach((U,H)=>{if(J.test(U))Q.push({file_path:BZ(Y,K),line_number:H+1,content:U})}),G++}catch(W){continue}}return{matches:Q,totalFiles:G}}async function kZ($,Y){let Z=[];async function X(Q){Y.throwIfAborted();try{let J=await zZ(Q,{withFileTypes:!0});for(let q of J){Y.throwIfAborted();let G=T9(Q,q.name);if(q.isDirectory()){if(!f9(G))await X(G)}else if(q.isFile())Z.push(G)}}catch(J){}}return await X($),Z}function f9($){for(let Y of F1)if($.includes(Y))return!0;return!1}function vZ($,Y){return LZ(Y)($)}function MZ($){let Y=[];if($.case_insensitive)Y.push("-i");if($.multiline)Y.push("-U","--multiline-dotall");switch($.output_mode){case"files_with_matches":Y.push("-l");break;case"count":Y.push("-c");break;case"content":if($.line_numbers)Y.push("-n");break}if($.context!==void 0&&$.output_mode==="content")Y.push("-C",$.context.toString());else{if($.context_before!==void 0&&$.output_mode==="content")Y.push("-B",$.context_before.toString());if($.context_after!==void 0&&$.output_mode==="content")Y.push("-A",$.context_after.toString())}if($.type)Y.push("--type",$.type);for(let Z of F1)Y.push("--glob",`!${Z}/**`);if($.glob)Y.push("--glob",$.glob);if($.head_limit!==void 0){let Z=($.offset??0)+$.head_limit;Y.push("-m",Z.toString())}return Y.push($.pattern),Y.push($.path),Y}function yZ($,Y){if(!$.trim())return[];let Z=$.trim().split(`
|
|
678
|
+
`),X=[];switch(Y){case"files_with_matches":return Z.map((Q)=>({file_path:Q.trim()}));case"count":return Z.map((Q)=>{let[J,q]=Q.split(":");return{file_path:J,count:parseInt(q,10)}});case"content":for(let Q of Z){let J=EZ(Q);if(J)X.push(J)}return X;default:return[]}}function EZ($){let Y=$.indexOf(":");if(Y===-1)return null;let Z=$.substring(0,Y),X=$.substring(Y+1),Q=X.indexOf(":");if(Q!==-1&&/^\d+$/.test(X.substring(0,Q))){let J=parseInt(X.substring(0,Q),10),q=X.substring(Q+1);return{file_path:Z,line_number:J,content:q}}else return{file_path:Z,content:X}}function jZ($){let{search_pattern:Y,search_path:Z,output_mode:X,total_matches:Q,strategy:J}=$,q=`✅ 在 ${Z} 中搜索 "${Y}"`;if(J)q+=`
|
|
679
|
+
\uD83D\uDD27 使用策略: ${J}`;switch(X){case"files_with_matches":q+=`
|
|
680
|
+
\uD83D\uDCC1 找到 ${Q} 个包含匹配内容的文件`;break;case"count":q+=`
|
|
681
|
+
\uD83D\uDD22 统计了 ${Q} 个文件的匹配数量`;break;case"content":q+=`
|
|
682
|
+
\uD83D\uDCDD 找到 ${Q} 个匹配行`;break}return q}var W4=n({name:"Grep",displayName:"内容搜索",kind:"readonly",schema:P1.object({pattern:G0.pattern({description:"The regular expression pattern to search for in file contents"}),path:P1.string().optional().describe("File or directory to search in (rg PATH). Defaults to current working directory"),glob:P1.string().optional().describe('Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}") - maps to rg --glob'),type:P1.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:P1.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":P1.boolean().optional().describe("Case insensitive search (rg -i)"),"-n":P1.boolean().default(!0).describe('Show line numbers in output (rg -n). Requires output_mode: "content", ignored otherwise. Defaults to true'),"-B":G0.nonNegativeInt().optional().describe('Number of lines to show before each match (rg -B). Requires output_mode: "content", ignored otherwise'),"-A":G0.nonNegativeInt().optional().describe('Number of lines to show after each match (rg -A). Requires output_mode: "content", ignored otherwise'),"-C":G0.nonNegativeInt().optional().describe('Number of lines to show before and after each match (rg -C). Requires output_mode: "content", ignored otherwise'),head_limit:G0.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:G0.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:P1.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($,Y){let{pattern:Z,path:X=process.cwd(),glob:Q,type:J,output_mode:q,"-i":G,"-n":K=!0,"-B":W,"-A":O,"-C":U,head_limit:H,offset:_,multiline:z}=$,{updateOutput:F}=Y,w=Y.signal??new AbortController().signal;try{F?.(`使用智能搜索策略查找模式 "${Z}"...`);let L=null,N="ripgrep",A=[],V=C9();if(V)try{F?.(`\uD83D\uDE80 使用 ripgrep (${V})`);let D=MZ({pattern:Z,path:X,glob:Q,type:J,output_mode:q,case_insensitive:G??!1,line_numbers:K,context_before:W,context_after:O,context:U,head_limit:H,offset:_,multiline:z??!1});L=await bZ(D,q,w,F),N="ripgrep"}catch(D){F?.("⚠️ ripgrep 失败,尝试降级策略..."),L=null}if(!L&&await AZ(X))try{F?.("\uD83D\uDCE6 使用 git grep"),L=await VZ(Z,X,{caseInsensitive:G??!1,glob:Q,contextLines:U},w),N="git-grep"}catch(D){F?.("⚠️ git grep 失败,继续尝试其他策略..."),L=null}if(!L&&RZ())try{F?.("\uD83D\uDD27 使用系统 grep"),L=await DZ(Z,X,{caseInsensitive:G??!1,contextLines:U},w),N="system-grep"}catch(D){F?.("⚠️ 系统 grep 失败,使用纯 JavaScript 实现..."),L=null}if(!L)F?.("\uD83D\uDCA1 使用纯 JavaScript 搜索实现"),A=(await IZ(Z,X,{caseInsensitive:G??!1,glob:Q,multiline:z??!1},w)).matches,N="fallback",L={stdout:"",stderr:"",exitCode:0};else A=yZ(L.stdout,q);let E=A.length;if(_!==void 0&&_>0)A=A.slice(_);if(H!==void 0&&A.length>H)A=A.slice(0,H);let R={search_pattern:Z,search_path:X,output_mode:q,case_insensitive:G??!1,total_matches:A.length,original_total:E,offset:_,head_limit:H,strategy:N,exit_code:L?.exitCode};if(L&&L.exitCode!==0&&L.stderr)return{success:!1,llmContent:`Search execution failed: ${L.stderr}`,displayContent:`❌ 搜索执行失败: ${L.stderr}`,error:{type:"execution_error",message:L.stderr}};let B=jZ(R);return{success:!0,llmContent:A,displayContent:B,metadata:R}}catch(L){if(L.name==="AbortError")return{success:!1,llmContent:"Search aborted",displayContent:"⚠️ 搜索被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Search failed: ${L.message}`,displayContent:`❌ 搜索失败: ${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 PZ}from"child_process";import{randomUUID as SZ}from"crypto";class C0{static instance=null;processes=new Map;static getInstance(){if(!C0.instance)C0.instance=new C0;return C0.instance}startBackgroundProcess($){let Y=`bash_${SZ()}`,Z={};for(let[J,q]of Object.entries({...process.env,...$.env,BLADE_CLI:"1"}))if(q!==void 0)Z[J]=q;let X=PZ("bash",["-c",$.command],{cwd:$.cwd||process.cwd(),env:Z,stdio:["ignore","pipe","pipe"]}),Q={id:Y,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:X,pid:X.pid,status:"running",startTime:Date.now(),pendingStdout:"",pendingStderr:""};return X.stdout?.setEncoding("utf8"),X.stderr?.setEncoding("utf8"),X.stdout?.on("data",(J)=>{Q.pendingStdout+=J.toString()}),X.stderr?.on("data",(J)=>{Q.pendingStderr+=J.toString()}),X.on("close",(J,q)=>{Q.status=Q.status==="killed"?"killed":"exited",Q.exitCode=J,Q.signal=q,Q.endTime=Date.now(),Q.process=void 0}),X.on("error",(J)=>{Q.status="error",Q.errorMessage=J.message,Q.endTime=Date.now(),Q.process=void 0,Q.pendingStderr+=`
|
|
683
|
+
[error] ${J.message}`}),this.processes.set(Y,Q),Q}consumeOutput($){let Y=this.processes.get($);if(!Y)return;let Z={id:Y.id,command:Y.command,status:Y.status,stdout:Y.pendingStdout,stderr:Y.pendingStderr,exitCode:Y.exitCode,signal:Y.signal,pid:Y.pid,startedAt:Y.startTime,endedAt:Y.endTime,errorMessage:Y.errorMessage};return Y.pendingStdout="",Y.pendingStderr="",Z}getProcess($){return this.processes.get($)}kill($){let Y=this.processes.get($);if(!Y)return;if(Y.status!=="running"||!Y.process)return{success:!1,alreadyExited:!0,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal};if(!Y.process.kill("SIGTERM"))return{success:!1,alreadyExited:!1,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal};return Y.status="killed",Y.endTime=Date.now(),Y.process=void 0,{success:!0,alreadyExited:!1,status:Y.status,pid:Y.pid,exitCode:Y.exitCode,signal:Y.signal}}killAll(){for(let[$,Y]of this.processes)if(Y.status==="running"&&Y.process)try{Y.process.kill("SIGTERM"),Y.status="killed",Y.endTime=Date.now(),Y.process=void 0}catch{}this.processes.clear()}}import{spawn as TZ}from"child_process";import{randomUUID as CZ}from"crypto";import{z as U4}from"zod";var O4=n({name:"Bash",displayName:"Bash Command",kind:"execute",schema:U4.object({command:G0.command({description:"Bash command to execute"}),timeout:G0.timeout(1000,300000,30000),cwd:U4.string().optional().describe("Working directory (optional; applies only to this command). To persist, use cd"),env:G0.environment(),run_in_background:U4.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.
|
|
684
684
|
|
|
685
685
|
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.
|
|
686
686
|
|
|
@@ -696,21 +696,21 @@ Before executing commands:
|
|
|
696
696
|
* cd "/Users/name/My Documents" (correct)
|
|
697
697
|
* cd /Users/name/My Documents (incorrect - will fail)
|
|
698
698
|
* python "/path/with spaces/script.py" (correct)
|
|
699
|
-
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the BashOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Y){let{command:Z,timeout:X=30000,cwd:Q,env:J,run_in_background:
|
|
699
|
+
* python /path/with spaces/script.py (incorrect - will fail)`,usageNotes:["The command argument is required","You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30000ms (30 seconds)","It is very helpful if you write a clear, concise description of what this command does in 5-10 words","If the output exceeds 30000 characters, output will be truncated before being returned to you",'You can use the run_in_background parameter to run the command in the background, which allows you to continue working while the command runs. You can monitor the output using the BashOutput tool. You do not need to use "&" at the end of the command when using this parameter',"Avoid using Bash with the find, grep, cat, head, tail, sed, awk, or echo commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:"," - File search: Use Glob (NOT find or ls)"," - Content search: Use Grep (NOT grep or rg)"," - Read files: Use Read (NOT cat/head/tail)"," - Edit files: Use Edit (NOT sed/awk)"," - Write files: Use Write (NOT echo >/cat <<EOF)"," - Communication: Output text directly (NOT echo/printf)","When issuing multiple commands:",' - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel',' - If the commands depend on each other and must run sequentially, use a single Bash call with "&&" to chain them together (e.g., git add . && git commit -m "message" && git push). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead',` - Use ";" only when you need to run commands sequentially but don't care if earlier commands fail`," - DO NOT use newlines to separate commands (newlines are ok in quoted strings)","Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd. You may use cd if the User explicitly requests it"," Good example: pytest /foo/bar/tests"," Bad example: cd /foo/bar && pytest tests"],examples:[{description:"Run a simple command",params:{command:"ls -la",description:"List files in current directory"}},{description:"Temporarily change working directory (this command only)",params:{command:"npm install",cwd:"/path/to/project",description:"Install package dependencies"}},{description:"Persistently change working directory",params:{command:"cd /path/to/project && npm install",description:"Change directory and install dependencies"}},{description:"Run a long-running command in background",params:{command:"npm run dev",run_in_background:!0,description:"Start development server in background"}},{description:"Run multiple independent commands in parallel",params:{command:"git status",description:"Show working tree status"}}],important:["Committing changes with git:"," - Only create commits when requested by the user. If unclear, ask first"," - Git Safety Protocol:"," * NEVER update the git config"," * NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them"," * NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it"," * NEVER run force push to main/master, warn the user if they request it"," * Avoid git commit --amend. ONLY use --amend when either (1) user explicitly requested amend OR (2) adding edits from pre-commit hook",' * Before amending: ALWAYS check authorship (git log -1 --format="%an %ae")'," * NEVER commit changes unless the user explicitly asks you to"," - When creating commits:"," 1. Run git status, git diff, and git log in parallel to understand changes",' 2. Analyze staged changes and draft a concise commit message (1-2 sentences) focusing on "why" rather than "what"'," 3. Add relevant untracked files, create the commit, and run git status to verify"," 4. Always pass commit message via HEREDOC format"," - DO NOT push to remote repository unless explicitly requested"," - NEVER use git commands with the -i flag (no interactive input supported)"," - If no changes to commit, do not create an empty commit","Creating pull requests:"," - Use the gh command for ALL GitHub-related tasks"," - When creating a PR:"," 1. Run git status, git diff, and git log in parallel to understand branch changes"," 2. Analyze all commits (not just the latest) and draft a PR summary"," 3. Create new branch if needed, push with -u flag, and create PR using gh pr create with HEREDOC body format"," - Return the PR URL when done","Other important notes:"," - Dangerous commands (rm -rf, sudo, etc.) require user confirmation"," - Background commands require manual termination using KillShell"," - NEVER use find, grep, cat, sed, etc. — use dedicated tools instead"]},async execute($,Y){let{command:Z,timeout:X=30000,cwd:Q,env:J,run_in_background:q=!1}=$,{updateOutput:G}=Y,K=Y.signal??new AbortController().signal;try{if(G?.(`Executing Bash command: ${Z}`),q)return fZ(Z,Q,J);else return hZ(Z,Q,J,X,K,G)}catch(W){let O=W;if(O.name==="AbortError")return{success:!1,llmContent:"Command execution aborted",displayContent:"⚠️ 命令执行被用户中止",error:{type:"execution_error",message:"Operation aborted"}};return{success:!1,llmContent:`Command execution failed: ${O.message}`,displayContent:`❌ 命令执行失败: ${O.message}`,error:{type:"execution_error",message:O.message,details:O}}}},version:"2.0.0",category:"命令工具",tags:["bash","shell","non-interactive","event-driven"],extractSignatureContent:($)=>{return $.command.trim()},abstractPermissionRule:($)=>{let Z=$.command.trim().split(/\s+/);if(Z.length===1)return Z[0];if(["run","exec","test","start","build","dev"].includes(Z[1])){if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}if(Z.length===2)return`${Z[0]} ${Z[1]}`;return`${Z[0]} ${Z[1]} *`}});function fZ($,Y,Z){let Q=C0.getInstance().startBackgroundProcess({command:$,sessionId:CZ(),cwd:Y||process.cwd(),env:Z}),q=`后台启动命令: ${$.length>30?`${$.substring(0,30)}...`:$}`,G={command:$,background:!0,pid:Q.pid,bash_id:Q.id,shell_id:Q.id,message:"命令已在后台启动",summary:q},K=`✅ 命令已在后台启动
|
|
700
700
|
`+`\uD83C\uDD94 进程 ID: ${Q.pid}
|
|
701
701
|
`+`\uD83D\uDCA1 Bash ID: ${Q.id}
|
|
702
|
-
`+"⚠️ 使用 BashOutput/KillShell 管理后台进程";return{success:!0,llmContent:{command:$,background:!0,pid:Q.pid,bash_id:Q.id,shell_id:Q.id},displayContent:K,metadata:
|
|
702
|
+
`+"⚠️ 使用 BashOutput/KillShell 管理后台进程";return{success:!0,llmContent:{command:$,background:!0,pid:Q.pid,bash_id:Q.id,shell_id:Q.id},displayContent:K,metadata:G}}async function hZ($,Y,Z,X,Q,J){return new Promise((q)=>{let G=Date.now(),K="",W="",O=!1,U=TZ("bash",["-c",$],{cwd:Y||process.cwd(),env:{...process.env,...Z,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]});U.stdout.on("data",(z)=>{K+=z.toString()}),U.stderr.on("data",(z)=>{W+=z.toString()});let H=setTimeout(()=>{O=!0,U.kill("SIGTERM"),setTimeout(()=>{if(!U.killed)U.kill("SIGKILL")},1000)},X),_=()=>{U.kill("SIGTERM"),clearTimeout(H)};if(Q.addEventListener)Q.addEventListener("abort",_);else if("onabort"in Q)Q.onabort=_;U.on("close",(z,F)=>{if(clearTimeout(H),Q.removeEventListener)Q.removeEventListener("abort",_);else if("onabort"in Q)Q.onabort=null;let w=Date.now()-G;if(O){q({success:!1,llmContent:`Command execution timed out (${X}ms)`,displayContent:`⏱️ 命令执行超时 (${X}ms)
|
|
703
703
|
输出: ${K}
|
|
704
|
-
错误: ${W}`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K,stderr:W,execution_time:
|
|
704
|
+
错误: ${W}`,error:{type:"timeout_error",message:"命令执行超时"},metadata:{command:$,timeout:!0,stdout:K,stderr:W,execution_time:w}});return}if(Q.aborted){q({success:!1,llmContent:"Command execution aborted by user",displayContent:`⚠️ 命令执行被用户中止
|
|
705
705
|
输出: ${K}
|
|
706
|
-
错误: ${W}`,error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:K,stderr:W,execution_time:
|
|
707
|
-
⏱️ 执行时间: ${Q}ms`,
|
|
708
|
-
\uD83D\uDCCA 退出码: ${J??"N/A"}`,G
|
|
709
|
-
⚡ 信号: ${
|
|
706
|
+
错误: ${W}`,error:{type:"execution_error",message:"操作被中止"},metadata:{command:$,aborted:!0,stdout:K,stderr:W,execution_time:w}});return}let L=$.length>30?`${$.substring(0,30)}...`:$,N=z===0?`执行命令成功 (${w}ms): ${L}`:`执行命令完成 (退出码 ${z}, ${w}ms): ${L}`,A={command:$,execution_time:w,exit_code:z,signal:F,stdout_length:K.length,stderr_length:W.length,has_stderr:W.length>0,summary:N},V=xZ({stdout:K,stderr:W,command:$,execution_time:w,exit_code:z,signal:F});q({success:!0,llmContent:{stdout:K.trim(),stderr:W.trim(),execution_time:w,exit_code:z,signal:F},displayContent:V,metadata:A})}),U.on("error",(z)=>{if(clearTimeout(H),Q.removeEventListener)Q.removeEventListener("abort",_);else if("onabort"in Q)Q.onabort=null;q({success:!1,llmContent:`Command execution failed: ${z.message}`,displayContent:`❌ 命令执行失败: ${z.message}`,error:{type:"execution_error",message:z.message,details:z}})})})}function xZ($){let{stdout:Y,stderr:Z,command:X,execution_time:Q,exit_code:J,signal:q}=$,G=`✅ Bash 命令执行完成: ${X}`;if(G+=`
|
|
707
|
+
⏱️ 执行时间: ${Q}ms`,G+=`
|
|
708
|
+
\uD83D\uDCCA 退出码: ${J??"N/A"}`,q)G+=`
|
|
709
|
+
⚡ 信号: ${q}`;if(Y&&Y.trim())G+=`
|
|
710
710
|
\uD83D\uDCE4 输出:
|
|
711
|
-
${Y.trim()}`;if(Z&&Z.trim())
|
|
711
|
+
${Y.trim()}`;if(Z&&Z.trim())G+=`
|
|
712
712
|
⚠️ 错误输出:
|
|
713
|
-
${Z.trim()}`;return
|
|
713
|
+
${Z.trim()}`;return G}import{z as H4}from"zod";var _4=n({name:"BashOutput",displayName:"后台命令输出",kind:"readonly",schema:H4.object({bash_id:H4.string().min(1).describe("Background bash session ID"),filter:H4.string().optional().describe("Optional regex filter: only return matching lines; non-matching lines are discarded")}),description:{short:"Retrieves output from a running or completed background bash shell",long:`
|
|
714
714
|
- Retrieves output from a running or completed background bash shell
|
|
715
715
|
- Takes a shell_id parameter identifying the shell
|
|
716
716
|
- Always returns only new output since the last check
|
|
@@ -718,26 +718,26 @@ ${Z.trim()}`;return q}import{z as W4}from"zod";var U4=a({name:"BashOutput",displ
|
|
|
718
718
|
- Supports optional regex filtering to show only lines matching a pattern
|
|
719
719
|
- Use this tool when you need to monitor or check the output of a long-running shell
|
|
720
720
|
- Shell IDs can be found using the /tasks command
|
|
721
|
-
`},async execute($,Y){let Z=
|
|
721
|
+
`},async execute($,Y){let Z=C0.getInstance(),X;if($.filter)try{X=new RegExp($.filter)}catch(W){return{success:!1,llmContent:`Invalid regular expression: ${$.filter}
|
|
722
722
|
|
|
723
723
|
\uD83D\uDCA1 Output was not consumed; you can retry`,displayContent:`❌ 无效的正则表达式: ${$.filter}
|
|
724
724
|
|
|
725
|
-
\uD83D\uDCA1 输出未被消费,可重新尝试`,error:{type:"validation_error",message:W.message}}}let Q=Z.consumeOutput($.bash_id);if(!Q)return{success:!1,llmContent:`Bash session not found: ${$.bash_id}`,displayContent:`❌ 未找到 Bash 会话: ${$.bash_id}`,error:{type:"execution_error",message:"Bash 会话不存在或已清理"}};let{stdoutLines:J,stderrLines:
|
|
725
|
+
\uD83D\uDCA1 输出未被消费,可重新尝试`,error:{type:"validation_error",message:W.message}}}let Q=Z.consumeOutput($.bash_id);if(!Q)return{success:!1,llmContent:`Bash session not found: ${$.bash_id}`,displayContent:`❌ 未找到 Bash 会话: ${$.bash_id}`,error:{type:"execution_error",message:"Bash 会话不存在或已清理"}};let{stdoutLines:J,stderrLines:q}=pZ(Q,X),G={bash_id:Q.id,status:Q.status,command:Q.command,pid:Q.pid,exit_code:Q.exitCode,signal:Q.signal,started_at:new Date(Q.startedAt).toISOString(),finished_at:Q.endedAt?new Date(Q.endedAt).toISOString():void 0,stdout:J,stderr:q},K=gZ(Q,J.length,q.length);return{success:!0,llmContent:G,displayContent:K,metadata:G}},version:"1.0.0",category:"命令工具",tags:["bash","shell","monitor"],extractSignatureContent:($)=>$.bash_id,abstractPermissionRule:()=>"*"});function pZ($,Y){let Z=h9($.stdout).filter((Q)=>{if(!Y)return!0;return Y.lastIndex=0,Y.test(Q)}),X=h9($.stderr).filter((Q)=>{if(!Y)return!0;return Y.lastIndex=0,Y.test(Q)});return{stdoutLines:Z,stderrLines:X}}function h9($){if(!$)return[];return $.replace(/\r\n/g,`
|
|
726
726
|
`).split(`
|
|
727
|
-
`)}function
|
|
727
|
+
`)}function gZ($,Y,Z){let Q=`${$.status==="running"?"⏳":$.status==="exited"?"✅":$.status==="killed"?"✂️":"⚠️"} BashOutput(${$.id}) - 状态: ${$.status}`;if(Q+=`
|
|
728
728
|
命令: ${$.command}`,$.pid)Q+=`
|
|
729
729
|
PID: ${$.pid}`;if($.exitCode!==void 0&&$.exitCode!==null)Q+=`
|
|
730
730
|
退出码: ${$.exitCode}`;if($.signal)Q+=`
|
|
731
731
|
信号: ${$.signal}`;if(Y===0&&Z===0)Q+=`
|
|
732
732
|
无新的输出`;else Q+=`
|
|
733
733
|
stdout 行数: ${Y}`,Q+=`
|
|
734
|
-
stderr 行数: ${Z}`;return Q}import{z as
|
|
734
|
+
stderr 行数: ${Z}`;return Q}import{z as x9}from"zod";var F4=n({name:"KillShell",displayName:"终止后台 Shell",kind:"execute",schema:x9.object({shell_id:x9.string().min(1).describe("Background Shell ID to terminate")}),description:{short:"Kills a running background bash shell by its ID",long:`
|
|
735
735
|
- Kills a running background bash shell by its ID
|
|
736
736
|
- Takes a shell_id parameter identifying the shell to kill
|
|
737
737
|
- Returns a success or failure status
|
|
738
738
|
- Use this tool when you need to terminate a long-running shell
|
|
739
739
|
- Shell IDs can be found using the /tasks command
|
|
740
|
-
`},async execute($,Y){let X=
|
|
740
|
+
`},async execute($,Y){let X=C0.getInstance().kill($.shell_id);if(!X)return{success:!1,llmContent:`Shell not found: ${$.shell_id}`,displayContent:`❌ 未找到 Shell: ${$.shell_id}`,error:{type:"execution_error",message:"Shell ID 不存在或已清理"}};if(!X.success&&!X.alreadyExited)return{success:!1,llmContent:`Failed to terminate Shell: ${$.shell_id}`,displayContent:`❌ 无法终止 Shell (${$.shell_id})`,error:{type:"execution_error",message:"发送终止信号失败"},metadata:X};let Q=X.alreadyExited?`Shell ${$.shell_id} 已经处于 ${X.status} 状态`:`已向 Shell ${$.shell_id} 发送终止信号`;return{success:!0,llmContent:{shell_id:$.shell_id,status:X.status,already_exited:X.alreadyExited,pid:X.pid,exit_code:X.exitCode,signal:X.signal},displayContent:X.alreadyExited?`ℹ️ ${Q}`:`✂️ ${Q}`,metadata:X}},version:"1.0.0",category:"命令工具",tags:["bash","shell","terminate"],extractSignatureContent:($)=>$.shell_id,abstractPermissionRule:()=>"*"});import{z as p9}from"zod";var z4=n({name:"Skill",displayName:"Skill",kind:"execute",schema:p9.object({skill:p9.string().describe('The skill name (no arguments). E.g., "pdf" or "xlsx"')}),description:{short:"Execute a skill within the main conversation",long:`Execute a skill within the main conversation
|
|
741
741
|
|
|
742
742
|
<skills_instructions>
|
|
743
743
|
When users ask you to perform tasks, check if any of the available skills below can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
|
@@ -760,7 +760,7 @@ Important:
|
|
|
760
760
|
<available_skills>
|
|
761
761
|
|
|
762
762
|
</available_skills>
|
|
763
|
-
`},async execute($,Y){let{skill:Z}=$;return{success:!1,llmContent:`Skill system not yet implemented. The skill "${Z}" could not be executed.`,displayContent:"Skill system not available",error:{type:"execution_error",message:"Skill handler not configured"}}}});import{z as
|
|
763
|
+
`},async execute($,Y){let{skill:Z}=$;return{success:!1,llmContent:`Skill system not yet implemented. The skill "${Z}" could not be executed.`,displayContent:"Skill system not available",error:{type:"execution_error",message:"Skill handler not configured"}}}});import{z as g9}from"zod";var N4=n({name:"SlashCommand",displayName:"Slash Command",kind:"execute",schema:g9.object({command:g9.string().describe('The slash command to execute with its arguments, e.g., "/review-pr 123"')}),description:{short:"Execute a slash command within the main conversation",long:`Execute a slash command within the main conversation
|
|
764
764
|
|
|
765
765
|
How slash commands work:
|
|
766
766
|
When you use this tool or when a user types a slash command, you will see <command-message>{name} is running...</command-message> followed by the expanded prompt. For example, if .claude/commands/foo.md contains "Print today's date", then /foo expands to that prompt in the next message.
|
|
@@ -778,14 +778,14 @@ Notes:
|
|
|
778
778
|
- When a user requests multiple slash commands, execute each one sequentially and check for <command-message>{name} is running...</command-message> to verify each has been processed
|
|
779
779
|
- Do not invoke a command that is already running. For example, if you see <command-message>foo is running...</command-message>, do NOT use this tool with "/foo" - process the expanded prompt in the following message
|
|
780
780
|
- Only custom slash commands with descriptions are listed in Available Commands. If a user's command is not listed, ask them to check the slash command file and consult the docs.
|
|
781
|
-
`},async execute($,Y){let{command:Z}=$;return{success:!1,llmContent:`Slash command system not yet implemented. The command "${Z}" could not be executed.`,displayContent:"Slash command system not available",error:{type:"execution_error",message:"Slash command handler not configured"}}}});import{z as
|
|
781
|
+
`},async execute($,Y){let{command:Z}=$;return{success:!1,llmContent:`Slash command system not yet implemented. The command "${Z}" could not be executed.`,displayContent:"Slash command system not available",error:{type:"execution_error",message:"Slash command handler not configured"}}}});import{z as u2}from"zod";class B4{config;constructor($){this.config=$}async execute($){let Y=Date.now();try{let Z=this.buildSystemPrompt($),X=await k0.create({systemPrompt:Z,toolWhitelist:this.config.tools}),Q=[{role:"user",content:$.prompt}],J="",q=0,G=0,K=await X.runAgenticLoop($.prompt,{messages:[],userId:"subagent",sessionId:$.parentSessionId||`subagent_${Date.now()}`,workspaceRoot:process.cwd(),permissionMode:$.permissionMode});if(K.success)J=K.finalMessage||"",q=K.metadata?.toolCallsCount||0,G=K.metadata?.tokensUsed||0;else throw Error(K.error?.message||"Subagent execution failed");let W=Date.now()-Y;return{success:!0,message:J,stats:{tokens:G,toolCalls:q,duration:W}}}catch(Z){let X=Date.now()-Y;return{success:!1,message:"",error:Z instanceof Error?Z.message:String(Z),stats:{duration:X}}}}buildSystemPrompt($){return this.config.systemPrompt||""}}import L4 from"node:fs";import mZ from"node:path";import uZ from"yaml";var dZ=Y0("Agent");class m9{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 subagent types and the tools they have access to:
|
|
782
782
|
${$.map((Z)=>{let X=`- ${Z.name}: ${Z.description}`;if(Z.tools&&Z.tools.length>0)X+=` (Tools: ${Z.tools.join(", ")})`;return X}).join(`
|
|
783
|
-
`)}`}loadFromDirectory($){if(!
|
|
783
|
+
`)}`}loadFromDirectory($){if(!L4.existsSync($))return;let Y=L4.readdirSync($);for(let Z of Y){if(!Z.endsWith(".md"))continue;let X=mZ.join($,Z);try{let Q=this.parseConfigFile(X);this.register(Q)}catch(Q){dZ.warn(`Failed to load subagent config from ${X}:`,Q)}}}parseConfigFile($){let Z=L4.readFileSync($,"utf-8").match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!Z)throw Error(`No YAML frontmatter found in ${$}`);let[,X,Q]=Z,J=uZ.parse(X);if(!J.name||!J.description)throw Error(`Missing required fields (name, description) in ${$}`);let q=Q.trim();return{name:J.name,description:J.description,systemPrompt:q,tools:J.tools,configPath:$}}loadFromStandardLocations(){let $=A0("node:os"),Y=A0("node:path"),Z=Y.join($.homedir(),".blade","agents");this.loadFromDirectory(Z);let X=Y.join(process.cwd(),".blade","agents");return this.loadFromDirectory(X),this.getAllNames().length}clear(){this.subagents.clear()}}var N0=new m9;function cZ(){let $=N0.getAllNames();if($.length===0)return["Explore"];return $}var w4=n({name:"Task",displayName:"Subagent Scheduler",kind:"readonly",isReadOnly:!0,schema:u2.object({subagent_type:u2.enum(cZ()).describe('Subagent type to use (e.g., "Explore", "Plan")'),description:u2.string().min(3).max(100).describe("Short task description (3-5 words)"),prompt:u2.string().min(10).describe("Detailed task instructions")}),description:{short:"Launch a specialized agent to handle complex, multi-step tasks autonomously",long:`
|
|
784
784
|
Launch a specialized agent to handle complex, multi-step tasks autonomously.
|
|
785
785
|
|
|
786
786
|
The Task tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.
|
|
787
787
|
|
|
788
|
-
${
|
|
788
|
+
${N0.getDescriptionsForPrompt()}
|
|
789
789
|
|
|
790
790
|
**How to use the Task tool:**
|
|
791
791
|
- Set subagent_type to ANY agent name from the list above (e.g., 'Explore', 'Plan', 'code-reviewer', etc.)
|
|
@@ -806,9 +806,9 @@ ${B0.getDescriptionsForPrompt()}
|
|
|
806
806
|
- 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
|
|
807
807
|
- 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.
|
|
808
808
|
- 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.
|
|
809
|
-
`.trim(),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($,Y){let{subagent_type:Z,description:X,prompt:Q}=$,{updateOutput:J}=Y;try{let
|
|
809
|
+
`.trim(),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($,Y){let{subagent_type:Z,description:X,prompt:Q}=$,{updateOutput:J}=Y;try{let q=N0.getAllNames();console.log(`[Task] subagentRegistry 状态: registered=${q.length}, names=[${q.join(", ")}], looking for="${Z}"`);let G=N0.getSubagent(Z);if(!G)return{success:!1,llmContent:`Unknown subagent type: ${Z}. Available types: ${q.join(", ")||"none"}`,displayContent:`❌ 未知的 subagent 类型: ${Z}
|
|
810
810
|
|
|
811
|
-
可用类型: ${
|
|
811
|
+
可用类型: ${q.join(", ")||"无"}`,error:{type:"execution_error",message:`Unknown subagent type: ${Z}`}};J?.(`\uD83D\uDE80 启动 ${Z} subagent: ${X}`);let K=new B4(G),W={prompt:Q,parentSessionId:Y.sessionId,permissionMode:Y.permissionMode};J?.("⚙️ 执行任务中...");let O=Date.now(),U=await K.execute(W),H=Date.now()-O;if(U.success){let _=U.message.length>1000?U.message.slice(0,1000)+`
|
|
812
812
|
...(截断)`:U.message;return{success:!0,llmContent:U.message,displayContent:`✅ Subagent 任务完成
|
|
813
813
|
|
|
814
814
|
`+`类型: ${Z}
|
|
@@ -823,11 +823,11 @@ ${_}`,metadata:{subagent_type:Z,description:X,duration:H,stats:U.stats}}}else re
|
|
|
823
823
|
`+`类型: ${Z}
|
|
824
824
|
`+`任务: ${X}
|
|
825
825
|
`+`耗时: ${H}ms
|
|
826
|
-
`+`错误: ${U.error}`,error:{type:"execution_error",message:U.error||"Unknown error"}}}catch(
|
|
826
|
+
`+`错误: ${U.error}`,error:{type:"execution_error",message:U.error||"Unknown error"}}}catch(q){let G=q;return{success:!1,llmContent:`Subagent execution error: ${G.message}`,displayContent:`❌ Subagent 执行异常
|
|
827
827
|
|
|
828
|
-
${
|
|
828
|
+
${G.message}
|
|
829
829
|
|
|
830
|
-
${
|
|
830
|
+
${G.stack||""}`,error:{type:"execution_error",message:G.message,details:q}}}},version:"4.0.0",category:"Subagent",tags:["task","subagent","delegation","explore","plan"],extractSignatureContent:($)=>`${$.subagent_type}:${$.description}`,abstractPermissionRule:()=>""});import{randomUUID as lZ}from"crypto";import*as L$ from"fs/promises";import*as d2 from"path";class S1{static instances=new Map;todos=[];filePath;loaded=!1;constructor($,Y){this.filePath=d2.join(Y,"todos",`${$}-agent-${$}.json`)}static getInstance($,Y){let Z=`${$}-${Y}`;if(!S1.instances.has(Z))S1.instances.set(Z,new S1($,Y));return S1.instances.get(Z)}validate($){if($.filter((Z)=>Z.status==="in_progress").length>1)return{valid:!1,error:"同时只能有一个任务处于 in_progress 状态"};return{valid:!0}}async updateTodos($){await this.ensureLoaded();let Y=new Date().toISOString(),Z=$.map((Q)=>{let J=Q,q=this.todos.find((G)=>G.id===J.id||G.content===Q.content);return{...Q,id:J.id||q?.id||lZ(),priority:Q.priority||q?.priority||"medium",createdAt:q?.createdAt||Y,startedAt:Q.status==="in_progress"&&!q?.startedAt?Y:q?.startedAt,completedAt:Q.status==="completed"&&!q?.completedAt?Y:q?.completedAt}}),X=this.validate(Z);if(!X.valid)throw Error(X.error);this.todos=Z,await this.saveTodos()}getSortedTodos(){let $={completed:0,in_progress:1,pending:2},Y={high:0,medium:1,low:2};return[...this.todos].sort((Z,X)=>{let Q=$[Z.status]-$[X.status];if(Q!==0)return Q;return Y[Z.priority]-Y[X.priority]})}getTodos(){return this.getSortedTodos()}async ensureLoaded(){if(!this.loaded)await this.loadTodos(),this.loaded=!0}async loadTodos(){try{let $=await L$.readFile(this.filePath,"utf-8");this.todos=JSON.parse($)}catch($){if($.code==="ENOENT")this.todos=[];else console.warn("加载 TODO 列表失败:",$),this.todos=[]}}async saveTodos(){try{await L$.mkdir(d2.dirname(this.filePath),{recursive:!0}),await L$.writeFile(this.filePath,JSON.stringify(this.todos,null,2),"utf-8")}catch($){throw console.error("保存 TODO 列表失败:",$),$}}}import{z as d9}from"zod";import{z as w$}from"zod";var u9=w$.object({id:w$.string().optional(),content:w$.string().min(1,"Content cannot be empty"),status:w$.enum(["pending","in_progress","completed"]),activeForm:w$.string().min(1,"ActiveForm cannot be empty"),priority:w$.enum(["high","medium","low"]).default("medium")});function A4($){let{sessionId:Y,configDir:Z}=$;return n({name:"TodoWrite",displayName:"Todo Write",kind:"readonly",schema:d9.object({todos:d9.array(u9).min(1,"At least one task is required")}),description:{short:"Use this tool to create and manage a structured task list for your current coding session",long:`Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
|
831
831
|
It also helps the user understand the progress of the task and overall progress of their requests.
|
|
832
832
|
|
|
833
833
|
## When to Use This Tool
|
|
@@ -888,9 +888,9 @@ NOTE that you should not use this tool if there is only one trivial task to do.
|
|
|
888
888
|
- activeForm: "Fixing authentication bug"
|
|
889
889
|
|
|
890
890
|
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.
|
|
891
|
-
`},async execute(X,Q){let{todos:J}=X,{updateOutput:
|
|
892
|
-
`);for(let Q of $){let J=Q.status==="completed"?"☑":"☐",
|
|
893
|
-
`)}import{z as
|
|
891
|
+
`},async execute(X,Q){let{todos:J}=X,{updateOutput:q}=Q;try{let G=Q.sessionId||Y,K=S1.getInstance(G,Z);q?.("Updating TODO list..."),await K.updateTodos(J);let W=K.getTodos(),O=iZ(W),U=rZ(W,O);return q?.(`✅ TODO list updated (${O.completed}/${O.total} completed)`),{success:!0,llmContent:{todos:W,stats:O},displayContent:U,metadata:{stats:O}}}catch(G){return{success:!1,llmContent:`Update failed: ${G.message}`,displayContent:`❌ 更新 TODO 列表失败: ${G.message}`,error:{type:"execution_error",message:G.message,details:G}}}},version:"1.0.0",category:"TODO tools",tags:["todo","task","management","planning"],extractSignatureContent:(X)=>`${X.todos.length} todos`,abstractPermissionRule:()=>"*"})}function iZ($){return{total:$.length,completed:$.filter((Y)=>Y.status==="completed").length,inProgress:$.filter((Y)=>Y.status==="in_progress").length,pending:$.filter((Y)=>Y.status==="pending").length}}function rZ($,Y){let Z=[],X=Y.total>0?Math.round(Y.completed/Y.total*100):0;if(Z.push(`\uD83D\uDCCB TODO 列表 (${Y.completed}/${Y.total} 完成,${X}%)`),Z.push(""),$.length===0)return Z.push(" (暂无任务)"),Z.join(`
|
|
892
|
+
`);for(let Q of $){let J=Q.status==="completed"?"☑":"☐",q=`(P${Q.priority==="high"?0:Q.priority==="medium"?1:2})`,G=Q.status==="in_progress"?" ⚡":"",K=Q.status==="completed"?"~~":"";Z.push(` ${J} ${q} ${K}${Q.content}${K}${G}`)}return Z.join(`
|
|
893
|
+
`)}import{z as D1}from"zod";var R4=n({name:"WebFetch",displayName:"Web Fetch",kind:"readonly",schema:D1.object({url:D1.string().url().describe("URL to request"),method:D1.enum(["GET","POST","PUT","DELETE","HEAD"]).default("GET").describe("HTTP method"),headers:D1.record(D1.string()).optional().describe("Request headers (optional)"),body:D1.string().optional().describe("Request body (optional)"),timeout:G0.timeout(1000,120000,30000),follow_redirects:D1.boolean().default(!0).describe("Follow redirects"),max_redirects:D1.number().int().min(0).max(10).default(5).describe("Maximum redirect hops"),return_headers:D1.boolean().default(!1).describe("Return response headers")}),description:{short:"Fetches content from a specified URL and processes it using an AI model",long:`
|
|
894
894
|
- Fetches content from a specified URL and processes it using an AI model
|
|
895
895
|
- Takes a URL and a prompt as input
|
|
896
896
|
- Fetches the URL content, converts HTML to markdown
|
|
@@ -907,14 +907,14 @@ Usage notes:
|
|
|
907
907
|
- Results may be summarized if the content is very large
|
|
908
908
|
- Includes a self-cleaning 15-minute cache for faster responses when repeatedly accessing the same URL
|
|
909
909
|
- When a URL redirects to a different host, the tool will inform you and provide the redirect URL in a special format. You should then make a new WebFetch request with the redirect URL to fetch the content.
|
|
910
|
-
`},async execute($,Y){let{url:Z,method:X="GET",headers:Q={},body:J,timeout:
|
|
911
|
-
响应时间: ${
|
|
912
|
-
内容长度: ${
|
|
910
|
+
`},async execute($,Y){let{url:Z,method:X="GET",headers:Q={},body:J,timeout:q=30000,follow_redirects:G=!0,max_redirects:K=5,return_headers:W=!1}=$,{updateOutput:O}=Y,U=Y.signal??new AbortController().signal;try{O?.(`发送 ${X} 请求到: ${Z}`);let H=Date.now(),_=await aZ({url:Z,method:X,headers:Q,body:J,timeout:q,follow_redirects:G,max_redirects:K,signal:U}),z=Date.now()-H;if(_.response_time=z,!W)delete _.headers;let F={url:Z,method:X,status:_.status,response_time:z,content_length:Buffer.byteLength(_.body||"","utf8"),redirected:_.redirected||!1,redirect_count:_.redirect_count??0,final_url:_.url,content_type:_.content_type,redirect_chain:_.redirect_chain};if(_.status>=400)return{success:!1,llmContent:`HTTP error ${_.status}: ${_.status_text}`,displayContent:c9(_,F,!0),error:{type:"execution_error",message:`HTTP error ${_.status}: ${_.status_text}`,details:{...F,response_body:_.body}},metadata:F};return{success:!0,llmContent:_,displayContent:c9(_,F,!1),metadata:F}}catch(H){if(H.name==="AbortError")return{success:!1,llmContent:"Request aborted",displayContent:"⚠️ 请求被用户中止",error:{type:"execution_error",message:"操作被中止"}};return{success:!1,llmContent:`Network request failed: ${H.message}`,displayContent:`❌ 网络请求失败: ${H.message}`,error:{type:"execution_error",message:H.message,details:H}}}},version:"2.0.0",category:"网络工具",tags:["web","http","fetch","request","api"],extractSignatureContent:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return $.url}},abstractPermissionRule:($)=>{try{return`domain:${new URL($.url).hostname}`}catch{return"*"}}});async function aZ($){let{url:Y,method:Z,headers:X,body:Q,timeout:J,follow_redirects:q,max_redirects:G,signal:K}=$,W={"User-Agent":"Blade-AI/1.0",...X},O=Y,U=Z,H=Q,_=0,z=[];while(!0){let F={...W};if(H&&U!=="GET"&&U!=="HEAD"&&!$X(F,"content-type"))F["Content-Type"]="application/json";let w=await sZ(O,{method:U,headers:F,body:H&&U!=="GET"&&U!=="HEAD"?H:void 0,redirect:"manual"},J,K),L=w.headers.get("location"),N=w.status>=300&&w.status<400,A=q&&N&&L&&_<G;if(N&&q&&!L)throw Error(`收到状态码 ${w.status} 但响应缺少 Location 头`);if(N&&q&&_>=G)throw Error(`超过最大重定向次数 (${G})`);if(A&&L){_++;let R=tZ(L,O);if(z.push(`${w.status} → ${R}`),w.status===303||(w.status===301||w.status===302)&&U!=="GET"&&U!=="HEAD")U="GET",H=void 0;O=R;continue}let V=await w.text(),E=eZ(w.headers);return{status:w.status,status_text:w.statusText,headers:E,body:V,url:w.url||O,redirected:_>0,redirect_count:_,redirect_chain:z,content_type:E["content-type"],response_time:0}}}function c9($,Y,Z){let{url:X,method:Q,status:J,response_time:q,content_length:G}=Y,K=Z?`❌ ${Q} ${X} - ${J} ${$.status_text}`:`✅ ${Q} ${X} - ${J} ${$.status_text}`;if(K+=`
|
|
911
|
+
响应时间: ${q}ms`,K+=`
|
|
912
|
+
内容长度: ${G} 字节`,Y.content_type)K+=`
|
|
913
913
|
Content-Type: ${Y.content_type}`;if($.redirected&&Y.final_url&&Y.final_url!==X){if(K+=`
|
|
914
914
|
最终URL: ${Y.final_url}`,Y.redirect_count)K+=`
|
|
915
|
-
重定向次数: ${Y.redirect_count}`}let W=
|
|
915
|
+
重定向次数: ${Y.redirect_count}`}let W=nZ($.body,$.content_type);if(W)K+=`
|
|
916
916
|
响应内容:
|
|
917
|
-
${W}`;return K}function
|
|
917
|
+
${W}`;return K}function nZ($,Y){if(!$)return"(空响应)";if(oZ(Y,$))return"[binary content omitted]";let Z=$.trim();if(!Z)return"(仅包含空白字符)";return Z.length>800?`${Z.slice(0,800)}...`:Z}function oZ($,Y){if($){let Q=$.toLowerCase();if(["image/","audio/","video/","application/pdf","application/zip","application/octet-stream"].some((q)=>Q.startsWith(q)))return!0}if(!Y)return!1;let Z=0,X=Math.min(Y.length,200);for(let Q=0;Q<X;Q++){let J=Y.charCodeAt(Q);if(J===9||J===10||J===13)continue;if(J<32||J>126)Z++}return Z/(X||1)>0.3}async function sZ($,Y,Z,X){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z),q=()=>Q.abort();X?.addEventListener("abort",q);try{return await fetch($,{...Y,signal:Q.signal})}catch(G){if(G.name==="AbortError")throw G.message="请求被中止或超时",G;throw G}finally{clearTimeout(J),X?.removeEventListener("abort",q)}}function tZ($,Y){try{return new URL($,Y).toString()}catch{return $}}function eZ($){let Y={};return $.forEach((Z,X)=>{Y[X.toLowerCase()]=Z}),Y}function $X($,Y){let Z=Y.toLowerCase();return Object.keys($).some((X)=>X.toLowerCase()===Z)}import{z as A$}from"zod";var YX="https://duckduckgo.com/",ZX=15000,XX=8,b4=n({name:"WebSearch",displayName:"Web Search",kind:"readonly",schema:A$.object({query:A$.string().min(2,"Search query must be at least 2 characters").describe("Search query"),allowed_domains:A$.array(A$.string().min(1)).optional().describe("Return results only from these domains (optional)"),blocked_domains:A$.array(A$.string().min(1)).optional().describe("Exclude results from these domains (optional)")}),description:{short:"Search the web and use the results to inform responses",long:`
|
|
918
918
|
- Search the web and use the results to inform responses
|
|
919
919
|
- Provides up-to-date information for current events and recent data
|
|
920
920
|
- Returns search result information formatted as search result blocks, including links as markdown hyperlinks
|
|
@@ -939,29 +939,29 @@ Usage notes:
|
|
|
939
939
|
IMPORTANT - Use the correct year in search queries:
|
|
940
940
|
- You MUST use the current year when searching for recent information, documentation, or current events.
|
|
941
941
|
- Example: If the user asks for "latest React docs", search for "React documentation 2025", NOT "React documentation 2024"
|
|
942
|
-
`},async execute($,Y){let{query:Z}=$,X=
|
|
942
|
+
`},async execute($,Y){let{query:Z}=$,X=l9($.allowed_domains),Q=l9($.blocked_domains),{updateOutput:J}=Y,q=Y.signal??new AbortController().signal;J?.(`\uD83D\uDD0E Searching: "${Z}"`);try{let G=await JX(QX(Z),{headers:{Accept:"application/json, text/plain;q=0.9","User-Agent":"Blade-AI-WebSearch/1.0"}},ZX,q);if(!G.ok)throw Error(`Search request failed with status ${G.status}`);let K=await G.text(),W;try{W=JSON.parse(K)}catch{throw Error("Failed to parse search result JSON")}let O=qX(W),U=UX(O,X,Q),H=U.slice(0,XX),_={query:Z,results:H,provider:"duckduckgo",total_results:U.length,fetched_at:new Date().toISOString()},z={query:Z,provider:"duckduckgo",fetched_at:_.fetched_at,total_results:U.length,returned_results:H.length,allowed_domains:X,blocked_domains:Q};if(H.length===0)return{success:!0,llmContent:_,displayContent:`\uD83D\uDD0D WebSearch("${Z}") 未找到匹配结果`,metadata:z};return{success:!0,llmContent:_,displayContent:OX(Z,H,U.length),metadata:z}}catch(G){return{success:!1,llmContent:`WebSearch call failed: ${G.message}`,displayContent:`❌ WebSearch 调用失败: ${G.message}`,error:{type:"execution_error",message:G.message,details:{query:Z,allowedDomains:X,blockedDomains:Q}}}}},version:"1.0.0",category:"网络工具",tags:["web","search","internet","news"],extractSignatureContent:($)=>`search:${HX($.query)}`,abstractPermissionRule:()=>"search:*"});function QX($){let Y=new URL(YX);return Y.searchParams.set("q",$),Y.searchParams.set("format","json"),Y.searchParams.set("no_html","1"),Y.searchParams.set("skip_disambig","1"),Y.searchParams.set("t","blade-code"),Y.searchParams.set("kl","us-en"),Y.toString()}async function JX($,Y,Z,X){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z),q=()=>Q.abort();X?.addEventListener("abort",q);try{return await fetch($,{...Y,signal:Q.signal})}catch(G){if(G.name==="AbortError")throw Error("搜索请求超时或被中止");throw G}finally{clearTimeout(J),X?.removeEventListener("abort",q)}}function qX($){let Y=($.Results??[]).map((X)=>GX(X)).filter((X)=>X!==null),Z=r9($.RelatedTopics??[]);return[...Y,...Z]}function GX($){if(!$.FirstURL||!$.Text)return null;let{title:Y,snippet:Z}=a9($.Text);return{title:Y,snippet:Z,url:$.FirstURL,display_url:n9($.FirstURL),source:V4($.FirstURL)??""}}function r9($){let Y=[];for(let Z of $){if(Z.Topics&&Z.Topics.length>0){Y.push(...r9(Z.Topics));continue}if(Z.FirstURL&&Z.Text){let{title:X,snippet:Q}=a9(Z.Text);Y.push({title:X,snippet:Q,url:Z.FirstURL,display_url:n9(Z.FirstURL),source:V4(Z.FirstURL)??""})}}return Y}function a9($){let Y=KX($).trim();if(!Y.includes(" - "))return{title:Y,snippet:Y};let[Z,...X]=Y.split(" - "),Q=Z.trim(),J=X.join(" - ").trim()||Y;return{title:Q,snippet:J}}function KX($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'")}function n9($){try{let Y=new URL($),Z=Y.pathname==="/"?"":Y.pathname;return`${Y.hostname}${Z}`}catch{return $}}function V4($){try{return new URL($).hostname.toLowerCase()}catch{return null}}function WX($){return $.trim().toLowerCase()}function l9($){if(!$||$.length===0)return[];return $.map(WX).filter(Boolean)}function i9($,Y){return $===Y||$.endsWith(`.${Y}`)}function UX($,Y,Z){return $.filter((X)=>{let Q=V4(X.url);if(!Q)return!1;if(Z.length>0&&Z.some((J)=>i9(Q,J)))return!1;if(Y.length>0&&!Y.some((J)=>i9(Q,J)))return!1;return!0})}function OX($,Y,Z){let X=`\uD83D\uDD0E WebSearch("${$}") - 返回 ${Y.length}/${Z} 条结果`,Q=Y.map((J,q)=>`${q+1}. ${J.title}
|
|
943
943
|
${J.display_url}
|
|
944
944
|
${J.snippet}`);return[X,...Q].join(`
|
|
945
|
-
`)}function
|
|
946
|
-
`):void 0}}async executePostToolHooks($,Y,Z){if($.length===0)return{};let X=Z.config.maxConcurrentHooks||5,Q=await this.executeHooksConcurrently($,Y,Z,X),J=[],
|
|
945
|
+
`)}function HX($){let Y=$.trim().toLowerCase();return Y.length>80?Y.slice(0,80):Y}async function _X(){try{return await I0.getInstance().getAvailableTools()}catch($){return console.warn("MCP协议工具加载失败:",$),[]}}async function t9($){let Y=$?.sessionId||`session_${Date.now()}`,Z=$?.configDir||s9.join(o9.homedir(),".blade"),X=[s6,o6,e6,$4,q4,W4,O4,_4,F4,R4,b4,w4,A4({sessionId:Y,configDir:Z}),Y4,X4,z4,N4],Q=await _X();return[...X,...Q]}import{EventEmitter as EX}from"events";import{nanoid as vX}from"nanoid";import{nanoid as Y5}from"nanoid";var c2;((X)=>{X.PreToolUse="PreToolUse";X.PostToolUse="PostToolUse";X.Stop="Stop"})(c2||={});var D4;((X)=>{X.Approve="approve";X.Block="block";X.Async="async"})(D4||={});var I4;((X)=>{X.Allow="allow";X.Deny="deny";X.Ask="ask"})(I4||={});var k4={enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],Stop:[]};function v4($,Y){return{...$,...Y,PreToolUse:Y.PreToolUse??$.PreToolUse,PostToolUse:Y.PostToolUse??$.PostToolUse,Stop:Y.Stop??$.Stop}}function e9(){let $={};if(process.env.BLADE_DISABLE_HOOKS==="true")$.enabled=!1;if(process.env.BLADE_HOOK_TIMEOUT){let Y=parseInt(process.env.BLADE_HOOK_TIMEOUT,10);if(!isNaN(Y)&&Y>0)$.defaultTimeout=Y}return $}import{spawn as FX}from"child_process";class M4{content="";maxSize;constructor($){this.maxSize=$}append($){if(this.content.length<this.maxSize){let Y=this.maxSize-this.content.length;this.content+=$.substring(0,Y)}}getContent(){return this.content}isFull(){return this.content.length>=this.maxSize}}class y4{MAX_STDOUT_SIZE=1048576;MAX_STDERR_SIZE=1048576;MAX_INPUT_SIZE=102400;async execute($,Y,Z,X){let Q=JSON.stringify(Y);if(Q.length>this.MAX_INPUT_SIZE)throw Error(`Hook input too large: ${Q.length} bytes (max ${this.MAX_INPUT_SIZE})`);let J=this.createSafeEnv(Y),q=FX($,[],{shell:!0,env:J,cwd:Z.projectDir,timeout:X}),G=new M4(this.MAX_STDOUT_SIZE),K=new M4(this.MAX_STDERR_SIZE);q.stdout.setEncoding("utf8"),q.stderr.setEncoding("utf8"),q.stdout.on("data",(W)=>{G.append(W)}),q.stderr.on("data",(W)=>{K.append(W)});try{q.stdin.write(Q),q.stdin.end()}catch(W){throw q.kill("SIGTERM"),Error(`Failed to write hook input: ${W}`)}return new Promise((W,O)=>{let U=!1,H=setTimeout(()=>{U=!0,q.kill("SIGKILL")},X);if(q.on("close",(_)=>{clearTimeout(H),W({stdout:G.getContent(),stderr:K.getContent(),exitCode:U?124:_??1,timedOut:U})}),q.on("error",(_)=>{clearTimeout(H),O(_)}),Z.abortSignal)Z.abortSignal.addEventListener("abort",()=>{clearTimeout(H),q.kill("SIGTERM"),W({stdout:G.getContent(),stderr:"Hook cancelled by abort signal",exitCode:1,timedOut:!1})})})}createSafeEnv($){return{BLADE_PROJECT_DIR:$.project_dir,BLADE_SESSION_ID:$.session_id,BLADE_HOOK_EVENT:$.hook_event_name,BLADE_TOOL_NAME:"tool_name"in $?$.tool_name:"",BLADE_TOOL_USE_ID:"tool_use_id"in $?$.tool_use_id:"",PATH:process.env.PATH||"",HOME:process.env.HOME||"",USER:process.env.USER||"",SHELL:process.env.SHELL||"/bin/sh"}}}import{z as j}from"zod";var j4=j.object({hook_event_name:j.nativeEnum(c2),hook_execution_id:j.string(),timestamp:j.string(),project_dir:j.string(),session_id:j.string(),permission_mode:j.enum(["default","autoEdit","yolo","plan"]),_metadata:j.object({blade_version:j.string(),hook_timeout_ms:j.number()}).optional()}),NX=j4.extend({hook_event_name:j.literal("PreToolUse"),tool_name:j.string(),tool_use_id:j.string(),tool_input:j.record(j.unknown())}),BX=j4.extend({hook_event_name:j.literal("PostToolUse"),tool_name:j.string(),tool_use_id:j.string(),tool_input:j.record(j.unknown()),tool_response:j.unknown()}),LX=j4.extend({hook_event_name:j.literal("Stop"),reason:j.string().optional()}),FF=j.discriminatedUnion("hook_event_name",[NX,BX,LX]),wX=j.object({hookEventName:j.literal("PreToolUse"),permissionDecision:j.nativeEnum(I4).optional(),permissionDecisionReason:j.string().optional(),updatedInput:j.record(j.unknown()).optional()}),AX=j.object({hookEventName:j.literal("PostToolUse"),additionalContext:j.string().optional(),updatedOutput:j.unknown().optional()}),RX=j.object({decision:j.object({behavior:j.nativeEnum(D4)}).optional(),systemMessage:j.string().optional(),hookSpecificOutput:j.discriminatedUnion("hookEventName",[wX,AX]).optional(),suppressOutput:j.boolean().optional()}),bX=j.object({type:j.literal("command"),command:j.string(),timeout:j.number().positive().optional(),statusMessage:j.string().optional()}),VX=j.object({type:j.literal("prompt"),prompt:j.string(),timeout:j.number().positive().optional()}),DX=j.discriminatedUnion("type",[bX,VX]),IX=j.object({tools:j.string().optional(),paths:j.string().optional(),commands:j.string().optional()}),E4=j.object({name:j.string().optional(),matcher:IX.optional(),hooks:j.array(DX)}),zF=j.object({enabled:j.boolean().optional(),defaultTimeout:j.number().positive().optional(),timeoutBehavior:j.enum(["ignore","deny","ask"]).optional(),failureBehavior:j.enum(["ignore","deny","ask"]).optional(),maxConcurrentHooks:j.number().positive().optional(),PreToolUse:j.array(E4).optional(),PostToolUse:j.array(E4).optional(),Stop:j.array(E4).optional()});function $5($){let Y=RX.safeParse($);if(Y.success)return{success:!0,data:Y.data};return{success:!1,error:Y.error}}class P4{parse($,Y,Z){if($.timedOut){let Q=Z?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y}}let X=this.tryParseJSON($.stdout);if(X){let Q=$5(X);if(!Q.success){let q="error"in Q?Q.error.message:"Unknown validation error",G=Z?.failureBehavior||"ignore",K=`Invalid hook output JSON: ${q}`;if(G==="deny")return{success:!1,blocking:!0,error:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};else if(G==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${K}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};else return{success:!1,blocking:!1,warning:K,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y}}let J=Q.data;if(J.decision?.behavior==="block")return{success:!1,blocking:!0,error:J.systemMessage||"Hook blocked execution",output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};if(J.decision?.behavior==="async")return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y};return{success:!0,output:J,stdout:$.stdout,stderr:$.stderr,exitCode:$.exitCode,hook:Y}}return this.parseByExitCode($,Y,Z)}parseByExitCode($,Y,Z){let X=$.exitCode;switch(X){case 0:return{success:!0,stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};case 2:return{success:!1,blocking:!0,error:$.stderr||$.stdout||"Hook returned exit code 2",stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};case 124:{let Q=Z?.timeoutBehavior||"ignore",J="Hook timeout";if(Q==="deny")return{success:!1,blocking:!0,error:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:"Hook timeout. Continue?",stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};else return{success:!1,blocking:!1,warning:"Hook timeout",stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y}}default:{let Q=Z?.failureBehavior||"ignore",J=$.stderr||$.stdout||`Hook failed with exit code ${X}`;if(Q==="deny")return{success:!1,blocking:!0,error:J,stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};else if(Q==="ask")return{success:!1,blocking:!1,needsConfirmation:!0,warning:`${J}. Continue?`,stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y};else return{success:!1,blocking:!1,warning:J,stdout:$.stdout,stderr:$.stderr,exitCode:X,hook:Y}}}}tryParseJSON($){try{let Y=$.trim();if(!Y)return null;let Z=Y.match(/^\s*(\{[\s\S]*\})\s*$/);if(!Z)return null;return JSON.parse(Z[1])}catch{return null}}}class S4{processExecutor=new y4;outputParser=new P4;async executePreToolHooks($,Y,Z){if($.length===0)return{decision:"allow"};let X="tool_input"in Y?Y.tool_input:{},Q=[];for(let J of $)try{let q={...Y,...X&&{tool_input:X}},G=await this.executeHook(J,q,Z);if(!G.success){if(G.blocking)return{decision:"deny",reason:G.error};if(G.needsConfirmation)return{decision:"ask",reason:G.warning||G.error};if(G.warning)Q.push(G.warning);continue}let K=G.output?.hookSpecificOutput;if(K&&"permissionDecision"in K){switch(K.permissionDecision){case"deny":return{decision:"deny",reason:K.permissionDecisionReason};case"ask":return{decision:"ask",reason:K.permissionDecisionReason};case"allow":break}if(K.updatedInput)X={...X,...K.updatedInput}}}catch(q){let G=q instanceof Error?q.message:String(q);if(Q.push(`Hook failed: ${G}`),Z.config.failureBehavior==="deny")return{decision:"deny",reason:G};else if(Z.config.failureBehavior==="ask")return{decision:"ask",reason:`Hook failed: ${G}. Continue?`}}return{decision:"allow",modifiedInput:X,warning:Q.length>0?Q.join(`
|
|
946
|
+
`):void 0}}async executePostToolHooks($,Y,Z){if($.length===0)return{};let X=Z.config.maxConcurrentHooks||5,Q=await this.executeHooksConcurrently($,Y,Z,X),J=[],q=void 0,G=[];for(let K of Q){if(!K.success&&K.warning){G.push(K.warning);continue}let W=K.output?.hookSpecificOutput;if(W&&"additionalContext"in W){if(W.additionalContext)J.push(W.additionalContext);if(W.updatedOutput!==void 0)q=W.updatedOutput}}return{additionalContext:J.length>0?J.join(`
|
|
947
947
|
|
|
948
|
-
`):void 0,modifiedOutput:
|
|
949
|
-
`):void 0}}async executeHook($,Y,Z){if($.type==="command")return this.executeCommandHook($,Y,Z);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,Y,Z){let X=($.timeout??Z.config.defaultTimeout??60)*1000;try{let Q=await this.processExecutor.execute($.command,Y,Z,X);return this.outputParser.parse(Q,$,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch(Q){return{success:!1,blocking:!1,error:Q instanceof Error?Q.message:String(Q),hook:$}}}async executeHooksConcurrently($,Y,Z,X){let Q=[],J=new Set;for(let
|
|
948
|
+
`):void 0,modifiedOutput:q,warning:G.length>0?G.join(`
|
|
949
|
+
`):void 0}}async executeHook($,Y,Z){if($.type==="command")return this.executeCommandHook($,Y,Z);throw Error(`Hook type ${$.type} not yet implemented`)}async executeCommandHook($,Y,Z){let X=($.timeout??Z.config.defaultTimeout??60)*1000;try{let Q=await this.processExecutor.execute($.command,Y,Z,X);return this.outputParser.parse(Q,$,{timeoutBehavior:Z.config.timeoutBehavior,failureBehavior:Z.config.failureBehavior})}catch(Q){return{success:!1,blocking:!1,error:Q instanceof Error?Q.message:String(Q),hook:$}}}async executeHooksConcurrently($,Y,Z,X){let Q=[],J=new Set;for(let q of $){if(J.size>=X)await Promise.race(J);let G=this.executeHook(q,Y,Z).catch((W)=>({success:!1,blocking:!1,error:W instanceof Error?W.message:String(W),hook:q})),K=G.then(()=>{J.delete(K)}).catch(()=>{J.delete(K)});J.add(K),Q.push(G)}return Promise.all(Q)}}class T4{executedHooks=new Map;canExecute($,Y){if(!this.executedHooks.has($))this.executedHooks.set($,new Set);if(this.executedHooks.get($).has(Y))return console.warn(`[HookGuard] Hook ${Y} for tool ${$} already executed, skipping`),!1;return!0}markExecuted($,Y){let Z=this.executedHooks.get($);if(Z)Z.add(Y)}cleanup($){this.executedHooks.delete($)}cleanupAll(){this.executedHooks.clear()}}import kX from"picomatch";class C4{matches($,Y){if(!$)return!0;if($.tools&&Y.toolName){if(!this.matchPattern(Y.toolName,$.tools))return!1}if($.paths&&Y.filePath){if(!kX($.paths)(Y.filePath))return!1}if($.commands&&Y.command){if(!this.matchPattern(Y.command,$.commands))return!1}return!0}matchPattern($,Y){if(Y==="*")return!0;if(!Y.includes("|")&&!/[.*+?^${}()|[\]\\]/.test(Y))return $===Y;if(Y.includes("|"))return Y.split("|").map((X)=>X.trim()).includes($);try{return new RegExp(Y).test($)}catch{return $===Y}}}class l0{static instance=null;config=k4;executor=new S4;guard=new T4;matcher=new C4;sessionDisabled=!1;constructor(){}static getInstance(){if(!l0.instance)l0.instance=new l0;return l0.instance}loadConfig($){let Y=v4(k4,$),Z=e9();Y=v4(Y,Z),this.config=Y}isEnabled(){if(!this.config.enabled)return!1;if(this.sessionDisabled)return!1;return!0}disable(){this.sessionDisabled=!0,console.log("[HookManager] Hooks disabled for this session")}enable(){this.sessionDisabled=!1,console.log("[HookManager] Hooks enabled for this session")}async executePreToolHooks($,Y,Z,X){if(!this.isEnabled())return{decision:"allow"};if(X.permissionMode==="plan")return{decision:"allow"};if(!this.guard.canExecute(Y,"PreToolUse"))return{decision:"allow"};let Q={hook_event_name:"PreToolUse",hook_execution_id:Y5(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Y,tool_input:Z,project_dir:X.projectDir,session_id:X.sessionId,permission_mode:X.permissionMode},J=this.getMatchingHooks("PreToolUse",{toolName:$,filePath:this.extractFilePath(Z),command:this.extractCommand($,Z)});if(J.length===0)return{decision:"allow"};let q={projectDir:X.projectDir,sessionId:X.sessionId,permissionMode:X.permissionMode,config:this.config,abortSignal:X.abortSignal};try{let G=await this.executor.executePreToolHooks(J,Q,q);if(this.guard.markExecuted(Y,"PreToolUse"),X.permissionMode==="yolo"){if(G.decision==="deny")return G;return{decision:"allow",modifiedInput:G.modifiedInput,warning:G.warning,reason:G.reason}}return G}catch(G){return console.error("[HookManager] Error executing PreToolUse hooks:",G),{decision:"allow",warning:`Hook execution failed: ${G instanceof Error?G.message:String(G)}`}}}async executePostToolHooks($,Y,Z,X,Q){if(!this.isEnabled())return{};if(Q.permissionMode==="plan")return{};if(!this.guard.canExecute(Y,"PostToolUse"))return{};let J={hook_event_name:"PostToolUse",hook_execution_id:Y5(),timestamp:new Date().toISOString(),tool_name:$,tool_use_id:Y,tool_input:Z,tool_response:X,project_dir:Q.projectDir,session_id:Q.sessionId,permission_mode:Q.permissionMode},q=this.getMatchingHooks("PostToolUse",{toolName:$,filePath:this.extractFilePath(Z),command:this.extractCommand($,Z)});if(q.length===0)return{};let G={projectDir:Q.projectDir,sessionId:Q.sessionId,permissionMode:Q.permissionMode,config:this.config,abortSignal:Q.abortSignal};try{let K=await this.executor.executePostToolHooks(q,J,G);return this.guard.markExecuted(Y,"PostToolUse"),K}catch(K){return console.error("[HookManager] Error executing PostToolUse hooks:",K),{warning:`Hook execution failed: ${K instanceof Error?K.message:String(K)}`}}finally{this.guard.cleanup(Y)}}getMatchingHooks($,Y){let Z=this.config[$]||[],X=[];for(let Q of Z)if(this.matcher.matches(Q.matcher,Y))X.push(...Q.hooks);return X}extractFilePath($){let Y=["file_path","path","filePath","source","target"];for(let Z of Y){let X=$[Z];if(typeof X==="string")return X}return}extractCommand($,Y){if($==="Bash"||$==="BashTool"){let Z=Y.command;if(typeof Z==="string")return Z}return}cleanup(){this.guard.cleanupAll()}}class f4{name="hook";hookManager;constructor(){this.hookManager=l0.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Y=$._internal.tool;if(!Y)return;try{let Z=$.context.messageId||`tool_${vX()}`;$._internal.hookToolUseId=Z;let X=$.context.workspaceRoot||process.cwd(),Q=await this.hookManager.executePreToolHooks(Y.name,Z,$.params,{projectDir:X,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});if(Q.decision==="deny"){$.abort(Q.reason||"Hook blocked execution");return}if(Q.decision==="ask"){$._internal.needsConfirmation=!0,$._internal.confirmationReason=Q.reason||"Hook requires confirmation";return}if(Q.modifiedInput){let J={...$.params,...Q.modifiedInput};if(Y.build)try{Y.build(J),$.params=J}catch(q){$.abort(`Hook modified parameters are invalid: ${q instanceof Error?q.message:String(q)}`);return}}if(Q.warning)console.warn(`[Hook Warning] ${Q.warning}`)}catch(Z){console.error("[HookStage] Error executing hooks:",Z)}}}import{nanoid as MX}from"nanoid";class h4{name="post-hook";hookManager;constructor(){this.hookManager=l0.getInstance()}async process($){if(!this.hookManager.isEnabled())return;let Y=$._internal.tool;if(!Y)return;let Z=$.getResult();if(!Z)return;try{let X=$._internal.hookToolUseId||$.context.messageId||`tool_${MX()}`,Q=$.context.workspaceRoot||process.cwd(),J=await this.hookManager.executePostToolHooks(Y.name,X,$.params,Z,{projectDir:Q,sessionId:$.context.sessionId||"unknown",permissionMode:$.context.permissionMode||"default"});if(J.additionalContext){let q=Z.llmContent||Z.displayContent||"";Z.llmContent=`${q}
|
|
950
950
|
|
|
951
951
|
---
|
|
952
952
|
**Hook Context:**
|
|
953
|
-
${J.additionalContext}`}if(J.modifiedOutput!==void 0){let
|
|
953
|
+
${J.additionalContext}`}if(J.modifiedOutput!==void 0){let q=J.modifiedOutput;if(typeof q==="object"&&q!==null)Object.assign(Z,q)}if(J.warning)console.warn(`[PostToolUseHook Warning] ${J.warning}`)}catch(X){console.error("[PostToolUseHookStage] Error executing post-tool hooks:",X)}}}var x4=Y0("Execution");class T1{static instance=null;locks=new Map;constructor(){}static getInstance(){if(!T1.instance)T1.instance=new T1;return T1.instance}async acquireLock($,Y){let Z=this.locks.get($);if(Z)try{await Z}catch{}let X=this.executeWithLock($,Y);return this.locks.set($,X.then(()=>{return})),X}async executeWithLock($,Y){x4.debug(`获取文件锁: ${$}`);try{let Z=await Y();return x4.debug(`释放文件锁: ${$}`),Z}catch(Z){throw x4.debug(`操作失败,释放文件锁: ${$}`),Z}}isLocked($){return this.locks.has($)}clearLock($){this.locks.delete($)}clearAll(){this.locks.clear()}getLockedFiles(){return Array.from(this.locks.keys())}getLockedFileCount(){return this.locks.size}static resetInstance(){T1.instance=null}}import yX from"node:os";import p4 from"node:path";class g4{static SENSITIVE_PATTERNS=[{pattern:/^\.?id_rsa$/i,level:"high",description:"SSH 私钥"},{pattern:/^\.?id_ed25519$/i,level:"high",description:"SSH Ed25519 私钥"},{pattern:/^\.?id_ecdsa$/i,level:"high",description:"SSH ECDSA 私钥"},{pattern:/\.pem$/i,level:"high",description:"PEM 格式私钥"},{pattern:/\.key$/i,level:"high",description:"密钥文件"},{pattern:/\.p12$/i,level:"high",description:"PKCS#12 证书"},{pattern:/\.pfx$/i,level:"high",description:"PFX 证书"},{pattern:/^\.?keystore$/i,level:"high",description:"Java Keystore"},{pattern:/^\.?pgpass$/i,level:"high",description:"PostgreSQL 密码文件"},{pattern:/^\.?my\.cnf$/i,level:"high",description:"MySQL 配置文件(可能含密码)"},{pattern:/credentials\.json$/i,level:"high",description:"Google Cloud 凭证"},{pattern:/^\.?aws[\\/]credentials$/i,level:"high",description:"AWS 凭证"},{pattern:/^\.?gcp[\\/]credentials$/i,level:"high",description:"GCP 凭证"},{pattern:/^\.?azure[\\/]credentials$/i,level:"high",description:"Azure 凭证"},{pattern:/^service-account.*\.json$/i,level:"high",description:"服务账号密钥"},{pattern:/^\.env$/i,level:"medium",description:"环境变量文件"},{pattern:/^\.env\./i,level:"medium",description:"环境变量文件(带环境后缀)"},{pattern:/^\.?npmrc$/i,level:"medium",description:"npm 配置文件(可能含 token)"},{pattern:/^\.?pypirc$/i,level:"medium",description:"PyPI 配置文件(可能含密码)"},{pattern:/^\.?dockercfg$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?docker[\\/]config\.json$/i,level:"medium",description:"Docker 配置文件"},{pattern:/^\.?netrc$/i,level:"medium",description:"FTP/HTTP 认证文件"},{pattern:/^\.?git-credentials$/i,level:"medium",description:"Git 凭证文件"},{pattern:/^config\.toml$/i,level:"medium",description:"配置文件(可能含敏感信息)"},{pattern:/^secrets\./i,level:"medium",description:"密钥配置文件"},{pattern:/\.sqlite$/i,level:"low",description:"SQLite 数据库"},{pattern:/\.db$/i,level:"low",description:"数据库文件"},{pattern:/\.sql$/i,level:"low",description:"SQL 文件(可能含敏感数据)"}];static SENSITIVE_PATHS=[{path:/\.ssh[\\/]/i,level:"high",description:"SSH 配置目录"},{path:/\.aws[\\/]/i,level:"high",description:"AWS 配置目录"},{path:/\.config[\\/]gcloud[\\/]/i,level:"high",description:"Google Cloud 配置目录"},{path:/\.kube[\\/]/i,level:"high",description:"Kubernetes 配置目录"}];static check($){let Y=this.normalizePath($),Z=p4.basename(Y);for(let X of this.SENSITIVE_PATTERNS)if(this.matchPattern(Z,X.pattern))return{isSensitive:!0,level:X.level,matchedPattern:X.pattern instanceof RegExp?X.pattern.source:X.pattern,reason:X.description};for(let X of this.SENSITIVE_PATHS)if(this.matchPattern(Y,X.path))return{isSensitive:!0,level:X.level,matchedPattern:X.path instanceof RegExp?X.path.source:X.path,reason:X.description};return{isSensitive:!1}}static checkMultiple($){let Y=new Map;for(let Z of $)Y.set(Z,this.check(Z));return Y}static filterSensitive($,Y="low"){let Z={["high"]:3,["medium"]:2,["low"]:1},X=Z[Y];return $.map((Q)=>({path:Q,result:this.check(Q)})).filter(({result:Q})=>Q.isSensitive&&Q.level&&Z[Q.level]>=X)}static normalizePath($){if($.startsWith("~/")||$==="~")return p4.join(yX.homedir(),$.slice(1));return p4.resolve($)}static matchPattern($,Y){if(Y instanceof RegExp)return Y.test($);let Z=Y.replace(/\*/g,".*");return new RegExp(`^${Z}$`,"i").test($)}static getSensitivePatterns(){return[...this.SENSITIVE_PATTERNS]}static getSensitivePaths(){return[...this.SENSITIVE_PATHS]}}var t1=Y0("Execution");class m4{registry;name="discovery";constructor($){this.registry=$}async process($){let Y=this.registry.get($.toolName);if(!Y){$.abort(`Tool "${$.toolName}" not found`);return}$._internal.tool=Y}}class u4{name="permission";permissionChecker;sessionApprovals;defaultPermissionMode;constructor($,Y,Z){this.permissionChecker=new i1($),this.sessionApprovals=Y,this.defaultPermissionMode=Z}getPermissionChecker(){return this.permissionChecker}async process($){let Y=$._internal.tool;if(!Y){$.abort("Discovery stage failed; cannot perform permission check");return}try{let Z=Y.build($.params),X=Z.getAffectedPaths(),Q={toolName:Y.name,params:$.params,affectedPaths:X,tool:Y},J=i1.buildSignature(Q);$._internal.permissionSignature=J;let q=this.permissionChecker.check(Q),G=$.context.permissionMode||this.defaultPermissionMode;switch(q=this.applyModeOverrides(Y.kind,q,G),q.result){case"deny":$.abort(q.reason||`Tool invocation "${Y.name}" was denied by permission rules: ${q.matchedRule}`);return;case"ask":if(this.sessionApprovals.has(J))q={result:"allow",matchedRule:"remembered:session",reason:"User already allowed this operation in this session"};else $._internal.needsConfirmation=!0,$._internal.confirmationReason=q.reason||"User confirmation required";break;case"allow":break}if(X.length>0){let K=["/etc/","/sys/","/proc/","/dev/","/boot/","/root/","C:\\Windows\\System32","C:\\Program Files","C:\\ProgramData"],W=X.filter((U)=>{if(U.includes(".."))return!0;return K.some((H)=>U.includes(H))});if(W.length>0){$.abort(`Access to dangerous system paths denied: ${W.join(", ")}`);return}let O=g4.filterSensitive(X,"medium");if(O.length>0){let U=O.map(({path:_,result:z})=>`${_} (${z.level}: ${z.reason})`);if(O.filter(({result:_})=>_.level==="high").length>0&&q.result!=="allow"){$.abort(`Access to highly sensitive files denied:
|
|
954
954
|
${U.join(`
|
|
955
955
|
`)}
|
|
956
956
|
|
|
957
|
-
If access is required, add an explicit allow rule in permissions.`);return}if(
|
|
957
|
+
If access is required, add an explicit allow rule in permissions.`);return}if(q.result==="allow"&&O.length>0)$._internal.confirmationReason=`Sensitive file access detected:
|
|
958
958
|
${U.join(`
|
|
959
959
|
`)}
|
|
960
960
|
|
|
961
|
-
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=Z,$._internal.permissionCheckResult=
|
|
962
|
-
`);if(
|
|
961
|
+
Confirm to proceed?`,$._internal.needsConfirmation=!0}}$._internal.invocation=Z,$._internal.permissionCheckResult=q}catch(Z){$.abort(`Permission check failed: ${Z.message}`)}}applyModeOverrides($,Y,Z){if(Z==="yolo")return{result:"allow",matchedRule:"mode:yolo",reason:"YOLO mode: automatically approve all tool invocations"};if(Z==="plan"){if(!c$($))return{result:"deny",matchedRule:"mode:plan",reason:"Plan mode: modification tools are blocked; only read-only tools are allowed (Read/Glob/Grep/WebFetch/WebSearch/Task)"}}if(Y.result==="deny")return Y;if(Y.result==="allow")return Y;if(c$($))return{result:"allow",matchedRule:`mode:${Z}:readonly`,reason:"Read-only tools do not require confirmation"};if(Z==="autoEdit"&&$==="write")return{result:"allow",matchedRule:"mode:autoEdit:write",reason:"AUTO_EDIT mode: automatically approve write tools"};return Y}}class d4{sessionApprovals;name="confirmation";permissionChecker;constructor($,Y){this.sessionApprovals=$;this.permissionChecker=Y}async process($){let{tool:Y,invocation:Z,needsConfirmation:X,confirmationReason:Q,permissionCheckResult:J}=$._internal;if(!Y||!Z){$.abort("Pre-confirmation stage failed; cannot request user approval");return}if(!X)return;try{let G={title:`权限确认: ${Y.extractSignatureContent?Y.extractSignatureContent($.params):Y.name}`,message:Q||"此操作需要用户确认",details:this.generatePreviewForTool(Y.name,$.params),risks:this.extractRisksFromPermissionCheck(Y,$.params,J),affectedFiles:Z.getAffectedPaths()||[]};if(t1.warn(`工具 "${Y.name}" 需要用户确认: ${G.title}`),t1.warn(`详情: ${G.message}`),G.risks&&G.risks.length>0)t1.warn(`风险: ${G.risks.join(", ")}`);let K=$.context.confirmationHandler;if(K){let W=await K.requestConfirmation(G);if(!W.approved){$.abort(`User rejected execution: ${W.reason||"No reason provided"}`);return}if((W.scope||"once")==="session"&&$._internal.permissionSignature){let U=$._internal.permissionSignature;this.sessionApprovals.add(U);let H={toolName:Y.name,params:$.params,affectedPaths:Z.getAffectedPaths()||[],tool:Y};await this.persistSessionApproval(U,H)}}else t1.warn("⚠️ No ConfirmationHandler; auto-approving tool execution (non-interactive environment only)")}catch(q){$.abort(`User confirmation failed: ${q.message}`)}}async persistSessionApproval($,Y){try{let Z=i1.abstractPattern(Y);t1.debug(`保存权限规则: "${Z}"`),await e().appendLocalPermissionAllowRule(Z,{immediate:!0});let X=F0();if(X?.permissions)t1.debug("同步权限配置到 PermissionChecker:",X.permissions),this.permissionChecker.replaceConfig(X.permissions)}catch(Z){t1.warn(`Failed to persist permission rule "${$}": ${Z instanceof Error?Z.message:"Unknown error"}`)}}generatePreviewForTool($,Y){switch($){case"Edit":{let{old_string:Z,new_string:X}=Y;if(!Z&&!X)return;let Q=20,J=(q)=>{let G=q.split(`
|
|
962
|
+
`);if(G.length<=Q)return q;return`${G.slice(0,Q).join(`
|
|
963
963
|
`)}
|
|
964
|
-
... (还有 ${
|
|
964
|
+
... (还有 ${G.length-Q} 行)`};return`**变更前:**
|
|
965
965
|
\`\`\`
|
|
966
966
|
${J(Z||"(空)")}
|
|
967
967
|
\`\`\`
|
|
@@ -973,50 +973,50 @@ ${J(X||"(删除)")}
|
|
|
973
973
|
`);if(J.length<=Q)return`**文件内容预览:**
|
|
974
974
|
\`\`\`
|
|
975
975
|
${Z}
|
|
976
|
-
\`\`\``;let
|
|
976
|
+
\`\`\``;let q=J.slice(0,Q).join(`
|
|
977
977
|
`);return`**文件内容预览 (前 ${Q} 行):**
|
|
978
978
|
\`\`\`
|
|
979
|
-
${
|
|
979
|
+
${q}
|
|
980
980
|
\`\`\`
|
|
981
981
|
|
|
982
|
-
... (还有 ${J.length-Q} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Y,Z){let X=[];if(Z?.reason)X.push(Z.reason);if($.name==="Bash"){let Q=Y.command||"",J=Q.trim().split(/\s+/)[0];if(J==="cat"||J==="head"||J==="tail")X.push(`\uD83D\uDCA1 建议使用 Read 工具代替 ${J} 命令(性能更好,支持大文件分页)`);else if(J==="grep"||J==="rg")X.push("\uD83D\uDCA1 建议使用 Grep 工具代替 grep/rg 命令(支持更强大的过滤和上下文)");else if(J==="find")X.push("\uD83D\uDCA1 建议使用 Glob 工具代替 find 命令(更快,支持 glob 模式)");else if(J==="sed"||J==="awk")X.push(`\uD83D\uDCA1 建议使用 Edit 工具代替 ${J} 命令(更安全,支持预览和回滚)`);if(Q.includes("rm"))X.push("⚠️ 此命令可能删除文件");if(Q.includes("sudo"))X.push("⚠️ 此命令需要管理员权限");if(Q.includes("git push"))X.push("⚠️ 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")X.push("此操作将修改文件内容");else if($.name==="Delete")X.push("此操作将永久删除文件");return X}}class u4{name="execution";async process($){let Y=$._internal.invocation;if(!Y){$.abort("Pre-execution stage failed; cannot run tool");return}try{let Z=await Y.execute($.context.signal,$.context.onProgress,$.context);$.setResult(Z)}catch(Z){$.abort(`Tool execution failed: ${Z.message}`)}}}class m4{name="formatting";async process($){try{let Y=$.getResult();if(!Y.llmContent)Y.llmContent="Execution completed";if(!Y.displayContent)Y.displayContent=Y.success?"执行成功":"执行失败";if(!Y.metadata)Y.metadata={};Y.metadata.executionId=$.context.sessionId,Y.metadata.toolName=$.toolName,Y.metadata.timestamp=Date.now(),$.setResult(Y)}catch(Y){$.abort(`Result formatting failed: ${Y.message}`)}}}class d4 extends DX{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals=new Set;constructor($,Y={}){super();this.registry=$;this.maxHistorySize=Y.maxHistorySize||1000;let Z=Y.permissionConfig||{allow:[],ask:[],deny:[]},X=Y.permissionMode??"default",Q=new p4(Z,this.sessionApprovals,X);this.stages=[new x4(this.registry),Q,new P4,new g4(this.sessionApprovals,Q.getPermissionChecker()),new u4,new T4,new m4]}async execute($,Y,Z){let X=Date.now(),Q=this.generateExecutionId(),J=new y6($,Y,{...Z,sessionId:Z.sessionId||Q});this.emit("executionStarted",{executionId:Q,toolName:$,params:Y,context:Z,timestamp:X});let G=this.registry.get($),q=G&&!G.isConcurrencySafe,K=q&&Y.file_path?String(Y.file_path):null;if(q&&K)return P1.getInstance().acquireLock(K,()=>this.executeWithPipeline(J,Q,X));return this.executeWithPipeline(J,Q,X)}async executeWithPipeline($,Y,Z){try{for(let J of this.stages)if(this.emit("stageStarted",{executionId:Y,stageName:J.name,timestamp:Date.now()}),await J.process($),this.emit("stageCompleted",{executionId:Y,stageName:J.name,timestamp:Date.now()}),$.shouldAbort())break;let X=$.getResult(),Q=Date.now();return this.addToHistory({executionId:Y,toolName:$.toolName,params:$.params,result:X,startTime:Z,endTime:Q,context:$.context}),this.emit("executionCompleted",{executionId:Y,toolName:$.toolName,result:X,duration:Q-Z,timestamp:Q}),X}catch(X){let Q={success:!1,llmContent:`Tool execution failed: ${X.message}`,displayContent:`错误: ${X.message}`,error:{type:"execution_error",message:X.message}},J=Date.now();return this.addToHistory({executionId:Y,toolName:$.toolName,params:$.params,result:Q,startTime:Z,endTime:J,context:$.context}),this.emit("executionFailed",{executionId:Y,toolName:$.toolName,error:X,duration:J-Z,timestamp:J}),Q}}async executeAll($){let Y=$.map((Z)=>this.execute(Z.toolName,Z.params,Z.context));return Promise.all(Y)}async executeParallel($,Y=5){let Z=[],X=[];for(let Q=0;Q<$.length;Q++){let J=$[Q],G=this.execute(J.toolName,J.params,J.context);if(X.push(G),X.length>=Y||Q===$.length-1){let q=await Promise.all(X);Z.push(...q),X.length=0}}return Z}getExecutionHistory($){let Y=[...this.executionHistory];return $?Y.slice(-$):Y}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)},Y=0;for(let Z of this.executionHistory){if(Z.result.success)$.successfulExecutions++;else $.failedExecutions++;let X=Z.endTime-Z.startTime;Y+=X;let Q=$.toolUsage.get(Z.toolName)||0;$.toolUsage.set(Z.toolName,Q+1)}return $.averageDuration=$.totalExecutions>0?Y/$.totalExecutions:0,$}addStage($,Y=-1){if(Y===-1){let Z=this.stages.findIndex((X)=>X.name==="execution");this.stages.splice(Z,0,$)}else this.stages.splice(Y,0,$);this.emit("stageAdded",{stageName:$.name,position:Y,timestamp:Date.now()})}removeStage($){let Y=this.stages.findIndex((Z)=>Z.name===$);if(Y===-1)return!1;return this.stages.splice(Y,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 kX}from"events";class c4 extends kX{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;constructor(){super()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Y=[];for(let Z of $)try{this.register(Z)}catch(X){Y.push(`${Z.name}: ${X.message}`)}if(Y.length>0)throw Error(`批量注册失败: ${Y.join(", ")}`)}unregister($){let Y=this.tools.get($);if(!Y)return!1;return this.tools.delete($),this.removeFromIndexes(Y),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 Y=this.categories.get($);if(!Y)return[];return Array.from(Y).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}getByTag($){let Y=this.tags.get($);if(!Y)return[];return Array.from(Y).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}search($){let Y=$.toLowerCase();return this.getAll().filter((Z)=>{let X=typeof Z.description==="string"?Z.description:Z.description.short;return Z.name.toLowerCase().includes(Y)||X.toLowerCase().includes(Y)||Z.displayName.toLowerCase().includes(Y)||Z.category&&Z.category.toLowerCase().includes(Y)||Z.tags.some((Q)=>Q.toLowerCase().includes(Y))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();return this.getFunctionDeclarations()}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(([$,Y])=>[$,Y.size]))}}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let Y=0,Z=`mcp__${$}__`;for(let[X,Q]of this.mcpTools.entries())if(X.startsWith(Z))this.mcpTools.delete(X),this.removeFromIndexes(Q),Y++,this.emit("toolUnregistered",{type:"mcp",toolName:X,serverName:$,timestamp:Date.now()});return Y}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Y of $.tags){if(!this.tags.has(Y))this.tags.set(Y,new Set);this.tags.get(Y).add($.name)}}removeFromIndexes($){if($.category){let Y=this.categories.get($.category);if(Y){if(Y.delete($.name),Y.size===0)this.categories.delete($.category)}}for(let Y of $.tags){let Z=this.tags.get(Y);if(Z){if(Z.delete($.name),Z.size===0)this.tags.delete(Y)}}}}import*as Y5 from"crypto";import{nanoid as $5}from"nanoid";class l4{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Y=10,Z=20){this.maxSummaryLength=$,this.keyPointsLimit=Y,this.recentMessagesLimit=Z}async compress($){let Y=$.layers.conversation.messages,Z=$.layers.tool.recentCalls,X=Y.filter((U)=>U.role==="system"),Q=Y.filter((U)=>U.role!=="system"),J=this.getRecentMessages(Q),G=Q.slice(0,-this.recentMessagesLimit),q=await this.generateSummary(G),K=this.extractKeyPoints(G,Z),W=this.generateToolSummary(Z),O=this.estimateTokenCount(q,K,J,W);return{summary:q,keyPoints:K,recentMessages:[...X,...J],toolSummary:W,tokenCount:O}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Y=new Set,Z=new Set,X=new Set;for(let J of $){let G=J.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((O)=>{if(G.includes(O)){let U=this.extractContext(G,O,50);if(U)Y.add(U)}}),["创建","删除","修改","更新","实现","开发"].forEach((O)=>{if(G.includes(O)){let U=this.extractContext(G,O,30);if(U)Z.add(U)}}),["决定","选择","确定","采用","使用"].forEach((O)=>{if(G.includes(O)){let U=this.extractContext(G,O,40);if(U)X.add(U)}})}let Q=`对话涉及 ${$.length} 条消息。`;if(Y.size>0)Q+=` 主要讨论:${Array.from(Y).slice(0,3).join("、")}。`;if(Z.size>0)Q+=` 执行操作:${Array.from(Z).slice(0,3).join("、")}。`;if(X.size>0)Q+=` 关键决策:${Array.from(X).slice(0,2).join("、")}。`;return Q.length>this.maxSummaryLength?Q.substring(0,this.maxSummaryLength)+"...":Q}extractKeyPoints($,Y){let Z=new Set;for(let Q of $)if(Q.role==="user")this.extractQuestions(Q.content).forEach((q)=>Z.add(`用户问题:${q}`)),this.extractRequests(Q.content).forEach((q)=>Z.add(`用户请求:${q}`));else if(Q.role==="assistant")this.extractSolutions(Q.content).forEach((G)=>Z.add(`解决方案:${G}`));return this.summarizeToolUsage(Y).forEach((Q)=>Z.add(`工具使用:${Q}`)),Array.from(Z).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Y=new Map,Z=Date.now()-600000;for(let Q of $){let J=Y.get(Q.name)||{count:0,success:0,recent:0};if(J.count++,Q.status==="success")J.success++;if(Q.timestamp>Z)J.recent++;Y.set(Q.name,J)}let X=[];for(let[Q,J]of Array.from(Y.entries())){let G=Math.round(J.success/J.count*100);X.push(`${Q}(${J.count}次,成功率${G}%)`)}return`工具调用:${X.join("、")}`}estimateTokenCount($,Y,Z,X){let Q=$.length+Y.join(" ").length;if(X)Q+=X.length;for(let J of Z)Q+=J.content.length;return Math.ceil(Q/4)}extractContext($,Y,Z){let X=$.indexOf(Y);if(X===-1)return null;let Q=Math.max(0,X-Z/2),J=Math.min($.length,X+Z/2);return $.substring(Q,J).trim()}extractQuestions($){let Y=[],Z=["?","?","如何","怎么","什么","为什么"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Y.push(J)}return Y.slice(0,3)}extractRequests($){let Y=[],Z=["请","帮我","需要","想要","希望","能否"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Y.push(J)}return Y.slice(0,3)}extractSolutions($){let Y=[],Z=["可以","建议","推荐","应该","最好","解决方案"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>10&&J.length<150)Y.push(J)}return Y.slice(0,3)}summarizeToolUsage($){let Y=[],Z=$.filter((X)=>Date.now()-X.timestamp<1800000);if(Z.length>0){let X=new Map;Z.forEach((Q)=>{let J=X.get(Q.name)||[];J.push(Q),X.set(Q.name,J)});for(let[Q,J]of Array.from(X.entries())){let G=J.filter((q)=>q.status==="success").length;Y.push(`${Q}(${J.length}次,${G}成功)`)}}return Y.slice(0,5)}shouldCompress($,Y){return this.estimateCurrentTokens($)>Y*0.8}estimateCurrentTokens($){let Z=$.layers.conversation.messages.reduce((X,Q)=>X+Q.content.length,0);return Math.ceil(Z/4)}}class t1{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Y){let Z={...this.defaultOptions,...Y},X={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,Z),tool:Z.includeTools?this.filterTools($.layers.tool,Z):{recentCalls:[],toolStates:{},dependencies:{}},workspace:Z.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return X.metadata.totalTokens=this.estimateTokens(X),X}filterConversation($,Y){let Z=[...$.messages];if(Y.timeWindow>0){let X=Date.now()-Y.timeWindow;Z=Z.filter((Q)=>Q.timestamp>=X||Q.role==="system")}if(Y.priority>1)Z=this.filterByPriority(Z,Y.priority);if(Y.maxMessages>0)Z=this.limitMessages(Z,Y.maxMessages);if(Y.maxTokens>0)Z=this.limitByTokens(Z,Y.maxTokens);return{messages:Z,summary:$.summary,topics:this.updateTopics(Z,$.topics),lastActivity:$.lastActivity}}filterTools($,Y){let Z=[...$.recentCalls];if(Y.timeWindow>0){let K=Date.now()-Y.timeWindow;Z=Z.filter((W)=>W.timestamp>=K)}let X=Z.filter((K)=>K.status==="success"),Q=Z.filter((K)=>K.status==="error"),J=Math.min(20,X.length),G=Math.min(10,Q.length);return{recentCalls:[...X.slice(-J),...Q.slice(-G)].sort((K,W)=>K.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Y){return $.filter((Z)=>{if(Z.role==="system")return!0;return this.calculateMessagePriority(Z)>=Y})}calculateMessagePriority($){let Y=1;if($.role==="system")Y+=3;else if($.role==="assistant")Y+=1;let Z=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((J)=>Z.includes(J)))Y+=2;if(Z.includes("```")||Z.includes("function")||Z.includes("class"))Y+=1;let Q=(Date.now()-$.timestamp)/3600000;if(Q<1)Y+=2;else if(Q<6)Y+=1;return Y}limitMessages($,Y){if($.length<=Y)return $;let Z=$.filter((G)=>G.role==="system"),X=$.filter((G)=>G.role!=="system"),Q=Y-Z.length,J=Q>0?X.slice(-Q):[];return[...Z,...J].sort((G,q)=>G.timestamp-q.timestamp)}limitByTokens($,Y){if(Y<=0)return $;let Z=0,X=[];for(let Q=$.length-1;Q>=0;Q--){let J=$[Q],G=this.estimateMessageTokens(J);if(J.role==="system")if(Z+G<=Y)X.unshift(J),Z+=G;else{let q=this.compressMessage(J,Y-Z);X.unshift(q),Z+=this.estimateMessageTokens(q)}else if(Z+G<=Y)X.unshift(J),Z+=G;else break}return X.sort((Q,J)=>Q.timestamp-J.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Y){let Z=Y*4;if($.content.length<=Z)return $;let X=$.content.substring(0,Z-3)+"...";return{...$,content:X,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Y){let Z=new Set(Y);for(let X of $)this.extractTopicsFromMessage(X).forEach((J)=>Z.add(J));return Array.from(Z).slice(0,10)}extractTopicsFromMessage($){let Y=$.content.toLowerCase(),Z=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((Q)=>{if(Y.includes(Q))Z.push(Q)}),Z}estimateTokens($){let Y=0;for(let X of $.layers.conversation.messages)Y+=this.estimateMessageTokens(X);let Z=JSON.stringify($.layers.system);if(Y+=Math.ceil(Z.length/4),$.layers.tool.recentCalls.length>0){let X=JSON.stringify($.layers.tool);Y+=Math.ceil(X.length/8)}return Y}static createPresets(){return{lightweight:new t1({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new t1({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new t1({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new t1({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class i4{cache=new Map;maxSize;defaultTTL;constructor($=100,Y=300000){this.maxSize=$,this.defaultTTL=Y}set($,Y,Z){let X=Date.now(),Q={data:Y,timestamp:X,accessCount:0,lastAccess:X,ttl:Z||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,Q)}get($){let Y=this.cache.get($);if(!Y)return null;let Z=Date.now();if(Z-Y.timestamp>Y.ttl)return this.cache.delete($),null;return Y.accessCount++,Y.lastAccess=Z,Y.data}has($){let Y=this.cache.get($);if(!Y)return!1;if(Date.now()-Y.timestamp>Y.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($,Y,Z){let X=`summary:${$}:${Y.length}`;this.set(X,{summary:Z,messageCount:Y.length,lastMessage:Y[Y.length-1]?.timestamp||0},600000)}getMessageSummary($,Y){let Z=`summary:${$}:${Y}`;return this.get(Z)}cacheToolResult($,Y,Z){let X=this.hashInput(Y),Q=`tool:${$}:${X}`;this.set(Q,Z,1800000)}getToolResult($,Y){let Z=this.hashInput(Y),X=`tool:${$}:${Z}`;return this.get(X)}cacheCompressedContext($,Y){let Z=`compressed:${$}`;this.set(Z,Y,900000)}getCompressedContext($){let Y=`compressed:${$}`;return this.get(Y)}getStats(){this.cleanExpired();let $=0,Y=0,Z=[];for(let[X,Q]of Array.from(this.cache.entries()))$+=Q.accessCount,Y+=this.estimateItemSize(Q),Z.push({key:X,accessCount:Q.accessCount,lastAccess:Q.lastAccess});return Z.sort((X,Q)=>Q.accessCount-X.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Y,topKeys:Z.slice(0,10)}}cleanExpired(){let $=Date.now(),Y=[];for(let[Z,X]of Array.from(this.cache.entries()))if($-X.timestamp>X.ttl)Y.push(Z);Y.forEach((Z)=>this.cache.delete(Z))}evictLeastUsed(){let $=null,Y=1/0,Z=Date.now();for(let[X,Q]of Array.from(this.cache.entries())){let J=1/(Z-Q.lastAccess+1),G=Q.accessCount,q=J*G;if(q<Y)Y=q,$=X}if($)this.cache.delete($)}hashInput($){let Y=JSON.stringify($),Z=0;for(let X=0;X<Y.length;X++){let Q=Y.charCodeAt(X);Z=(Z<<5)-Z+Q,Z=Z&Z}return Math.abs(Z).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Y){let Z=this.cache.get($);if(Z)return Z.ttl=Y,Z.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Y=this.cache.get($);if(!Y)return-1;let Z=Y.ttl-(Date.now()-Y.timestamp);return Math.max(0,Z)}warmup($){$.forEach(({key:Y,value:Z,ttl:X})=>{this.set(Y,Z,X)})}}class r4{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 Y=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Y.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($,Y){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Y,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 Y=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Y)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}z$();import{nanoid as A$}from"nanoid";import*as D1 from"node:fs/promises";import*as e9 from"node:path";import*as d2 from"node:fs";import{createReadStream as MX}from"node:fs";import*as E0 from"node:fs/promises";import*as n4 from"node:path";import{createInterface as vX}from"node:readline";class J1{filePath;constructor($){this.filePath=$}async append($){try{await E0.mkdir(n4.dirname(this.filePath),{recursive:!0});let Y=JSON.stringify($)+`
|
|
983
|
-
`;await E0.appendFile(this.filePath,Y,"utf-8")}catch(Y){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,Y),Y}}async appendBatch($){try{await E0.mkdir(
|
|
982
|
+
... (还有 ${J.length-Q} 行)`}case"Bash":case"Shell":return;default:return}}extractRisksFromPermissionCheck($,Y,Z){let X=[];if(Z?.reason)X.push(Z.reason);if($.name==="Bash"){let Q=Y.command||"",J=Q.trim().split(/\s+/)[0];if(J==="cat"||J==="head"||J==="tail")X.push(`\uD83D\uDCA1 建议使用 Read 工具代替 ${J} 命令(性能更好,支持大文件分页)`);else if(J==="grep"||J==="rg")X.push("\uD83D\uDCA1 建议使用 Grep 工具代替 grep/rg 命令(支持更强大的过滤和上下文)");else if(J==="find")X.push("\uD83D\uDCA1 建议使用 Glob 工具代替 find 命令(更快,支持 glob 模式)");else if(J==="sed"||J==="awk")X.push(`\uD83D\uDCA1 建议使用 Edit 工具代替 ${J} 命令(更安全,支持预览和回滚)`);if(Q.includes("rm"))X.push("⚠️ 此命令可能删除文件");if(Q.includes("sudo"))X.push("⚠️ 此命令需要管理员权限");if(Q.includes("git push"))X.push("⚠️ 此命令将推送代码到远程仓库")}else if($.name==="Write"||$.name==="Edit")X.push("此操作将修改文件内容");else if($.name==="Delete")X.push("此操作将永久删除文件");return X}}class c4{name="execution";async process($){let Y=$._internal.invocation;if(!Y){$.abort("Pre-execution stage failed; cannot run tool");return}try{let Z=await Y.execute($.context.signal,$.context.onProgress,$.context);$.setResult(Z)}catch(Z){$.abort(`Tool execution failed: ${Z.message}`)}}}class l4{name="formatting";async process($){try{let Y=$.getResult();if(!Y.llmContent)Y.llmContent="Execution completed";if(!Y.displayContent)Y.displayContent=Y.success?"执行成功":"执行失败";if(!Y.metadata)Y.metadata={};Y.metadata.executionId=$.context.sessionId,Y.metadata.toolName=$.toolName,Y.metadata.timestamp=Date.now(),$.setResult(Y)}catch(Y){$.abort(`Result formatting failed: ${Y.message}`)}}}class i4 extends EX{registry;stages;executionHistory=[];maxHistorySize;sessionApprovals=new Set;constructor($,Y={}){super();this.registry=$;this.maxHistorySize=Y.maxHistorySize||1000;let Z=Y.permissionConfig||{allow:[],ask:[],deny:[]},X=Y.permissionMode??"default",Q=new u4(Z,this.sessionApprovals,X);this.stages=[new m4(this.registry),Q,new f4,new d4(this.sessionApprovals,Q.getPermissionChecker()),new c4,new h4,new l4]}async execute($,Y,Z){let X=Date.now(),Q=this.generateExecutionId(),J=new P6($,Y,{...Z,sessionId:Z.sessionId||Q});this.emit("executionStarted",{executionId:Q,toolName:$,params:Y,context:Z,timestamp:X});let q=this.registry.get($),G=q&&!q.isConcurrencySafe,K=G&&Y.file_path?String(Y.file_path):null;if(G&&K)return T1.getInstance().acquireLock(K,()=>this.executeWithPipeline(J,Q,X));return this.executeWithPipeline(J,Q,X)}async executeWithPipeline($,Y,Z){try{for(let J of this.stages)if(this.emit("stageStarted",{executionId:Y,stageName:J.name,timestamp:Date.now()}),await J.process($),this.emit("stageCompleted",{executionId:Y,stageName:J.name,timestamp:Date.now()}),$.shouldAbort())break;let X=$.getResult(),Q=Date.now();return this.addToHistory({executionId:Y,toolName:$.toolName,params:$.params,result:X,startTime:Z,endTime:Q,context:$.context}),this.emit("executionCompleted",{executionId:Y,toolName:$.toolName,result:X,duration:Q-Z,timestamp:Q}),X}catch(X){let Q={success:!1,llmContent:`Tool execution failed: ${X.message}`,displayContent:`错误: ${X.message}`,error:{type:"execution_error",message:X.message}},J=Date.now();return this.addToHistory({executionId:Y,toolName:$.toolName,params:$.params,result:Q,startTime:Z,endTime:J,context:$.context}),this.emit("executionFailed",{executionId:Y,toolName:$.toolName,error:X,duration:J-Z,timestamp:J}),Q}}async executeAll($){let Y=$.map((Z)=>this.execute(Z.toolName,Z.params,Z.context));return Promise.all(Y)}async executeParallel($,Y=5){let Z=[],X=[];for(let Q=0;Q<$.length;Q++){let J=$[Q],q=this.execute(J.toolName,J.params,J.context);if(X.push(q),X.length>=Y||Q===$.length-1){let G=await Promise.all(X);Z.push(...G),X.length=0}}return Z}getExecutionHistory($){let Y=[...this.executionHistory];return $?Y.slice(-$):Y}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)},Y=0;for(let Z of this.executionHistory){if(Z.result.success)$.successfulExecutions++;else $.failedExecutions++;let X=Z.endTime-Z.startTime;Y+=X;let Q=$.toolUsage.get(Z.toolName)||0;$.toolUsage.set(Z.toolName,Q+1)}return $.averageDuration=$.totalExecutions>0?Y/$.totalExecutions:0,$}addStage($,Y=-1){if(Y===-1){let Z=this.stages.findIndex((X)=>X.name==="execution");this.stages.splice(Z,0,$)}else this.stages.splice(Y,0,$);this.emit("stageAdded",{stageName:$.name,position:Y,timestamp:Date.now()})}removeStage($){let Y=this.stages.findIndex((Z)=>Z.name===$);if(Y===-1)return!1;return this.stages.splice(Y,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 jX}from"events";class r4 extends jX{tools=new Map;mcpTools=new Map;categories=new Map;tags=new Map;constructor(){super()}register($){if(this.tools.has($.name))throw Error(`工具 '${$.name}' 已注册`);this.tools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"builtin",tool:$,timestamp:Date.now()})}registerAll($){let Y=[];for(let Z of $)try{this.register(Z)}catch(X){Y.push(`${Z.name}: ${X.message}`)}if(Y.length>0)throw Error(`批量注册失败: ${Y.join(", ")}`)}unregister($){let Y=this.tools.get($);if(!Y)return!1;return this.tools.delete($),this.removeFromIndexes(Y),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 Y=this.categories.get($);if(!Y)return[];return Array.from(Y).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}getByTag($){let Y=this.tags.get($);if(!Y)return[];return Array.from(Y).map((Z)=>this.get(Z)).filter((Z)=>Z!==void 0)}search($){let Y=$.toLowerCase();return this.getAll().filter((Z)=>{let X=typeof Z.description==="string"?Z.description:Z.description.short;return Z.name.toLowerCase().includes(Y)||X.toLowerCase().includes(Y)||Z.displayName.toLowerCase().includes(Y)||Z.category&&Z.category.toLowerCase().includes(Y)||Z.tags.some((Q)=>Q.toLowerCase().includes(Y))})}getFunctionDeclarations(){return this.getAll().map(($)=>$.getFunctionDeclaration())}getReadOnlyFunctionDeclarations(){return this.getAll().filter(($)=>$.isReadOnly).map(($)=>$.getFunctionDeclaration())}getFunctionDeclarationsByMode($){if($==="plan")return this.getReadOnlyFunctionDeclarations();return this.getFunctionDeclarations()}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(([$,Y])=>[$,Y.size]))}}registerMcpTool($){if(this.mcpTools.has($.name))this.mcpTools.delete($.name);this.mcpTools.set($.name,$),this.updateIndexes($),this.emit("toolRegistered",{type:"mcp",tool:$,timestamp:Date.now()})}removeMcpTools($){let Y=0,Z=`mcp__${$}__`;for(let[X,Q]of this.mcpTools.entries())if(X.startsWith(Z))this.mcpTools.delete(X),this.removeFromIndexes(Q),Y++,this.emit("toolUnregistered",{type:"mcp",toolName:X,serverName:$,timestamp:Date.now()});return Y}updateIndexes($){if($.category){if(!this.categories.has($.category))this.categories.set($.category,new Set);this.categories.get($.category).add($.name)}for(let Y of $.tags){if(!this.tags.has(Y))this.tags.set(Y,new Set);this.tags.get(Y).add($.name)}}removeFromIndexes($){if($.category){let Y=this.categories.get($.category);if(Y){if(Y.delete($.name),Y.size===0)this.categories.delete($.category)}}for(let Y of $.tags){let Z=this.tags.get(Y);if(Z){if(Z.delete($.name),Z.size===0)this.tags.delete(Y)}}}}import*as Q5 from"crypto";import{nanoid as X5}from"nanoid";class a4{maxSummaryLength;keyPointsLimit;recentMessagesLimit;constructor($=500,Y=10,Z=20){this.maxSummaryLength=$,this.keyPointsLimit=Y,this.recentMessagesLimit=Z}async compress($){let Y=$.layers.conversation.messages,Z=$.layers.tool.recentCalls,X=Y.filter((U)=>U.role==="system"),Q=Y.filter((U)=>U.role!=="system"),J=this.getRecentMessages(Q),q=Q.slice(0,-this.recentMessagesLimit),G=await this.generateSummary(q),K=this.extractKeyPoints(q,Z),W=this.generateToolSummary(Z),O=this.estimateTokenCount(G,K,J,W);return{summary:G,keyPoints:K,recentMessages:[...X,...J],toolSummary:W,tokenCount:O}}getRecentMessages($){return $.slice(-this.recentMessagesLimit)}async generateSummary($){if($.length===0)return"";let Y=new Set,Z=new Set,X=new Set;for(let J of $){let q=J.content.toLowerCase();["关于","讨论","问题","项目","功能","需求"].forEach((O)=>{if(q.includes(O)){let U=this.extractContext(q,O,50);if(U)Y.add(U)}}),["创建","删除","修改","更新","实现","开发"].forEach((O)=>{if(q.includes(O)){let U=this.extractContext(q,O,30);if(U)Z.add(U)}}),["决定","选择","确定","采用","使用"].forEach((O)=>{if(q.includes(O)){let U=this.extractContext(q,O,40);if(U)X.add(U)}})}let Q=`对话涉及 ${$.length} 条消息。`;if(Y.size>0)Q+=` 主要讨论:${Array.from(Y).slice(0,3).join("、")}。`;if(Z.size>0)Q+=` 执行操作:${Array.from(Z).slice(0,3).join("、")}。`;if(X.size>0)Q+=` 关键决策:${Array.from(X).slice(0,2).join("、")}。`;return Q.length>this.maxSummaryLength?Q.substring(0,this.maxSummaryLength)+"...":Q}extractKeyPoints($,Y){let Z=new Set;for(let Q of $)if(Q.role==="user")this.extractQuestions(Q.content).forEach((G)=>Z.add(`用户问题:${G}`)),this.extractRequests(Q.content).forEach((G)=>Z.add(`用户请求:${G}`));else if(Q.role==="assistant")this.extractSolutions(Q.content).forEach((q)=>Z.add(`解决方案:${q}`));return this.summarizeToolUsage(Y).forEach((Q)=>Z.add(`工具使用:${Q}`)),Array.from(Z).slice(0,this.keyPointsLimit)}generateToolSummary($){if($.length===0)return"";let Y=new Map,Z=Date.now()-600000;for(let Q of $){let J=Y.get(Q.name)||{count:0,success:0,recent:0};if(J.count++,Q.status==="success")J.success++;if(Q.timestamp>Z)J.recent++;Y.set(Q.name,J)}let X=[];for(let[Q,J]of Array.from(Y.entries())){let q=Math.round(J.success/J.count*100);X.push(`${Q}(${J.count}次,成功率${q}%)`)}return`工具调用:${X.join("、")}`}estimateTokenCount($,Y,Z,X){let Q=$.length+Y.join(" ").length;if(X)Q+=X.length;for(let J of Z)Q+=J.content.length;return Math.ceil(Q/4)}extractContext($,Y,Z){let X=$.indexOf(Y);if(X===-1)return null;let Q=Math.max(0,X-Z/2),J=Math.min($.length,X+Z/2);return $.substring(Q,J).trim()}extractQuestions($){let Y=[],Z=["?","?","如何","怎么","什么","为什么"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Y.push(J)}return Y.slice(0,3)}extractRequests($){let Y=[],Z=["请","帮我","需要","想要","希望","能否"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>5&&J.length<100)Y.push(J)}return Y.slice(0,3)}extractSolutions($){let Y=[],Z=["可以","建议","推荐","应该","最好","解决方案"],X=$.split(/[。!.!]/);for(let Q of X)if(Z.some((J)=>Q.includes(J))){let J=Q.trim();if(J.length>10&&J.length<150)Y.push(J)}return Y.slice(0,3)}summarizeToolUsage($){let Y=[],Z=$.filter((X)=>Date.now()-X.timestamp<1800000);if(Z.length>0){let X=new Map;Z.forEach((Q)=>{let J=X.get(Q.name)||[];J.push(Q),X.set(Q.name,J)});for(let[Q,J]of Array.from(X.entries())){let q=J.filter((G)=>G.status==="success").length;Y.push(`${Q}(${J.length}次,${q}成功)`)}}return Y.slice(0,5)}shouldCompress($,Y){return this.estimateCurrentTokens($)>Y*0.8}estimateCurrentTokens($){let Z=$.layers.conversation.messages.reduce((X,Q)=>X+Q.content.length,0);return Math.ceil(Z/4)}}class e1{defaultOptions;constructor($){this.defaultOptions={maxTokens:32000,maxMessages:50,timeWindow:86400000,priority:1,includeTools:!0,includeWorkspace:!0,...$}}filter($,Y){let Z={...this.defaultOptions,...Y},X={layers:{system:$.layers.system,session:$.layers.session,conversation:this.filterConversation($.layers.conversation,Z),tool:Z.includeTools?this.filterTools($.layers.tool,Z):{recentCalls:[],toolStates:{},dependencies:{}},workspace:Z.includeWorkspace?$.layers.workspace:{currentFiles:[],recentFiles:[],environment:{}}},metadata:{...$.metadata,lastUpdated:Date.now()}};return X.metadata.totalTokens=this.estimateTokens(X),X}filterConversation($,Y){let Z=[...$.messages];if(Y.timeWindow>0){let X=Date.now()-Y.timeWindow;Z=Z.filter((Q)=>Q.timestamp>=X||Q.role==="system")}if(Y.priority>1)Z=this.filterByPriority(Z,Y.priority);if(Y.maxMessages>0)Z=this.limitMessages(Z,Y.maxMessages);if(Y.maxTokens>0)Z=this.limitByTokens(Z,Y.maxTokens);return{messages:Z,summary:$.summary,topics:this.updateTopics(Z,$.topics),lastActivity:$.lastActivity}}filterTools($,Y){let Z=[...$.recentCalls];if(Y.timeWindow>0){let K=Date.now()-Y.timeWindow;Z=Z.filter((W)=>W.timestamp>=K)}let X=Z.filter((K)=>K.status==="success"),Q=Z.filter((K)=>K.status==="error"),J=Math.min(20,X.length),q=Math.min(10,Q.length);return{recentCalls:[...X.slice(-J),...Q.slice(-q)].sort((K,W)=>K.timestamp-W.timestamp),toolStates:$.toolStates,dependencies:$.dependencies}}filterByPriority($,Y){return $.filter((Z)=>{if(Z.role==="system")return!0;return this.calculateMessagePriority(Z)>=Y})}calculateMessagePriority($){let Y=1;if($.role==="system")Y+=3;else if($.role==="assistant")Y+=1;let Z=$.content.toLowerCase();if(["错误","警告","重要","关键","问题","解决"].some((J)=>Z.includes(J)))Y+=2;if(Z.includes("```")||Z.includes("function")||Z.includes("class"))Y+=1;let Q=(Date.now()-$.timestamp)/3600000;if(Q<1)Y+=2;else if(Q<6)Y+=1;return Y}limitMessages($,Y){if($.length<=Y)return $;let Z=$.filter((q)=>q.role==="system"),X=$.filter((q)=>q.role!=="system"),Q=Y-Z.length,J=Q>0?X.slice(-Q):[];return[...Z,...J].sort((q,G)=>q.timestamp-G.timestamp)}limitByTokens($,Y){if(Y<=0)return $;let Z=0,X=[];for(let Q=$.length-1;Q>=0;Q--){let J=$[Q],q=this.estimateMessageTokens(J);if(J.role==="system")if(Z+q<=Y)X.unshift(J),Z+=q;else{let G=this.compressMessage(J,Y-Z);X.unshift(G),Z+=this.estimateMessageTokens(G)}else if(Z+q<=Y)X.unshift(J),Z+=q;else break}return X.sort((Q,J)=>Q.timestamp-J.timestamp)}estimateMessageTokens($){return Math.ceil($.content.length/4)}compressMessage($,Y){let Z=Y*4;if($.content.length<=Z)return $;let X=$.content.substring(0,Z-3)+"...";return{...$,content:X,metadata:{...$.metadata,compressed:!0,originalLength:$.content.length}}}updateTopics($,Y){let Z=new Set(Y);for(let X of $)this.extractTopicsFromMessage(X).forEach((J)=>Z.add(J));return Array.from(Z).slice(0,10)}extractTopicsFromMessage($){let Y=$.content.toLowerCase(),Z=[];return["项目","功能","模块","组件","服务","接口","数据库","前端","后端","算法","架构","设计"].forEach((Q)=>{if(Y.includes(Q))Z.push(Q)}),Z}estimateTokens($){let Y=0;for(let X of $.layers.conversation.messages)Y+=this.estimateMessageTokens(X);let Z=JSON.stringify($.layers.system);if(Y+=Math.ceil(Z.length/4),$.layers.tool.recentCalls.length>0){let X=JSON.stringify($.layers.tool);Y+=Math.ceil(X.length/8)}return Y}static createPresets(){return{lightweight:new e1({maxTokens:1000,maxMessages:10,timeWindow:7200000,includeTools:!1,includeWorkspace:!1}),standard:new e1({maxTokens:4000,maxMessages:30,timeWindow:43200000,includeTools:!0,includeWorkspace:!0}),comprehensive:new e1({maxTokens:8000,maxMessages:100,timeWindow:86400000,includeTools:!0,includeWorkspace:!0}),debug:new e1({maxTokens:2000,maxMessages:20,timeWindow:21600000,priority:2,includeTools:!0,includeWorkspace:!1})}}}class n4{cache=new Map;maxSize;defaultTTL;constructor($=100,Y=300000){this.maxSize=$,this.defaultTTL=Y}set($,Y,Z){let X=Date.now(),Q={data:Y,timestamp:X,accessCount:0,lastAccess:X,ttl:Z||this.defaultTTL};if(this.cache.size>=this.maxSize&&!this.cache.has($))this.evictLeastUsed();this.cache.set($,Q)}get($){let Y=this.cache.get($);if(!Y)return null;let Z=Date.now();if(Z-Y.timestamp>Y.ttl)return this.cache.delete($),null;return Y.accessCount++,Y.lastAccess=Z,Y.data}has($){let Y=this.cache.get($);if(!Y)return!1;if(Date.now()-Y.timestamp>Y.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($,Y,Z){let X=`summary:${$}:${Y.length}`;this.set(X,{summary:Z,messageCount:Y.length,lastMessage:Y[Y.length-1]?.timestamp||0},600000)}getMessageSummary($,Y){let Z=`summary:${$}:${Y}`;return this.get(Z)}cacheToolResult($,Y,Z){let X=this.hashInput(Y),Q=`tool:${$}:${X}`;this.set(Q,Z,1800000)}getToolResult($,Y){let Z=this.hashInput(Y),X=`tool:${$}:${Z}`;return this.get(X)}cacheCompressedContext($,Y){let Z=`compressed:${$}`;this.set(Z,Y,900000)}getCompressedContext($){let Y=`compressed:${$}`;return this.get(Y)}getStats(){this.cleanExpired();let $=0,Y=0,Z=[];for(let[X,Q]of Array.from(this.cache.entries()))$+=Q.accessCount,Y+=this.estimateItemSize(Q),Z.push({key:X,accessCount:Q.accessCount,lastAccess:Q.lastAccess});return Z.sort((X,Q)=>Q.accessCount-X.accessCount),{size:this.cache.size,maxSize:this.maxSize,hitRate:$>0?$/($+this.cache.size):0,memoryUsage:Y,topKeys:Z.slice(0,10)}}cleanExpired(){let $=Date.now(),Y=[];for(let[Z,X]of Array.from(this.cache.entries()))if($-X.timestamp>X.ttl)Y.push(Z);Y.forEach((Z)=>this.cache.delete(Z))}evictLeastUsed(){let $=null,Y=1/0,Z=Date.now();for(let[X,Q]of Array.from(this.cache.entries())){let J=1/(Z-Q.lastAccess+1),q=Q.accessCount,G=J*q;if(G<Y)Y=G,$=X}if($)this.cache.delete($)}hashInput($){let Y=JSON.stringify($),Z=0;for(let X=0;X<Y.length;X++){let Q=Y.charCodeAt(X);Z=(Z<<5)-Z+Q,Z=Z&Z}return Math.abs(Z).toString(36)}estimateItemSize($){try{return JSON.stringify($).length*2}catch{return 1000}}setTTL($,Y){let Z=this.cache.get($);if(Z)return Z.ttl=Y,Z.timestamp=Date.now(),!0;return!1}getRemainingTTL($){let Y=this.cache.get($);if(!Y)return-1;let Z=Y.ttl-(Date.now()-Y.timestamp);return Math.max(0,Z)}warmup($){$.forEach(({key:Y,value:Z,ttl:X})=>{this.set(Y,Z,X)})}}class o4{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 Y=this.contextData.layers.conversation.messages;return this.recordAccess("messages"),Y.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($,Y){if(!this.contextData)throw Error("上下文数据未初始化");this.contextData.layers.tool.toolStates[$]=Y,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 Y=Math.floor(this.maxSize*0.8);this.contextData.layers.conversation.messages=$.slice(-Y)}}getMemoryUsage(){if(!this.contextData)return 0;return JSON.stringify(this.contextData).length}}N$();import{nanoid as R$}from"nanoid";import*as I1 from"node:fs/promises";import*as Z5 from"node:path";import*as l2 from"node:fs";import{createReadStream as PX}from"node:fs";import*as E0 from"node:fs/promises";import*as s4 from"node:path";import{createInterface as SX}from"node:readline";class J1{filePath;constructor($){this.filePath=$}async append($){try{await E0.mkdir(s4.dirname(this.filePath),{recursive:!0});let Y=JSON.stringify($)+`
|
|
983
|
+
`;await E0.appendFile(this.filePath,Y,"utf-8")}catch(Y){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,Y),Y}}async appendBatch($){try{await E0.mkdir(s4.dirname(this.filePath),{recursive:!0});let Y=$.map((Z)=>JSON.stringify(Z)).join(`
|
|
984
984
|
`)+`
|
|
985
|
-
`;await E0.appendFile(this.filePath,Y,"utf-8")}catch(Y){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,Y),Y}}async readAll(){try{if(!
|
|
986
|
-
`).filter((X)=>X.trim().length>0),Z=[];for(let X of Y)try{Z.push(JSON.parse(X))}catch(Q){console.warn(`[JSONLStore] 解析 JSON 行失败: ${X}`,Q)}return Z}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((Y,Z)=>{if(!
|
|
987
|
-
`).filter((X)=>X.trim().length>0).length;return{exists:!0,size:$.size,lineCount:Z}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await E0.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await E0.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class a4{projectPath;maxSessions;version;constructor($=process.cwd(),Y=100,Z="0.0.10"){this.projectPath=$,this.maxSessions=Y,this.version=Z}async initialize(){try{let $=F$(this.projectPath);await D1.mkdir($,{recursive:!0}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Y,Z,X=null,Q){try{let J=X1(this.projectPath,$),G=new J1(J),q={uuid:A$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:Y==="user"?"user":Y==="assistant"?"assistant":"system",cwd:this.projectPath,gitBranch:a1(this.projectPath),version:this.version,message:{role:Y,content:Z,...Q||{}}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,J),J}}async saveToolUse($,Y,Z,X=null){try{let Q=X1(this.projectPath,$),J=new J1(Q),G={uuid:A$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"tool_use",cwd:this.projectPath,gitBranch:a1(this.projectPath),version:this.version,message:{role:"assistant",content:""},tool:{id:A$(),name:Y,input:Z}};return await J.append(G),G.uuid}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Y,Z,X=null,Q){try{let J=X1(this.projectPath,$),G=new J1(J),q={uuid:A$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"tool_result",cwd:this.projectPath,gitBranch:a1(this.projectPath),version:this.version,message:{role:"assistant",content:""},toolResult:{id:Y,output:Z,error:Q}};return await G.append(q),q.uuid}catch(J){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,J),J}}async saveCompaction($,Y,Z,X=null){try{let Q=X1(this.projectPath,$),J=new J1(Q),G={uuid:A$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"system",subtype:"compact_boundary",cwd:this.projectPath,gitBranch:a1(this.projectPath),version:this.version,message:{role:"system",content:"=== 上下文压缩边界 ==="},compactMetadata:Z};await J.append(G),console.log("[PersistentStore] 保存压缩边界标记");let q={uuid:A$(),parentUuid:G.uuid,logicalParentUuid:X??void 0,sessionId:$,timestamp:new Date().toISOString(),type:"user",isCompactSummary:!0,cwd:this.projectPath,gitBranch:a1(this.projectPath),version:this.version,message:{role:"user",content:Y},compactMetadata:Z};return await J.append(q),console.log("[PersistentStore] 保存压缩总结消息"),q.uuid}catch(Q){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Q),Q}}async saveContext($,Y){try{let{conversation:Z}=Y.layers;for(let X of Z.messages)await this.saveMessage($,X.role,X.content,null)}catch(Z){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,Z)}}async saveSession($,Y){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,Y){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let Y=X1(this.projectPath,$),X=await new J1(Y).readAll();if(X.length===0)return null;let Q=X[0];return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Q.timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Y=X1(this.projectPath,$),X=await new J1(Y).readAll();if(X.length===0)return null;let Q=X.filter((q)=>["user","assistant","system"].includes(q.type)).map((q)=>({id:q.uuid,role:q.message.role,content:q.message.content,timestamp:new Date(q.timestamp).getTime()})),J=X[X.length-1],G=new Date(J.timestamp).getTime();return{messages:Q,topics:[],lastActivity:G}}catch{return null}}async listSessions(){try{let $=F$(this.projectPath);return(await D1.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Y=X1(this.projectPath,$),Z=new J1(Y);if(!(await Z.getStats()).exists)return null;let Q=await Z.readAll();if(Q.length===0)return null;let J=Q[Q.length-1];return{sessionId:$,lastActivity:new Date(J.timestamp).getTime(),messageCount:Q.filter((G)=>["user","assistant"].includes(G.type)).length,topics:[]}}catch{return null}}async deleteSession($){try{let Y=X1(this.projectPath,$);await new J1(Y).delete()}catch(Y){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Y)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let X=(await Promise.all($.map((Q)=>this.getSessionSummary(Q)))).filter((Q)=>Q!==null).sort((Q,J)=>J.lastActivity-Q.lastActivity).slice(this.maxSessions).map((Q)=>Q.sessionId);await Promise.all(X.map((Q)=>this.deleteSession(Q))),console.log(`[PersistentStore] 已清理 ${X.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Y=0;for(let Z of $){let X=X1(this.projectPath,Z),J=await new J1(X).getStats();Y+=J.size}return{totalSessions:$.length,totalSize:Y,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=F$(this.projectPath);await D1.mkdir($,{recursive:!0});let Y=e9.join($,".health-check");return await D1.writeFile(Y,"test","utf-8"),await D1.unlink(Y),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return l6()}}z$();class s${memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let Y=$.storage?.persistentPath||E1();this.options={storage:{maxMemorySize:1000,persistentPath:Y,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new r4(this.options.storage.maxMemorySize),this.persistent=new a4(process.cwd(),100),this.cache=new i4(this.options.storage.cacheSize,300000),this.compressor=new l4,this.filter=new t1(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($,Y={},Z={}){let X=Z.sessionId||this.generateSessionId(),Q=Date.now(),J={layers:{system:await this.createSystemContext(),session:{sessionId:X,userId:$,preferences:Y,configuration:Z,startTime:Q},conversation:{messages:[],topics:[],lastActivity:Q},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Q}};return this.memory.setContext(J),await this.persistent.saveContext(X,J),this.currentSessionId=X,console.log(`新会话已创建: ${X}`),X}async loadSession($){try{let Y=this.memory.getContext();if(!Y||Y.layers.session.sessionId!==$){let[Z,X]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!Z||!X)return!1;Y={layers:{system:await this.createSystemContext(),session:Z,conversation:X,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(Y)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Y){return console.error("加载会话失败:",Y),!1}}async addMessage($,Y,Z){if(!this.currentSessionId)throw Error("没有活动会话");let X={id:this.generateMessageId(),role:$,content:Y,timestamp:Date.now(),metadata:Z};this.memory.addMessage(X);let Q=this.memory.getContext();if(Q&&this.shouldCompress(Q))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($,Y,Z,X=null,Q){return this.persistent.saveMessage($,Y,Z,X,Q)}async saveToolUse($,Y,Z,X=null){return this.persistent.saveToolUse($,Y,Z,X)}async saveToolResult($,Y,Z,X=null,Q){return this.persistent.saveToolResult($,Y,Z,X,Q)}async saveCompaction($,Y,Z,X=null){return this.persistent.saveCompaction($,Y,Z,X)}updateToolState($,Y){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Y)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Y=this.memory.getContext();if(!Y)throw Error("没有可用的上下文数据");let Z=this.filter.filter(Y,$),X=this.shouldCompress(Z),Q;if(X){let J=this.hashContext(Z);if(Q=this.cache.getCompressedContext(J),!Q)Q=await this.compressor.compress(Z),this.cache.cacheCompressedContext(J,Q)}return{context:Z,compressed:Q,tokenCount:Q?Q.tokenCount:Z.metadata.totalTokens}}async searchSessions($,Y=10){let Z=await this.persistent.listSessions(),X=[];for(let Q of Z){let J=await this.persistent.getSessionSummary(Q);if(J){let G=this.calculateRelevance($,J.topics);if(G>0)X.push({sessionId:Q,summary:`${J.messageCount}条消息,主题:${J.topics.join("、")}`,lastActivity:J.lastActivity,relevanceScore:G})}}return X.sort((Q,J)=>J.relevanceScore-Q.relevanceScore).slice(0,Y)}getCachedToolResult($,Y){return this.cache.getToolResult($,Y)}async getStats(){let[$,Y,Z]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Y,storage:Z}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return $5()}generateMessageId(){return $5()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=process.cwd();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 Y=await this.compressor.compress($);$.layers.conversation.summary=Y.summary,this.memory.setContext($)}async saveCurrentSession(){if(!this.currentSessionId)return;let $=this.memory.getContext();if($)await this.persistent.saveContext(this.currentSessionId,$)}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Y=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return Y5.createHash("md5").update(Y).digest("hex")}calculateRelevance($,Y){let Z=$.toLowerCase(),X=0;for(let Q of Y)if(Z.includes(Q.toLowerCase())||Q.toLowerCase().includes(Z))X+=1;return X}}class o4{chatService;contextManager;memoryAdapter;constructor($,Y){this.chatService=$,this.contextManager=Y||new s$,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Y)=>{$.push(Y)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeSimpleTask($){let Y=[{role:"user",content:$.prompt}],Z=await this.chatService.chat(Y);return{taskId:$.id,content:Z.content,metadata:{executionMode:"simple",taskType:$.type}}}async executeParallelTask($){let Y=this.decomposeTask($),Z=await Promise.all(Y.map(async(Q)=>{try{return{success:!0,result:await this.executeSimpleTask(Q)}}catch(J){return{success:!1,error:J instanceof Error?J.message:"执行失败",taskId:Q.id}}})),X=this.combineSubTaskResults(Z);return{taskId:$.id,content:X,metadata:{executionMode:"parallel",taskType:$.type,subTaskCount:Y.length,failedSubTasks:Z.filter((Q)=>!Q.success).length}}}async executeSteeringTask($){let Y=await this.generateExecutionSteps($),Z="",X={};for(let Q=0;Q<Y.length;Q++){let J=Y[Q];try{let G=await this.executeStep(J,$);Z+=G.content+`
|
|
985
|
+
`;await E0.appendFile(this.filePath,Y,"utf-8")}catch(Y){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,Y),Y}}async readAll(){try{if(!l2.existsSync(this.filePath))return[];let Y=(await E0.readFile(this.filePath,"utf-8")).split(`
|
|
986
|
+
`).filter((X)=>X.trim().length>0),Z=[];for(let X of Y)try{Z.push(JSON.parse(X))}catch(Q){console.warn(`[JSONLStore] 解析 JSON 行失败: ${X}`,Q)}return Z}catch($){return console.error(`[JSONLStore] 读取文件失败: ${this.filePath}`,$),[]}}async readStream($){return new Promise((Y,Z)=>{if(!l2.existsSync(this.filePath)){Y();return}let X=PX(this.filePath,"utf-8"),Q=SX({input:X,crlfDelay:Number.POSITIVE_INFINITY});Q.on("line",async(J)=>{let q=J.trim();if(q.length===0)return;try{let G=JSON.parse(q);await $(G)}catch(G){console.warn(`[JSONLStore] 解析 JSON 行失败: ${q}`,G)}}),Q.on("close",()=>Y()),Q.on("error",Z),X.on("error",Z)})}async filter($){let Y=[];return await this.readStream((Z)=>{if($(Z))Y.push(Z)}),Y}async readLast($){return(await this.readAll()).slice(-$)}async getStats(){try{if(!l2.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let $=await E0.stat(this.filePath),Z=(await E0.readFile(this.filePath,"utf-8")).split(`
|
|
987
|
+
`).filter((X)=>X.trim().length>0).length;return{exists:!0,size:$.size,lineCount:Z}}catch($){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,$),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await E0.access(this.filePath),!0}catch{return!1}}async delete(){try{if(await this.exists())await E0.unlink(this.filePath)}catch($){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,$),$}}getFilePath(){return this.filePath}}class t4{projectPath;maxSessions;version;constructor($=process.cwd(),Y=100,Z="0.0.10"){this.projectPath=$,this.maxSessions=Y,this.version=Z}async initialize(){try{let $=z$(this.projectPath);await I1.mkdir($,{recursive:!0}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Y,Z,X=null,Q){try{let J=Q1(this.projectPath,$),q=new J1(J),G={uuid:R$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:Y==="user"?"user":Y==="assistant"?"assistant":"system",cwd:this.projectPath,gitBranch:o1(this.projectPath),version:this.version,message:{role:Y,content:Z,...Q||{}}};return await q.append(G),G.uuid}catch(J){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,J),J}}async saveToolUse($,Y,Z,X=null){try{let Q=Q1(this.projectPath,$),J=new J1(Q),q={uuid:R$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"tool_use",cwd:this.projectPath,gitBranch:o1(this.projectPath),version:this.version,message:{role:"assistant",content:""},tool:{id:R$(),name:Y,input:Z}};return await J.append(q),q.uuid}catch(Q){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,Q),Q}}async saveToolResult($,Y,Z,X=null,Q){try{let J=Q1(this.projectPath,$),q=new J1(J),G={uuid:R$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"tool_result",cwd:this.projectPath,gitBranch:o1(this.projectPath),version:this.version,message:{role:"assistant",content:""},toolResult:{id:Y,output:Z,error:Q}};return await q.append(G),G.uuid}catch(J){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,J),J}}async saveCompaction($,Y,Z,X=null){try{let Q=Q1(this.projectPath,$),J=new J1(Q),q={uuid:R$(),parentUuid:X,sessionId:$,timestamp:new Date().toISOString(),type:"system",subtype:"compact_boundary",cwd:this.projectPath,gitBranch:o1(this.projectPath),version:this.version,message:{role:"system",content:"=== 上下文压缩边界 ==="},compactMetadata:Z};await J.append(q),console.log("[PersistentStore] 保存压缩边界标记");let G={uuid:R$(),parentUuid:q.uuid,logicalParentUuid:X??void 0,sessionId:$,timestamp:new Date().toISOString(),type:"user",isCompactSummary:!0,cwd:this.projectPath,gitBranch:o1(this.projectPath),version:this.version,message:{role:"user",content:Y},compactMetadata:Z};return await J.append(G),console.log("[PersistentStore] 保存压缩总结消息"),G.uuid}catch(Q){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Q),Q}}async saveContext($,Y){try{let{conversation:Z}=Y.layers;for(let X of Z.messages)await this.saveMessage($,X.role,X.content,null)}catch(Z){console.warn(`[PersistentStore] 保存上下文失败 (session: ${$}):`,Z)}}async saveSession($,Y){console.warn("[PersistentStore] saveSession 方法已废弃,请使用 saveMessage")}async saveConversation($,Y){console.warn("[PersistentStore] saveConversation 方法已废弃,请使用 saveMessage")}async loadSession($){try{let Y=Q1(this.projectPath,$),X=await new J1(Y).readAll();if(X.length===0)return null;let Q=X[0];return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Q.timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Y=Q1(this.projectPath,$),X=await new J1(Y).readAll();if(X.length===0)return null;let Q=X.filter((G)=>["user","assistant","system"].includes(G.type)).map((G)=>({id:G.uuid,role:G.message.role,content:G.message.content,timestamp:new Date(G.timestamp).getTime()})),J=X[X.length-1],q=new Date(J.timestamp).getTime();return{messages:Q,topics:[],lastActivity:q}}catch{return null}}async listSessions(){try{let $=z$(this.projectPath);return(await I1.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let Y=Q1(this.projectPath,$),Z=new J1(Y);if(!(await Z.getStats()).exists)return null;let Q=await Z.readAll();if(Q.length===0)return null;let J=Q[Q.length-1];return{sessionId:$,lastActivity:new Date(J.timestamp).getTime(),messageCount:Q.filter((q)=>["user","assistant"].includes(q.type)).length,topics:[]}}catch{return null}}async deleteSession($){try{let Y=Q1(this.projectPath,$);await new J1(Y).delete()}catch(Y){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Y)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let X=(await Promise.all($.map((Q)=>this.getSessionSummary(Q)))).filter((Q)=>Q!==null).sort((Q,J)=>J.lastActivity-Q.lastActivity).slice(this.maxSessions).map((Q)=>Q.sessionId);await Promise.all(X.map((Q)=>this.deleteSession(Q))),console.log(`[PersistentStore] 已清理 ${X.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),Y=0;for(let Z of $){let X=Q1(this.projectPath,Z),J=await new J1(X).getStats();Y+=J.size}return{totalSessions:$.length,totalSize:Y,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=z$(this.projectPath);await I1.mkdir($,{recursive:!0});let Y=Z5.join($,".health-check");return await I1.writeFile(Y,"test","utf-8"),await I1.unlink(Y),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return a6()}}N$();class e${memory;persistent;cache;compressor;filter;options;currentSessionId=null;initialized=!1;constructor($={}){let Y=$.storage?.persistentPath||j1();this.options={storage:{maxMemorySize:1000,persistentPath:Y,cacheSize:100,compressionEnabled:!0,...$.storage},defaultFilter:{maxTokens:32000,maxMessages:50,timeWindow:86400000,...$.defaultFilter},compressionThreshold:$.compressionThreshold||6000,enableVectorSearch:$.enableVectorSearch||!1},this.memory=new o4(this.options.storage.maxMemorySize),this.persistent=new t4(process.cwd(),100),this.cache=new n4(this.options.storage.cacheSize,300000),this.compressor=new a4,this.filter=new e1(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($,Y={},Z={}){let X=Z.sessionId||this.generateSessionId(),Q=Date.now(),J={layers:{system:await this.createSystemContext(),session:{sessionId:X,userId:$,preferences:Y,configuration:Z,startTime:Q},conversation:{messages:[],topics:[],lastActivity:Q},tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Q}};return this.memory.setContext(J),await this.persistent.saveContext(X,J),this.currentSessionId=X,console.log(`新会话已创建: ${X}`),X}async loadSession($){try{let Y=this.memory.getContext();if(!Y||Y.layers.session.sessionId!==$){let[Z,X]=await Promise.all([this.persistent.loadSession($),this.persistent.loadConversation($)]);if(!Z||!X)return!1;Y={layers:{system:await this.createSystemContext(),session:Z,conversation:X,tool:{recentCalls:[],toolStates:{},dependencies:{}},workspace:await this.createWorkspaceContext()},metadata:{totalTokens:0,priority:1,lastUpdated:Date.now()}},this.memory.setContext(Y)}return this.currentSessionId=$,console.log(`会话已加载: ${$}`),!0}catch(Y){return console.error("加载会话失败:",Y),!1}}async addMessage($,Y,Z){if(!this.currentSessionId)throw Error("没有活动会话");let X={id:this.generateMessageId(),role:$,content:Y,timestamp:Date.now(),metadata:Z};this.memory.addMessage(X);let Q=this.memory.getContext();if(Q&&this.shouldCompress(Q))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($,Y,Z,X=null,Q){return this.persistent.saveMessage($,Y,Z,X,Q)}async saveToolUse($,Y,Z,X=null){return this.persistent.saveToolUse($,Y,Z,X)}async saveToolResult($,Y,Z,X=null,Q){return this.persistent.saveToolResult($,Y,Z,X,Q)}async saveCompaction($,Y,Z,X=null){return this.persistent.saveCompaction($,Y,Z,X)}updateToolState($,Y){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateToolState($,Y)}updateWorkspace($){if(!this.currentSessionId)throw Error("没有活动会话");this.memory.updateWorkspace($)}async getFormattedContext($){let Y=this.memory.getContext();if(!Y)throw Error("没有可用的上下文数据");let Z=this.filter.filter(Y,$),X=this.shouldCompress(Z),Q;if(X){let J=this.hashContext(Z);if(Q=this.cache.getCompressedContext(J),!Q)Q=await this.compressor.compress(Z),this.cache.cacheCompressedContext(J,Q)}return{context:Z,compressed:Q,tokenCount:Q?Q.tokenCount:Z.metadata.totalTokens}}async searchSessions($,Y=10){let Z=await this.persistent.listSessions(),X=[];for(let Q of Z){let J=await this.persistent.getSessionSummary(Q);if(J){let q=this.calculateRelevance($,J.topics);if(q>0)X.push({sessionId:Q,summary:`${J.messageCount}条消息,主题:${J.topics.join("、")}`,lastActivity:J.lastActivity,relevanceScore:q})}}return X.sort((Q,J)=>J.relevanceScore-Q.relevanceScore).slice(0,Y)}getCachedToolResult($,Y){return this.cache.getToolResult($,Y)}async getStats(){let[$,Y,Z]=await Promise.all([Promise.resolve(this.memory.getMemoryInfo()),Promise.resolve(this.cache.getStats()),this.persistent.getStorageStats()]);return{currentSession:this.currentSessionId,memory:$,cache:Y,storage:Z}}async cleanup(){if(this.currentSessionId)await this.saveCurrentSession();this.memory.clear(),this.cache.clear(),await this.persistent.cleanupOldSessions(),this.currentSessionId=null,console.log("上下文管理器资源清理完成")}generateSessionId(){return X5()}generateMessageId(){return X5()}async createSystemContext(){return{role:"AI助手",capabilities:["对话","工具调用","代码生成","文档分析"],tools:["文件操作","Git操作","代码分析"],version:"1.0.0"}}async createWorkspaceContext(){try{let $=process.cwd();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 Y=await this.compressor.compress($);$.layers.conversation.summary=Y.summary,this.memory.setContext($)}async saveCurrentSession(){if(!this.currentSessionId)return;let $=this.memory.getContext();if($)await this.persistent.saveContext(this.currentSessionId,$)}saveCurrentSessionAsync(){this.saveCurrentSession().catch(($)=>{console.warn("异步保存会话失败:",$)})}hashContext($){let Y=JSON.stringify({messageCount:$.layers.conversation.messages.length,lastMessage:$.layers.conversation.messages[$.layers.conversation.messages.length-1]?.id,toolCallCount:$.layers.tool.recentCalls.length});return Q5.createHash("md5").update(Y).digest("hex")}calculateRelevance($,Y){let Z=$.toLowerCase(),X=0;for(let Q of Y)if(Z.includes(Q.toLowerCase())||Q.toLowerCase().includes(Z))X+=1;return X}}class e4{chatService;contextManager;memoryAdapter;constructor($,Y){this.chatService=$,this.contextManager=Y||new e$,this.memoryAdapter=this.createMemoryAdapter()}createMemoryAdapter(){let $=[];return{getMessages:()=>[...$],addMessage:(Y)=>{$.push(Y)},clearContext:()=>{$.length=0},getContextSize:()=>$.length}}getContextManager(){return this.contextManager}getMemoryAdapter(){return this.memoryAdapter}async executeSimpleTask($){let Y=[{role:"user",content:$.prompt}],Z=await this.chatService.chat(Y);return{taskId:$.id,content:Z.content,metadata:{executionMode:"simple",taskType:$.type}}}async executeParallelTask($){let Y=this.decomposeTask($),Z=await Promise.all(Y.map(async(Q)=>{try{return{success:!0,result:await this.executeSimpleTask(Q)}}catch(J){return{success:!1,error:J instanceof Error?J.message:"执行失败",taskId:Q.id}}})),X=this.combineSubTaskResults(Z);return{taskId:$.id,content:X,metadata:{executionMode:"parallel",taskType:$.type,subTaskCount:Y.length,failedSubTasks:Z.filter((Q)=>!Q.success).length}}}async executeSteeringTask($){let Y=await this.generateExecutionSteps($),Z="",X={};for(let Q=0;Q<Y.length;Q++){let J=Y[Q];try{let q=await this.executeStep(J,$);Z+=q.content+`
|
|
988
988
|
|
|
989
|
-
`,X[`step_${Q}_type`]=J.type,X[`step_${Q}_result`]=
|
|
989
|
+
`,X[`step_${Q}_type`]=J.type,X[`step_${Q}_result`]=q}catch(q){throw Error(`步骤 ${J.id} 执行失败: ${q instanceof Error?q.message:"未知错误"}`)}}return{taskId:$.id,content:Z.trim(),metadata:{executionMode:"steering",taskType:$.type,steps:Y.length,...X}}}decomposeTask($){return[{...$,id:`${$.id}_sub1`,prompt:`${$.prompt} (子任务1: 分析和规划)`},{...$,id:`${$.id}_sub2`,prompt:`${$.prompt} (子任务2: 执行和验证)`}]}async generateExecutionSteps($){return[{id:`${$.id}_step1`,type:"llm",description:"理解任务要求和约束",status:"pending"},{id:`${$.id}_step2`,type:"tool",description:"准备执行环境和工具",status:"pending"},{id:`${$.id}_step3`,type:"llm",description:"执行任务并生成结果",status:"pending"}]}async executeStep($,Y){switch($.type){case"llm":return this.executeLlmStep($,Y);case"tool":return this.executeToolStep($,Y);default:throw Error(`未知的步骤类型: ${$.type}`)}}async executeLlmStep($,Y){let Z=`Step: ${$.description}
|
|
990
990
|
Task: ${Y.prompt}`;return{content:(await this.chatService.chat([{role:"user",content:Z}])).content,stepId:$.id}}async executeToolStep($,Y){return{content:`Tool step completed: ${$.description}`,stepId:$.id}}combineSubTaskResults($){return $.filter((Y)=>Y.success).map((Y)=>Y.result?.content||Y.content||"").join(`
|
|
991
991
|
|
|
992
|
-
`)}}var k=
|
|
992
|
+
`)}}var k=Y0("Agent");class k0{config;runtimeOptions;isInitialized=!1;activeTask;executionPipeline;systemPrompt;chatService;executionEngine;attachmentCollector;constructor($,Y={},Z){this.config=$,this.runtimeOptions=Y,this.executionPipeline=Z||this.createDefaultPipeline()}createDefaultPipeline(){let $=new r4,Y={...this.config.permissions,...this.runtimeOptions.permissions},Z=this.runtimeOptions.permissionMode??this.config.permissionMode??"default";return new i4($,{permissionConfig:Y,permissionMode:Z,maxHistorySize:1000})}static async create($={}){if(await A2(),d$().length===0)throw Error(`❌ 没有可用的模型配置
|
|
993
993
|
|
|
994
994
|
`+`请先使用以下命令添加模型:
|
|
995
995
|
`+` /model add
|
|
996
996
|
|
|
997
997
|
`+`或运行初始化向导:
|
|
998
|
-
`+" /init");let Z=F0();if(!Z)throw Error("❌ 配置未初始化,请确保应用已正确启动");V0.getInstance().validateConfig(Z);let Q=new
|
|
998
|
+
`+" /init");let Z=F0();if(!Z)throw Error("❌ 配置未初始化,请确保应用已正确启动");V0.getInstance().validateConfig(Z);let Q=new k0(Z,$);if(await Q.initialize(),$.toolWhitelist&&$.toolWhitelist.length>0)Q.applyToolWhitelist($.toolWhitelist);return Q}async initialize(){if(this.isInitialized)return;try{this.log("初始化Agent..."),await this.initializeSystemPrompt(),await this.registerBuiltinTools(),await this.loadSubagents();let $=R2();if(!$)throw Error("❌ 当前模型配置未找到");this.log(`\uD83D\uDE80 使用模型: ${$.name} (${$.model})`),this.chatService=M2({provider:$.provider,apiKey:$.apiKey,model:$.model,baseUrl:$.baseUrl,temperature:$.temperature??this.config.temperature,maxContextTokens:$.maxContextTokens??this.config.maxContextTokens,maxOutputTokens:this.config.maxOutputTokens,timeout:this.config.timeout}),this.executionEngine=new e4(this.chatService),this.attachmentCollector=new c6({cwd:process.cwd(),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 Y;if($.type==="parallel")Y=await this.executionEngine.executeParallelTask($);else if($.type==="steering")Y=await this.executionEngine.executeSteeringTask($);else Y=await this.executionEngine.executeSimpleTask($);return this.activeTask=void 0,this.log(`任务执行完成: ${$.id}`),Y}catch(Y){throw this.activeTask=void 0,this.error(`任务执行失败: ${$.id}`,Y),Y}}async chat($,Y,Z){if(!this.isInitialized)throw Error("Agent未初始化");let X=await this.processAtMentions($);if(Y){let q={signal:Y.signal,...Z},G=Y.permissionMode==="plan"?await this.runPlanLoop(X,Y,q):await this.runLoop(X,Y,q);if(!G.success){if(G.error?.type==="aborted")return"";throw Error(G.error?.message||"执行失败")}if(G.metadata?.targetMode&&Y.permissionMode==="plan"){let K=G.metadata.targetMode,W=G.metadata.planContent;k.debug(`\uD83D\uDD04 Plan 模式已批准,切换到 ${K} 模式并重新执行`),await e().setPermissionMode(K),k.debug(`✅ 权限模式已更新: ${K}`);let O={...Y,permissionMode:K},U=X;if(W)U=`${X}
|
|
999
999
|
|
|
1000
1000
|
<approved-plan>
|
|
1001
1001
|
${W}
|
|
1002
1002
|
</approved-plan>
|
|
1003
1003
|
|
|
1004
|
-
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`,k.debug(`\uD83D\uDCCB 已将 plan 内容注入到消息中 (${W.length} 字符)`);return this.runLoop(U,O,
|
|
1004
|
+
IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`,k.debug(`\uD83D\uDCCB 已将 plan 内容注入到消息中 (${W.length} 字符)`);return this.runLoop(U,O,q).then((H)=>{if(!H.success)throw Error(H.error?.message||"执行失败");return H.finalMessage||""})}return G.finalMessage||""}let Q={id:this.generateTaskId(),type:"simple",prompt:X};return(await this.executeTask(Q)).content}async runPlanLoop($,Y,Z){k.debug("\uD83D\uDD35 Processing Plan mode message...");let{prompt:X}=await j2({projectPath:process.cwd(),mode:"plan",includeEnvironment:!0}),Q=d6($);return this.executeLoop(Q,Y,Z,X)}async runLoop($,Y,Z){k.debug("\uD83D\uDCAC Processing enhanced chat message...");let X=E2(),Q=this.systemPrompt?`${X}
|
|
1005
1005
|
|
|
1006
1006
|
---
|
|
1007
1007
|
|
|
1008
|
-
${this.systemPrompt}`:X;return this.executeLoop($,Y,Z,Q)}async executeLoop($,Y,Z,X){if(!this.isInitialized)throw Error("Agent未初始化");let Q=Date.now();try{let J=this.executionPipeline.getRegistry(),
|
|
1008
|
+
${this.systemPrompt}`:X;return this.executeLoop($,Y,Z,Q)}async executeLoop($,Y,Z,X){if(!this.isInitialized)throw Error("Agent未初始化");let Q=Date.now();try{let J=this.executionPipeline.getRegistry(),q=Y.permissionMode,G=J.getFunctionDeclarationsByMode(q);if(q==="plan"){let A=J.getReadOnlyTools();k.debug(`\uD83D\uDD12 Plan mode: 使用只读工具 (${A.length} 个): ${A.map((V)=>V.name).join(", ")}`)}let W=Y.messages.length===0||!Y.messages.some((A)=>A.role==="system"),O=[];if(W&&X)O.push({role:"system",content:X});O.push(...Y.messages,{role:"user",content:$});let U=null;try{let A=this.executionEngine?.getContextManager();if(A&&Y.sessionId&&$.trim()!=="")U=await A.saveMessage(Y.sessionId,"user",$);else if($.trim()==="")k.debug("[Agent] 跳过保存空用户消息")}catch(A){k.warn("[Agent] 保存用户消息失败:",A)}let H=100,_=this.runtimeOptions.maxTurns??Z?.maxTurns??this.config.maxTurns??-1;if(_===0)return{success:!1,error:{type:"chat_disabled",message:`对话功能已被禁用 (maxTurns=0)。如需启用,请调整配置:
|
|
1009
1009
|
`+` • CLI 参数: blade --max-turns -1
|
|
1010
1010
|
`+` • 配置文件: ~/.blade/config.json 中设置 "maxTurns": -1
|
|
1011
|
-
`+" • 环境变量: export BLADE_MAX_TURNS=-1"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let z=_===-1?H:Math.min(_,H);if(this.config.debug)k.debug(`[MaxTurns] 配置值: ${_}, 实际限制: ${z}, 安全上限: ${H}`);let F=0,
|
|
1012
|
-
========== 发送给 LLM ==========`),k.debug("轮次:",F+1),k.debug("消息数量:",O.length),k.debug("最后 3 条消息:"),O.slice(-3).forEach((
|
|
1013
|
-
`);let E=this.filterOrphanToolMessages(O);if(E.length<O.length)k.debug(`\uD83D\uDD27 过滤掉 ${O.length-E.length} 条孤儿 tool 消息`);let R=await this.chatService.chat(E,
|
|
1011
|
+
`+" • 环境变量: export BLADE_MAX_TURNS=-1"},metadata:{turnsCount:0,toolCallsCount:0,duration:0}};let z=_===-1?H:Math.min(_,H);if(this.config.debug)k.debug(`[MaxTurns] 配置值: ${_}, 实际限制: ${z}, 安全上限: ${H}`);let F=0,w=[],L=0,N;while(!0){if(Z?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F,toolCallsCount:w.length,duration:Date.now()-Q}};let A=Y.messages.length;if(await this.checkAndCompactInLoop(O,Y,F,N,Z?.onCompacting)){k.debug(`[Agent] [轮次 ${F}] 检测到压缩发生,重建 messages 数组 (${A} → ${Y.messages.length} 条历史消息)`);let B=W&&X?1:0,D=B+A,C=O.slice(0,B),p=O.slice(D);O.length=0,O.push(...C,...Y.messages,...p),k.debug(`[Agent] [轮次 ${F}] messages 重建完成: ${C.length} system + ${Y.messages.length} 历史 + ${p.length} 新增 = ${O.length} 总计`)}if(F++,k.debug(`\uD83D\uDD04 [轮次 ${F}/${z}] 调用 LLM...`),Z?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F-1,toolCallsCount:w.length,duration:Date.now()-Q}};Z?.onTurnStart?.({turn:F,maxTurns:z}),k.debug(`
|
|
1012
|
+
========== 发送给 LLM ==========`),k.debug("轮次:",F+1),k.debug("消息数量:",O.length),k.debug("最后 3 条消息:"),O.slice(-3).forEach((B,D)=>{if(k.debug(` [${D}] ${B.role}:`,typeof B.content==="string"?B.content.substring(0,100)+(B.content.length>100?"...":""):JSON.stringify(B.content).substring(0,100)),B.tool_calls)k.debug(" tool_calls:",B.tool_calls.map((C)=>("function"in C)?C.function.name:C.type).join(", "))}),k.debug("可用工具数量:",G.length),k.debug(`================================
|
|
1013
|
+
`);let E=this.filterOrphanToolMessages(O);if(E.length<O.length)k.debug(`\uD83D\uDD27 过滤掉 ${O.length-E.length} 条孤儿 tool 消息`);let R=await this.chatService.chat(E,G,Z?.signal);if(R.usage){if(R.usage.totalTokens)L+=R.usage.totalTokens;if(N=R.usage.promptTokens,k.debug(`[Agent] LLM usage: prompt=${N}, completion=${R.usage.completionTokens}, total=${R.usage.totalTokens}`),Z?.onTokenUsage)Z.onTokenUsage({inputTokens:R.usage.promptTokens??0,outputTokens:R.usage.completionTokens??0,totalTokens:L,maxContextTokens:this.config.maxContextTokens})}if(Z?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F-1,toolCallsCount:w.length,duration:Date.now()-Q}};if(k.debug(`
|
|
1014
1014
|
========== LLM 返回 ==========`),k.debug("Content:",R.content),k.debug("Tool Calls:",JSON.stringify(R.toolCalls,null,2)),k.debug("当前权限模式:",Y.permissionMode),k.debug(`================================
|
|
1015
|
-
`),R.content&&R.content.trim()&&Z?.onContent)Z.onContent(R.content);if(!R.toolCalls||R.toolCalls.length===0){let
|
|
1016
|
-
========== 工具执行结果 ==========`),k.debug("工具名称:",
|
|
1017
|
-
`),y.metadata?.shouldExitLoop){k.debug("\uD83D\uDEAA 检测到退出循环标记,结束 Agent 循环");let
|
|
1015
|
+
`),R.content&&R.content.trim()&&Z?.onContent)Z.onContent(R.content);if(!R.toolCalls||R.toolCalls.length===0){let B=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i],D=R.content||"",C=B.some((M)=>M.test(D)),p="请执行你提到的操作,不要只是描述。",y=O.slice(-10).filter((M)=>M.role==="user"&&M.content==="请执行你提到的操作,不要只是描述。").length;if(C&&y<2){k.debug(`⚠️ 检测到意图未完成(重试 ${y+1}/2): "${D.slice(-50)}"`),O.push({role:"user",content:"请执行你提到的操作,不要只是描述。"});continue}k.debug("✅ 任务完成 - LLM 未请求工具调用");try{let M=this.executionEngine?.getContextManager();if(M&&Y.sessionId&&R.content)if(R.content.trim()!=="")U=await M.saveMessage(Y.sessionId,"assistant",R.content,U);else k.debug("[Agent] 跳过保存空响应(任务完成时)")}catch(M){k.warn("[Agent] 保存助手消息失败:",M)}return{success:!0,finalMessage:R.content,metadata:{turnsCount:F,toolCallsCount:w.length,duration:Date.now()-Q,tokensUsed:L}}}O.push({role:"assistant",content:R.content||"",tool_calls:R.toolCalls});try{let B=this.executionEngine?.getContextManager();if(B&&Y.sessionId&&R.content)if(R.content.trim()!=="")U=await B.saveMessage(Y.sessionId,"assistant",R.content,U);else k.debug("[Agent] 跳过保存空响应(工具调用时)")}catch(B){k.warn("[Agent] 保存助手工具调用消息失败:",B)}for(let B of R.toolCalls){if(B.type!=="function")continue;try{if(Z?.onToolStart)Z.onToolStart(B);let D=JSON.parse(B.function.arguments);if(D.todos&&typeof D.todos==="string")try{D.todos=JSON.parse(D.todos),this.log("[Agent] 自动修复了字符串化的 todos 参数")}catch{this.error("[Agent] todos 参数格式异常,将由验证层处理")}let C=null;try{let S=this.executionEngine?.getContextManager();if(S&&Y.sessionId)C=await S.saveToolUse(Y.sessionId,B.function.name,D,U)}catch(S){k.warn("[Agent] 保存工具调用失败:",S)}let p=Z?.signal;if(!p)k.error("[Agent] Missing signal in tool execution, this should not happen");k.debug("[Agent] Passing confirmationHandler to ExecutionPipeline.execute:",{toolName:B.function.name,hasHandler:!!Y.confirmationHandler,hasMethod:!!Y.confirmationHandler?.requestConfirmation,methodType:typeof Y.confirmationHandler?.requestConfirmation});let y=await this.executionPipeline.execute(B.function.name,D,{sessionId:Y.sessionId,userId:Y.userId||"default",workspaceRoot:Y.workspaceRoot||process.cwd(),signal:p,confirmationHandler:Y.confirmationHandler,permissionMode:Y.permissionMode});if(w.push(y),k.debug(`
|
|
1016
|
+
========== 工具执行结果 ==========`),k.debug("工具名称:",B.function.name),k.debug("成功:",y.success),k.debug("LLM Content:",y.llmContent),k.debug("Display Content:",y.displayContent),y.error)k.debug("错误:",y.error);if(k.debug(`==================================
|
|
1017
|
+
`),y.metadata?.shouldExitLoop){k.debug("\uD83D\uDEAA 检测到退出循环标记,结束 Agent 循环");let S=typeof y.llmContent==="string"?y.llmContent:"循环已退出";return{success:y.success,finalMessage:S,metadata:{turnsCount:F,toolCallsCount:w.length,duration:Date.now()-Q,shouldExitLoop:!0,targetMode:y.metadata.targetMode}}}if(Z?.onToolResult){k.debug("[Agent] Calling onToolResult:",{toolName:B.function.name,hasCallback:!0,resultSuccess:y.success,resultKeys:Object.keys(y),hasMetadata:!!y.metadata,metadataKeys:y.metadata?Object.keys(y.metadata):[],hasSummary:!!y.metadata?.summary,summary:y.metadata?.summary});try{await Z.onToolResult(B,y),k.debug("[Agent] onToolResult callback completed successfully")}catch(S){k.error("[Agent] onToolResult callback error:",S)}}else k.debug("[Agent] No onToolResult callback provided");try{let S=this.executionEngine?.getContextManager();if(S&&Y.sessionId)U=await S.saveToolResult(Y.sessionId,B.id,y.success?y.llmContent:void 0,C,y.success?void 0:y.error?.message)}catch(S){k.warn("[Agent] 保存工具结果失败:",S)}if(B.function.name==="TodoWrite"&&y.success&&y.llmContent){let S=typeof y.llmContent==="object"?y.llmContent:{},U1=Array.isArray(S)?S:S.todos||[];Z1().setTodos(U1)}let M=y.success?y.llmContent||y.displayContent||"":y.error?.message||"执行失败";if(typeof M==="object"&&M!==null)M=JSON.stringify(M,null,2);let i=typeof M==="string"?M:JSON.stringify(M);O.push({role:"tool",tool_call_id:B.id,name:B.function.name,content:i})}catch(D){k.error(`Tool execution failed for ${B.function.name}:`,D),O.push({role:"tool",tool_call_id:B.id,name:B.function.name,content:`Execution failed: ${D instanceof Error?D.message:"Unknown error"}`})}}if(Z?.signal?.aborted)return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:F,toolCallsCount:w.length,duration:Date.now()-Q}};if(F>=z){let B=_===-1||_>H,D=B?H:_;k.warn(`⚠️ 达到${B?"安全上限":"最大轮次限制"} ${D},自动压缩上下文...`);try{let C=this.chatService.getConfig(),p=await O$.compact(Y.messages,{trigger:"auto",modelName:C.model,maxContextTokens:C.maxContextTokens??this.config.maxContextTokens,apiKey:C.apiKey,baseURL:C.baseUrl,actualPreTokens:N});Y.messages=p.compactedMessages;let y=O.find((i)=>i.role==="system");if(O.length=0,y)O.push(y);O.push(...Y.messages);let M={role:"user",content:`This session is being continued from a previous conversation that ran out of context. The conversation is summarized above.
|
|
1018
1018
|
|
|
1019
|
-
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};O.push(
|
|
1019
|
+
Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`};O.push(M),Y.messages.push(M);try{let i=this.executionEngine?.getContextManager();if(i&&Y.sessionId)await i.saveCompaction(Y.sessionId,p.summary,{trigger:"auto",preTokens:p.preTokens,postTokens:p.postTokens,filesIncluded:p.filesIncluded},null)}catch(i){k.warn("[Agent] 保存压缩数据失败:",i)}F=0,k.info(`✅ 上下文已压缩 (${p.preTokens} → ${p.postTokens} tokens),重置轮次计数,继续对话`)}catch(C){k.error("[Agent] 压缩失败,使用降级策略:",C);let p=O.find((M)=>M.role==="system"),y=O.slice(-80);if(O.length=0,p&&!y.some((M)=>M.role==="system"))O.push(p);O.push(...y),Y.messages=O.filter((M)=>M.role!=="system"),F=0,k.warn(`⚠️ 降级压缩完成,保留 ${O.length} 条消息,继续对话`)}}}}catch(J){if(J instanceof Error&&(J.name==="AbortError"||J.message.includes("aborted")))return{success:!1,error:{type:"aborted",message:"任务已被用户中止"},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}};return k.error("Enhanced chat processing error:",J),{success:!1,error:{type:"api_error",message:`处理消息时发生错误: ${J instanceof Error?J.message:"未知错误"}`,details:J},metadata:{turnsCount:0,toolCallsCount:0,duration:Date.now()-Q}}}}async runAgenticLoop($,Y,Z){if(!this.isInitialized)throw Error("Agent未初始化");let X={messages:Y.messages,userId:Y.userId||"subagent",sessionId:Y.sessionId||`subagent_${Date.now()}`,workspaceRoot:Y.workspaceRoot||process.cwd(),signal:Y.signal,confirmationHandler:Y.confirmationHandler};return await this.runLoop($,X,Z)}filterOrphanToolMessages($){let Y=new Set;for(let Z of $)if(Z.role==="assistant"&&Z.tool_calls)for(let X of Z.tool_calls)Y.add(X.id);return $.filter((Z)=>{if(Z.role==="tool"){if(!Z.tool_call_id)return!1;return Y.has(Z.tool_call_id)}return!0})}async chatWithSystem($,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Z=[{role:"system",content:$},{role:"user",content:Y}];return(await this.chatService.chat(Z)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.executionPipeline?this.executionPipeline.getRegistry().getAll():[]}getToolRegistry(){return this.executionPipeline.getRegistry()}applyToolWhitelist($){let Y=this.executionPipeline.getRegistry(),X=Y.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of X)Y.unregister(Q.name);k.debug(`\uD83D\uDD12 Applied tool whitelist: ${$.join(", ")} (removed ${X.length} tools)`)}getToolStats(){let $=this.getAvailableTools(),Y=new Map;return $.forEach((Z)=>{let X=Y.get(Z.kind)||0;Y.set(Z.kind,X+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Y),toolNames:$.map((Z)=>Z.name)}}async destroy(){this.log("销毁Agent...");try{this.isInitialized=!1,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Y){k.debug(`[MainAgent] ${$}`,Y||"")}error($,Y){k.error(`[MainAgent] ${$}`,Y||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Y=this.runtimeOptions.appendSystemPrompt,Z=await j2({projectPath:process.cwd(),replaceDefault:$,append:Y,includeEnvironment:!1});if(this.systemPrompt=Z.prompt,this.systemPrompt)this.log("系统提示已加载"),k.debug(`[SystemPrompt] 加载来源: ${Z.sources.filter((X)=>X.loaded).map((X)=>X.name).join(", ")}`)}catch($){this.error("初始化系统提示失败",$)}}getSystemPrompt(){return this.systemPrompt}async checkAndCompactInLoop($,Y,Z,X,Q){if(X===void 0)return k.debug(`[Agent] [轮次 ${Z}] 压缩检查: 跳过(无历史 usage 数据)`),!1;let J=this.chatService.getConfig(),q=J.model,G=J.maxContextTokens??this.config.maxContextTokens,K=J.maxOutputTokens??this.config.maxOutputTokens,W=G-K,O=Math.floor(W*0.8);if(k.debug(`[Agent] [轮次 ${Z}] 压缩检查:`,{promptTokens:X,maxContextTokens:G,maxOutputTokens:K,availableForInput:W,threshold:O,shouldCompact:X>=O}),X<O)return!1;let U=Z===0?"[Agent] 触发自动压缩":`[Agent] [轮次 ${Z}] 触发循环内自动压缩`;k.debug(U),Q?.(!0);try{let H=await O$.compact(Y.messages,{trigger:"auto",modelName:q,maxContextTokens:G,apiKey:J.apiKey,baseURL:J.baseUrl,actualPreTokens:X});if(H.success)Y.messages=H.compactedMessages,k.debug(`[Agent] [轮次 ${Z}] 压缩完成: ${H.preTokens} → ${H.postTokens} tokens (-${((1-H.postTokens/H.preTokens)*100).toFixed(1)}%)`);else Y.messages=H.compactedMessages,k.warn(`[Agent] [轮次 ${Z}] 压缩使用降级策略: ${H.preTokens} → ${H.postTokens} tokens`);try{let _=this.executionEngine?.getContextManager();if(_&&Y.sessionId)await _.saveCompaction(Y.sessionId,H.summary,{trigger:"auto",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded},null),k.debug(`[Agent] [轮次 ${Z}] 压缩数据已保存到 JSONL`)}catch(_){k.warn(`[Agent] [轮次 ${Z}] 保存压缩数据失败:`,_)}return Q?.(!1),!0}catch(H){return Q?.(!1),k.error(`[Agent] [轮次 ${Z}] 压缩失败,继续执行`,H),!1}}async registerBuiltinTools(){try{let $=await t9({sessionId:"default",configDir:q5.join(J5.homedir(),".blade")});k.debug(`\uD83D\uDCE6 Registering ${$.length} builtin tools...`),this.executionPipeline.getRegistry().registerAll($);let Y=this.executionPipeline.getRegistry().getAll().length;k.debug(`✅ Builtin tools registered: ${Y} tools`),k.debug(`[Tools] ${this.executionPipeline.getRegistry().getAll().map((Z)=>Z.name).join(", ")}`),await this.registerMcpTools()}catch($){throw k.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await U9({interactive:!1,silent:!0,mcpConfig:this.runtimeOptions.mcpConfig,strictMcpConfig:this.runtimeOptions.strictMcpConfig});if($>0)k.debug(`✅ Loaded ${$} servers from .mcp.json`);let Y=H1();if(Object.keys(Y).length===0){k.debug("\uD83D\uDCE6 No MCP servers configured");return}let Z=I0.getInstance();for(let[Q,J]of Object.entries(Y))try{k.debug(`\uD83D\uDD0C Connecting to MCP server: ${Q}`),await Z.registerServer(Q,J),k.debug(`✅ MCP server "${Q}" connected`)}catch(q){k.warn(`⚠️ MCP server "${Q}" connection failed:`,q)}let X=await Z.getAvailableTools();if(X.length>0)this.executionPipeline.getRegistry().registerAll(X),k.debug(`✅ Registered ${X.length} MCP tools`),k.debug(`[MCP Tools] ${X.map((Q)=>Q.name).join(", ")}`)}catch($){k.warn("Failed to register MCP tools:",$)}}async loadSubagents(){if(N0.getAllNames().length>0){k.debug(`\uD83D\uDCE6 Subagents already loaded: ${N0.getAllNames().join(", ")}`);return}try{let $=N0.loadFromStandardLocations();if($>0)k.debug(`✅ Loaded ${$} subagents: ${N0.getAllNames().join(", ")}`);else k.debug("\uD83D\uDCE6 No subagents configured")}catch($){k.warn("Failed to load subagents:",$)}}async processAtMentions($){if(!this.attachmentCollector)return $;try{let Y=await this.attachmentCollector.collect($);if(Y.length===0)return $;return k.debug(`✅ Processed ${Y.length} @ file mentions`),this.appendAttachments($,Y)}catch(Y){return k.error("Failed to process @ mentions:",Y),$}}appendAttachments($,Y){let Z=[],X=[];for(let J of Y)if(J.type==="file"){let q=J.metadata?.lineRange?` (lines ${J.metadata.lineRange.start}${J.metadata.lineRange.end?`-${J.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${J.path}"${q?` range="${q}"`:""}>`,J.content,"</file>")}else if(J.type==="directory")Z.push(`<directory path="${J.path}">`,J.content,"</directory>");else if(J.type==="error")X.push(`- @${J.path}: ${J.error}`);let Q=$;if(Z.length>0)Q+=`
|
|
1020
1020
|
|
|
1021
1021
|
<system-reminder>
|
|
1022
1022
|
`,Q+=`The following files were mentioned with @ syntax:
|
|
@@ -1027,15 +1027,15 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1027
1027
|
|
|
1028
1028
|
⚠️ Some files could not be loaded:
|
|
1029
1029
|
`,Q+=X.join(`
|
|
1030
|
-
`);return Q}}function
|
|
1031
|
-
Run \x1B[36mnpm install -g ${
|
|
1032
|
-
`).filter((K)=>K.trim());if(Q.length===0)throw Error("空的 JSONL 文件");let J=JSON.parse(Q[0]),
|
|
1033
|
-
`).filter((Q)=>Q.trim()).map((Q)=>JSON.parse(Q));return this.convertJSONLToMessages(X)}static convertJSONLToMessages($){let Y=[],Z=-1;for(let Q=$.length-1;Q>=0;Q--)if($[Q].subtype==="compact_boundary"){Z=Q
|
|
1030
|
+
`);return Q}}function TX($){return $.command("* [message]","Print response and exit (useful for pipes)",(Y)=>{return Y.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"})},async(Y)=>{if(!Y.print)return;try{let Z=await k0.create({systemPrompt:Y.systemPrompt,appendSystemPrompt:Y.appendSystemPrompt}),X="",Q=Y._?.[0];if(Q&&typeof Q==="string")X=Q;else if(!process.stdin.isTTY){let q=[];for await(let G of process.stdin)q.push(G);X=Buffer.concat(q).toString("utf-8").trim()}else X="Hello";let J;if(Y.appendSystemPrompt)J=await Z.chatWithSystem(Y.appendSystemPrompt,X);else J=await Z.chat(X,{messages:[],userId:"cli-user",sessionId:`print-${Date.now()}`,workspaceRoot:process.cwd()});if(Y.outputFormat==="json")console.log(JSON.stringify({response:J,input:X,model:Y.model,timestamp:new Date().toISOString()},null,2));else if(Y.outputFormat==="stream-json")console.log(JSON.stringify({type:"response",content:J}));else console.log(J);process.exit(0)}catch(Z){console.error(`Error: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}})}async function G5(){if(process.argv.slice(2).findIndex((Z)=>Z==="--print"||Z==="-p")===-1)return!1;try{let Z=(await import("yargs")).default,{hideBin:X}=await import("yargs/helpers"),Q=Z(X(process.argv)).scriptName("blade").strict(!1);return TX(Q),await Q.parse(),!0}catch(Z){console.error(`Print mode error: ${Z instanceof Error?Z.message:"未知错误"}`),process.exit(1)}}import{execSync as dX}from"child_process";import*as $$ from"fs/promises";import*as C1 from"path";import{fileURLToPath as CX}from"url";var $8="blade-code",W5=C1.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),U5=C1.join(W5,"version-cache.json"),fX=86400000,hX=`https://registry.npmmirror.com/${$8}/latest`;async function xX(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;let $=CX(import.meta.url),Y=C1.dirname($),Z=[C1.join(Y,"..","..","package.json"),C1.join(Y,"..","package.json"),C1.join(process.cwd(),"package.json")];for(let X of Z)try{let Q=await $$.readFile(X,"utf-8"),J=JSON.parse(Q);if(J.name===$8&&J.version)return J.version}catch{}return"unknown"}catch{return"unknown"}}async function pX(){try{let $=await $$.readFile(U5,"utf-8"),Y=JSON.parse($);if(Date.now()-Y.checkedAt<fX)return Y;return null}catch{return null}}async function gX($){try{await $$.mkdir(W5,{recursive:!0}),await $$.writeFile(U5,JSON.stringify($,null,2))}catch{}}async function mX(){try{let $=new AbortController,Y=setTimeout(()=>$.abort(),5000),Z=await fetch(hX,{signal:$.signal,headers:{Accept:"application/json"}});if(clearTimeout(Y),!Z.ok)return null;return(await Z.json()).version||null}catch{return null}}function K5($,Y){let Z=$.split(".").map(Number),X=Y.split(".").map(Number);for(let Q=0;Q<Math.max(Z.length,X.length);Q++){let J=Z[Q]||0,q=X[Q]||0;if(J>q)return 1;if(J<q)return-1}return 0}async function Y8($=!1){let Y=await xX();if(Y==="unknown")return{currentVersion:Y,latestVersion:null,hasUpdate:!1,error:"Unable to determine current version"};if(!$){let X=await pX();if(X)return{currentVersion:Y,latestVersion:X.latestVersion,hasUpdate:K5(X.latestVersion,Y)>0}}let Z=await mX();if(Z)return await gX({latestVersion:Z,checkedAt:Date.now()}),{currentVersion:Y,latestVersion:Z,hasUpdate:K5(Z,Y)>0};return{currentVersion:Y,latestVersion:null,hasUpdate:!1,error:"Unable to check for updates"}}function uX($){if(!$.hasUpdate||!$.latestVersion)return null;return`\x1B[33m⚠️ Update available: ${$.currentVersion} → ${$.latestVersion}\x1B[0m
|
|
1031
|
+
Run \x1B[36mnpm install -g ${$8}@latest\x1B[0m to update`}async function O5(){try{let $=await Y8();return uX($)}catch{return null}}var H5={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("\uD83D\uDD0D Checking for updates...");try{let $=await Y8(!0);if(console.log(`\uD83D\uDCE6 Current version: ${$.currentVersion}`),$.error){console.log(`⚠️ ${$.error}`);return}if($.latestVersion)console.log(`\uD83D\uDCE6 Latest version: ${$.latestVersion}`);if($.hasUpdate&&$.latestVersion){console.log(""),console.log(`\x1B[33m⚠️ Update available: ${$.currentVersion} → ${$.latestVersion}\x1B[0m`),console.log(""),console.log("\uD83D\uDE80 Updating...");try{dX("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("✅ Update complete!")}catch(Y){console.error("❌ Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("✅ You are running the latest version of Blade")}catch($){console.error(`❌ Failed to check for updates: ${$ instanceof Error?$.message:"未知错误"}`),process.exit(1)}}};var k1=Y0("Service");class b${static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;constructor(){}static getInstance(){if(!b$.instance)b$.instance=new b$;return b$.instance}initialize(){if(this.initialized){k1.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}if(process.on("uncaughtException",($)=>{this.handleFatalError("uncaughtException",$)}),process.on("unhandledRejection",($)=>{let Y=$ instanceof Error?$:Error(String($));this.handleFatalError("unhandledRejection",Y)}),process.on("SIGTERM",()=>{k1.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.env.BLADE_NON_INTERACTIVE==="true")process.on("SIGINT",()=>{k1.info("[GracefulShutdown] 收到 SIGINT 信号(非交互模式)"),this.shutdown("SIGINT",0)});this.initialized=!0,k1.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup($){return this.cleanupHandlers.push($),k1.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let Y=this.cleanupHandlers.indexOf($);if(Y!==-1)this.cleanupHandlers.splice(Y,1),k1.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError($,Y){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${$}):`,Y);return}if(console.error(""),console.error("═".repeat(60)),console.error(`\uD83D\uDCA5 发生未捕获的错误 (${$})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",Y.message),console.error(""),Y.stack)console.error("堆栈跟踪:"),console.error(Y.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown($,1)}async shutdown($,Y=0){if(this.isShuttingDown){k1.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,k1.info(`[GracefulShutdown] 开始优雅退出 (原因: ${$})`);let Z=5000,X=new Promise((Q,J)=>{setTimeout(()=>{J(Error(`清理超时 (${Z}ms)`))},Z)});try{let Q=this.runCleanupHandlers();await Promise.race([Q,X]),k1.info("[GracefulShutdown] 所有清理函数执行完成")}catch(Q){console.error("[GracefulShutdown] 清理过程中发生错误:",Q)}finally{setTimeout(()=>{process.exit(Y)},100)}}async runCleanupHandlers(){let $=[...this.cleanupHandlers].reverse();for(let Y of $)try{let Z=Y();if(Z instanceof Promise)await Z}catch(Z){console.error("[GracefulShutdown] 清理函数执行失败:",Z)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var i2=()=>{return b$.getInstance()},_5=($)=>{return i2().registerCleanup($)},F5=()=>{i2().initialize()};import{useMemoizedFn as TG}from"ahooks";import{useEffect as CG,useState as fG}from"react";import{useMemoizedFn as g0}from"ahooks";import{Box as z2,useApp as EG}from"ink";import{useEffect as J$,useRef as V6}from"react";N$();import{readdir as z5,readFile as N5}from"node:fs/promises";import*as r2 from"node:path";var Y$=Y0("Service");class z1{static async listSessions(){let $=[],Y=r2.join(j1(),"projects");try{let Z=await z5(Y,{withFileTypes:!0});for(let X of Z){if(!X.isDirectory())continue;let Q=r2.join(Y,X.name),J=r6(X.name),G=(await z5(Q)).filter((K)=>K.endsWith(".jsonl"));for(let K of G){let W=r2.join(Q,K),O=K.replace(".jsonl","");try{let U=await this.extractMetadata(W,O,J);$.push(U)}catch(U){Y$.warn(`[SessionService] 跳过损坏的会话文件: ${W}`,U)}}}return $.sort((X,Q)=>new Date(Q.lastMessageTime).getTime()-new Date(X.lastMessageTime).getTime()),$}catch(Z){return Y$.error("[SessionService] 列出会话失败:",Z),[]}}static async extractMetadata($,Y,Z){let Q=(await N5($,"utf-8")).trim().split(`
|
|
1032
|
+
`).filter((K)=>K.trim());if(Q.length===0)throw Error("空的 JSONL 文件");let J=JSON.parse(Q[0]),q=JSON.parse(Q[Q.length-1]),G=Q.some((K)=>{try{let W=JSON.parse(K);return W.type==="tool_result"&&W.toolResult?.error}catch{return!1}});return{sessionId:Y,projectPath:Z,gitBranch:J.gitBranch,messageCount:Q.length,firstMessageTime:J.timestamp,lastMessageTime:q.timestamp,hasErrors:G,filePath:$}}static async loadSession($,Y){try{if(Y){let Q=this.getSessionFilePath(Y,$);return await this.loadSessionFromFile(Q)}let X=(await this.listSessions()).find((Q)=>Q.sessionId===$);if(!X)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(X.filePath)}catch(Z){throw Y$.error(`[SessionService] 加载会话失败 (${$}):`,Z),Z}}static async loadSessionFromFile($){let X=(await N5($,"utf-8")).trim().split(`
|
|
1033
|
+
`).filter((Q)=>Q.trim()).map((Q)=>JSON.parse(Q));return this.convertJSONLToMessages(X)}static convertJSONLToMessages($){let Y=[],Z=-1;for(let Q=$.length-1;Q>=0;Q--)if($[Q].subtype==="compact_boundary"){Z=Q,Y$.debug(`[SessionService] 检测到压缩边界 at index ${Q}`);break}let X=Z>=0?Z:0;for(let Q=X;Q<$.length;Q++){let J=$[Q];if(J.subtype==="compact_boundary"){Y$.debug("[SessionService] 跳过 compact_boundary 消息");continue}switch(J.type){case"user":case"assistant":case"system":{let q={role:J.message.role,content:typeof J.message.content==="string"?J.message.content:JSON.stringify(J.message.content)};if(J.isCompactSummary)Y$.debug("[SessionService] 加载压缩总结消息");Y.push(q);break}case"tool_result":if(J.toolResult){let q=J.toolResult.error?`Error: ${J.toolResult.error}`:typeof J.toolResult.output==="string"?J.toolResult.output:JSON.stringify(J.toolResult.output);Y.push({role:"tool",content:q,tool_call_id:J.toolResult.id,name:J.tool?.name})}break;case"tool_use":break;default:break}}if(Z>=0)Y$.debug(`[SessionService] 会话已压缩,跳过前 ${Z} 条历史,加载 ${Y.length} 条消息`);return Y}static getSessionFilePath($,Y){let{getSessionFilePath:Z}=(N$(),xY(V9));return Z($,Y)}}import{useShallow as NN}from"zustand/react/shallow";import{useStore as cX}from"zustand";function K0($){return cX(u$,$)}var lX=[],B5=()=>K0(($)=>$.session.sessionId),a2=()=>K0(($)=>$.session.messages),f1=()=>K0(($)=>$.session.isThinking),L5=()=>K0(($)=>$.session.isCompacting);var V$=()=>K0(($)=>$.session.actions);var w5=()=>K0(($)=>{let{inputTokens:Y,maxContextTokens:Z}=$.session.tokenUsage;if(Z<=0)return 100;let X=Math.max(0,100-Y/Z*100);return Math.round(X)});var A5=()=>K0(($)=>$.app.initializationStatus),R5=()=>K0(($)=>$.app.initializationError),n2=()=>K0(($)=>$.app.activeModal),b5=()=>K0(($)=>$.app.todos),V5=()=>K0(($)=>$.app.modelEditorTarget),D5=()=>K0(($)=>$.app.sessionSelectorData),I5=()=>K0(($)=>$.app.awaitingSecondCtrlC),D$=()=>K0(($)=>$.app.actions),o2=()=>K0(($)=>$.app.initializationStatus==="ready");var k5=()=>K0(($)=>$.app.todos.length>0);var I$=()=>K0(($)=>$.config.config?.permissionMode||"default"),v5=()=>K0(($)=>$.config.config?.models??lX),M5=()=>K0(($)=>{let Y=$.config.config;if(!Y)return;let Z=Y.currentModelId;return Y.models.find((Q)=>Q.id===Z)??Y.models[0]}),y5=()=>K0(($)=>$.config.config?.currentModelId);var i0=()=>K0(($)=>$.focus.currentFocus);var E5=()=>K0(($)=>$.focus.actions);var j5=()=>K0(($)=>$.command.isProcessing);var P5=()=>K0(($)=>$.command.actions),S5=()=>K0(($)=>$.command.pendingCommands);import{useMemoizedFn as G8}from"ahooks";import{useEffect as uQ,useRef as dQ}from"react";import xQ from"fuse.js";import iX from"node:os";import T5 from"node:path";var C5={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($,Y){let Z=$[0],X=o().addAssistantMessage;if(!Z)return{success:!0,message:"show_agents_manager",data:{action:"show_agents_manager"}};if(Z==="list"){let J=N0.getAllNames().map((U)=>N0.getSubagent(U)).filter((U)=>U!==void 0);if(J.length===0){let U=`\uD83D\uDCCB **Agents 管理**
|
|
1034
1034
|
|
|
1035
1035
|
`+`❌ 没有找到任何 agent 配置
|
|
1036
1036
|
|
|
1037
1037
|
`+`**配置文件位置:**
|
|
1038
|
-
`+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"\uD83D\uDCA1 使用 `/agents` 打开管理对话框";return X(U),{success:!0,message:"No agents found"}}let
|
|
1038
|
+
`+"- 项目级: `.blade/agents/`\n"+"- 用户级: `~/.blade/agents/`\n\n"+"\uD83D\uDCA1 使用 `/agents` 打开管理对话框";return X(U),{success:!0,message:"No agents found"}}let q=T5.join(process.cwd(),".blade","agents"),G=T5.join(iX.homedir(),".blade","agents"),K=J.filter((U)=>U.configPath?.startsWith(q)),W=J.filter((U)=>U.configPath?.startsWith(G)),O=`\uD83D\uDCCB **Agents 管理**
|
|
1039
1039
|
|
|
1040
1040
|
找到 **${J.length}** 个 agent:
|
|
1041
1041
|
|
|
@@ -1075,32 +1075,32 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1075
1075
|
`+"- 项目级 (`.blade/agents/`) - 最高优先级\n"+"- 用户级 (`~/.blade/agents/`) - 较低优先级\n\n"+`**可用工具:**
|
|
1076
1076
|
`+"- `Glob` - 文件搜索\n"+"- `Grep` - 内容搜索\n"+"- `Read` - 读取文件\n"+"- `Write` - 写入文件\n"+"- `Edit` - 编辑文件\n"+"- `Bash` - 执行命令\n"+"- 省略 `tools` 字段 = 继承所有工具\n\n"+"\uD83D\uDCA1 **提示:** 创建文件后,重启 Blade 使配置生效";return X(J),{success:!0,message:"Help displayed"}}if(Z==="create")return{success:!0,message:"show_agent_creation_wizard",data:{action:"show_agent_creation_wizard"}};let Q=`❌ 未知子命令: \`${Z}\`
|
|
1077
1077
|
|
|
1078
|
-
`+"使用 `/agents help` 查看可用命令";return X(Q),{success:!1,error:`Unknown subcommand: ${Z}`}}};async function
|
|
1078
|
+
`+"使用 `/agents help` 查看可用命令";return X(Q),{success:!1,error:`Unknown subcommand: ${Z}`}}};async function rX($,Y){let Z=o().addAssistantMessage;try{let X=F0(),Q=R2();if(!X||!Q)return{success:!1,error:"配置未初始化"};let J=s().session,q=J.messages,G=J.sessionId;if(!q||q.length===0)return Z("⚠️ 当前会话没有消息,无需压缩"),{success:!1,error:"没有消息需要压缩"};let K=q.map((_)=>({role:_.role,content:_.content})),W=r1.countTokens(K,Q.model),O=Q.maxContextTokens??X.maxContextTokens,U=(W/O*100).toFixed(1);if(Z("\uD83D\uDCCA **当前上下文统计**"),Z(` • 消息数量: ${K.length}`),Z(` • Token 数量: ${W.toLocaleString()}`),Z(` • Token 限制: ${O.toLocaleString()}`),Z(` • 使用率: ${U}%`),Z(""),W<O*0.5)return Z(`\uD83D\uDCA1 提示: 当前 token 使用率较低(${U}%),可以暂时不压缩。`),Z(" 系统会在达到 80% 时自动触发压缩。"),{success:!0,message:"无需压缩"};Z("⏳ **正在压缩上下文...**");let H=await O$.compact(K,{trigger:"manual",modelName:Q.model,maxContextTokens:O,apiKey:Q.apiKey,baseURL:Q.baseUrl});if(H.success){try{if(G)await new e$().saveCompaction(G,H.summary,{trigger:"manual",preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded},null),console.log("[/compact] 压缩数据已保存到 JSONL")}catch(_){console.warn("[/compact] 保存压缩数据失败:",_)}if(Z(""),Z("✅ **压缩完成!**"),Z(""),Z("\uD83D\uDCC9 **Token 变化**"),Z(` • 压缩前: ${H.preTokens.toLocaleString()} tokens`),Z(` • 压缩后: ${H.postTokens.toLocaleString()} tokens`),Z(` • 压缩率: ${((1-H.postTokens/H.preTokens)*100).toFixed(1)}%`),H.filesIncluded.length>0)Z(""),Z(`\uD83D\uDCC1 **包含文件** (${H.filesIncluded.length})`),H.filesIncluded.forEach((_,z)=>{Z(` ${z+1}. ${_}`)});return Z(""),Z("\uD83D\uDCA1 对话历史已压缩,但完整记录仍保存在会话文件中。"),{success:!0,message:"compact_completed",data:{compactedMessages:H.compactedMessages,boundaryMessage:H.boundaryMessage,summaryMessage:H.summaryMessage,preTokens:H.preTokens,postTokens:H.postTokens,filesIncluded:H.filesIncluded}}}else return Z(""),Z("⚠️ **压缩使用降级策略**"),Z(""),Z("\uD83D\uDCC9 **Token 变化**"),Z(` • 压缩前: ${H.preTokens.toLocaleString()} tokens`),Z(` • 压缩后: ${H.postTokens.toLocaleString()} tokens`),Z(""),Z("\uD83D\uDCA1 由于压缩过程出现错误,已使用简单截断策略。"),Z(` 错误信息: ${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(X){let Q=X instanceof Error?X.message:String(X);return Z(`❌ **压缩失败**: ${Q}`),{success:!1,error:Q}}}var aX={name:"compact",description:"手动压缩当前会话的上下文",fullDescription:"压缩当前对话历史,生成详细的技术总结,保留最近的消息。压缩后的上下文可以节省 token 使用量,同时保留关键信息。",usage:"/compact",examples:["/compact"],category:"context",handler:rX},f5=aX;function x5($){let Y=Math.floor((Date.now()-$.getTime())/1000);if(Y<60)return`${Y}s ago`;let Z=Math.floor(Y/60);if(Z<60)return`${Z}m ago`;let X=Math.floor(Z/60);if(X<24)return`${X}h ago`;return`${Math.floor(X/24)}d ago`}async function nX(){let $=o().addAssistantMessage,Y=I0.getInstance(),Z=H1();if(Object.keys(Z).length===0){$(`\uD83D\uDD0C **MCP 服务器状态**
|
|
1079
1079
|
|
|
1080
1080
|
⚠️ 暂无配置的 MCP 服务器
|
|
1081
1081
|
|
|
1082
|
-
\uD83D\uDCA1 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$("\uD83D\uDD0D 正在检查 MCP 服务器状态...");let X=Object.entries(Z).map(async([Q,J])=>{try{let
|
|
1082
|
+
\uD83D\uDCA1 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$("\uD83D\uDD0D 正在检查 MCP 服务器状态...");let X=Object.entries(Z).map(async([Q,J])=>{try{let q=Y.getServerStatus(Q);if(!q)await Y.registerServer(Q,J),q=Y.getServerStatus(Q);else if(q.status==="disconnected")await Y.connectServer(Q);return{name:Q,config:J,serverInfo:Y.getServerStatus(Q)}}catch(q){return{name:Q,config:J,serverInfo:null,error:q}}});await Promise.all(X),oX(Y.getAllServers())}function oX($){let Y=o().addAssistantMessage,Z=`\uD83D\uDD0C **MCP 服务器状态**
|
|
1083
1083
|
|
|
1084
|
-
`,X=0,Q=0,J=0;for(let[G
|
|
1084
|
+
`,X=0,Q=0,J=0;for(let[q,G]of $){let{config:K,status:W,connectedAt:O,lastError:U,tools:H}=G,_=W==="connected"?"✓":"✗",z=W==="connected"?"Connected":"Disconnected";if(W==="connected")X++,J+=H.length;else Q++;if(Z+=`\uD83D\uDCE6 **${q}**
|
|
1085
1085
|
`,Z+=` 状态: ${_} ${z}
|
|
1086
1086
|
`,Z+=` 类型: ${K.type}
|
|
1087
1087
|
`,K.type==="stdio")Z+=` 命令: ${K.command}${K.args?.length?" "+K.args.join(" "):""}
|
|
1088
1088
|
`;else Z+=` URL: ${K.url}
|
|
1089
1089
|
`;if(Z+=` 工具: ${H.length} 个
|
|
1090
|
-
`,O&&W==="connected")Z+=` 连接时间: ${
|
|
1090
|
+
`,O&&W==="connected")Z+=` 连接时间: ${x5(O)}
|
|
1091
1091
|
`;if(U&&W!=="connected")Z+=` 错误: ${U.message}
|
|
1092
1092
|
`;Z+=`
|
|
1093
1093
|
`}Z+=`**总计:**
|
|
1094
1094
|
`,Z+=`- 服务器: ${$.size} 个 (${X} 连接, ${Q} 断开)
|
|
1095
1095
|
`,Z+=`- 可用工具: ${J} 个
|
|
1096
1096
|
|
|
1097
|
-
`,Z+="\uD83D\uDCA1 使用 `/mcp <server-name>` 查看详细信息\n",Z+="\uD83D\uDCA1 使用 `/mcp tools` 查看所有工具",Y(Z)}async function
|
|
1097
|
+
`,Z+="\uD83D\uDCA1 使用 `/mcp <server-name>` 查看详细信息\n",Z+="\uD83D\uDCA1 使用 `/mcp tools` 查看所有工具",Y(Z)}async function sX($){let Y=o().addAssistantMessage,Z=I0.getInstance(),Q=H1()[$];if(!Q){Y(`❌ 服务器 "${$}" 不存在
|
|
1098
1098
|
|
|
1099
|
-
\uD83D\uDCA1 使用 \`/mcp\` 查看所有可用服务器`);return}try{let J=Z.getServerStatus($);if(!J)Y(`\uD83D\uDD0D 正在连接 ${$}...`),await Z.registerServer($,Q),J=Z.getServerStatus($);else if(J.status==="disconnected")Y(`\uD83D\uDD0D 正在重新连接 ${$}...`),await Z.connectServer($),J=Z.getServerStatus($);if(J)
|
|
1100
|
-
⚠️ 连接失败: ${J instanceof Error?J.message:"未知错误"}`)}}function
|
|
1099
|
+
\uD83D\uDCA1 使用 \`/mcp\` 查看所有可用服务器`);return}try{let J=Z.getServerStatus($);if(!J)Y(`\uD83D\uDD0D 正在连接 ${$}...`),await Z.registerServer($,Q),J=Z.getServerStatus($);else if(J.status==="disconnected")Y(`\uD83D\uDD0D 正在重新连接 ${$}...`),await Z.connectServer($),J=Z.getServerStatus($);if(J)tX($,J);else h5($,Q)}catch(J){h5($,Q),Y(`
|
|
1100
|
+
⚠️ 连接失败: ${J instanceof Error?J.message:"未知错误"}`)}}function tX($,Y){let Z=o().addAssistantMessage,{config:X,status:Q,connectedAt:J,lastError:q,tools:G}=Y,K=Q==="connected"?"✓":"✗",W=Q==="connected"?"Connected":"Disconnected",O=`\uD83D\uDCE6 **${$}**
|
|
1101
1101
|
|
|
1102
1102
|
`;if(O+=`**连接状态:**
|
|
1103
|
-
`,O+=` ${K} ${W}`,J&&Q==="connected")O+=` (连接于 ${
|
|
1103
|
+
`,O+=` ${K} ${W}`,J&&Q==="connected")O+=` (连接于 ${x5(J)})`;if(O+=`
|
|
1104
1104
|
|
|
1105
1105
|
`,O+=`**配置信息:**
|
|
1106
1106
|
`,O+=` 类型: ${X.type}
|
|
@@ -1111,14 +1111,14 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1111
1111
|
`,X.headers&&Object.keys(X.headers).length>0)O+=` Headers: ${Object.keys(X.headers).length} 个
|
|
1112
1112
|
`;if(X.timeout)O+=` 超时: ${X.timeout}ms
|
|
1113
1113
|
`;if(O+=`
|
|
1114
|
-
`,Q==="connected")if(O+=`**可用工具 (${
|
|
1115
|
-
`,
|
|
1116
|
-
`;else for(let U of
|
|
1114
|
+
`,Q==="connected")if(O+=`**可用工具 (${G.length}):**
|
|
1115
|
+
`,G.length===0)O+=` (无)
|
|
1116
|
+
`;else for(let U of G){if(O+=` • ${U.name}`,U.description)O+=` - ${U.description}`;O+=`
|
|
1117
1117
|
`}else O+=`**工具:**
|
|
1118
1118
|
⚠️ 服务器未连接,无法获取工具列表
|
|
1119
|
-
`;if(
|
|
1119
|
+
`;if(q)O+=`
|
|
1120
1120
|
**错误信息:**
|
|
1121
|
-
`,O+=` ${
|
|
1121
|
+
`,O+=` ${q.message}`;Z(O)}function h5($,Y){let Z=o().addAssistantMessage,X=`\uD83D\uDCE6 **${$}**
|
|
1122
1122
|
|
|
1123
1123
|
`;if(X+=`**连接状态:**
|
|
1124
1124
|
`,X+=` ⏸️ 未启动 (等待 Agent 连接)
|
|
@@ -1132,22 +1132,22 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1132
1132
|
`,Y.headers&&Object.keys(Y.headers).length>0)X+=` Headers: ${Object.keys(Y.headers).join(", ")}
|
|
1133
1133
|
`;if(Y.timeout)X+=` 超时: ${Y.timeout}ms
|
|
1134
1134
|
`;X+=`
|
|
1135
|
-
\uD83D\uDCA1 服务器将在 Agent 启动时自动连接`,Z(X)}async function
|
|
1135
|
+
\uD83D\uDCA1 服务器将在 Agent 启动时自动连接`,Z(X)}async function eX(){let $=o().addAssistantMessage,Y=I0.getInstance(),Z=H1();if(Object.keys(Z).length===0){$(`\uD83D\uDD27 **可用的 MCP 工具**
|
|
1136
1136
|
|
|
1137
1137
|
⚠️ 暂无配置的 MCP 服务器
|
|
1138
1138
|
|
|
1139
|
-
\uD83D\uDCA1 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$("\uD83D\uDD0D 正在检查 MCP 服务器并获取工具列表...");let X=Object.entries(Z).map(async([
|
|
1139
|
+
\uD83D\uDCA1 使用 \`blade mcp add\` 命令添加 MCP 服务器`);return}$("\uD83D\uDD0D 正在检查 MCP 服务器并获取工具列表...");let X=Object.entries(Z).map(async([G,K])=>{try{let W=Y.getServerStatus(G);if(!W)await Y.registerServer(G,K),W=Y.getServerStatus(G);else if(W.status==="disconnected")await Y.connectServer(G);return{name:G,config:K,serverInfo:Y.getServerStatus(G)}}catch(W){return{name:G,config:K,serverInfo:null,error:W}}});await Promise.all(X);let Q=Y.getAllServers(),J=`\uD83D\uDD27 **可用的 MCP 工具**
|
|
1140
1140
|
|
|
1141
|
-
`,
|
|
1141
|
+
`,q=0;for(let[G,K]of Q){let{status:W,tools:O}=K;if(J+=`**${G} (${O.length} 个工具):**
|
|
1142
1142
|
`,W!=="connected"){J+=` ⚠️ 服务器未连接
|
|
1143
1143
|
|
|
1144
1144
|
`;continue}if(O.length===0){J+=` (无)
|
|
1145
1145
|
|
|
1146
|
-
`;continue}
|
|
1146
|
+
`;continue}q+=O.length;for(let U of O){if(J+=` • ${U.name}`,U.description){let H=U.description.length>60?U.description.substring(0,57)+"...":U.description;J+=` - ${H}`}J+=`
|
|
1147
1147
|
`}J+=`
|
|
1148
|
-
`}J+=`**总计:** ${
|
|
1148
|
+
`}J+=`**总计:** ${q} 个工具可用`,$(J)}var $Q={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($,Y){try{if(console.log("[MCP Command] Received args:",$),$.length===0)return await nX(),{success:!0,message:"MCP 服务器概览已显示"};let Z=$[0];if(console.log("[MCP Command] Subcommand:",Z),Z==="tools")return await eX(),{success:!0,message:"MCP 工具列表已显示"};return await sX(Z),{success:!0,message:`服务器 "${Z}" 详情已显示`}}catch(Z){return{success:!1,error:`显示 MCP 信息失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}},p5=$Q;async function YQ($,Y){return{success:!0,message:"show_permissions_manager",data:{action:"show_permissions_manager"}}}var ZQ={name:"permissions",description:"管理项目的本地权限规则",fullDescription:"打开权限管理器,管理 .blade/settings.local.json 中的权限规则",usage:"/permissions",aliases:["perm"],category:"ui",handler:YQ},s2=ZQ;var XQ={name:"resume",description:"Resume a conversation",fullDescription:"恢复历史会话。可以指定 sessionId 直接恢复,或不带参数打开会话选择器",usage:"/resume [sessionId]",aliases:["r"],category:"Session",examples:["/resume - 打开会话选择器","/resume abc123xyz - 直接恢复指定的会话"],async handler($,Y){let Z=o().addAssistantMessage,X=o().restoreSession;if($.length>0){let Q=$[0];try{let J=await z1.loadSession(Q);if(J.length===0)return Z(`❌ 会话 \`${Q}\` 为空或无法加载`),{success:!1,error:"会话为空"};let q=J.filter((G)=>G.role!=="tool").map((G,K)=>({id:`restored-${Date.now()}-${K}`,role:G.role,content:typeof G.content==="string"?G.content:JSON.stringify(G.content),timestamp:Date.now()-(J.length-K)*1000}));return X(Q,q),Z(`✅ 已恢复会话 \`${Q}\`
|
|
1149
1149
|
|
|
1150
|
-
共 ${
|
|
1150
|
+
共 ${q.length} 条消息已加载,可以继续对话`),{success:!0,message:"session_restored",data:{sessionId:Q,messageCount:q.length}}}catch(J){let q=J instanceof Error?J.message:"未知错误";return Z(`❌ 加载会话失败: ${q}`),{success:!1,error:`加载会话失败: ${q}`}}}try{let Q=await z1.listSessions();if(Q.length===0)return Z("\uD83D\uDCED **没有找到历史会话**\n\n开始一次对话后,会话历史将自动保存到 `~/.blade/projects/`"),{success:!0,message:"没有可用会话"};return{success:!0,message:"show_session_selector",data:{sessions:Q}}}catch(Q){let J=Q instanceof Error?Q.message:"未知错误";return Z(`❌ 获取会话列表失败: ${J}`),{success:!1,error:`获取会话列表失败: ${J}`}}}},g5=XQ;var QQ={name:"help",description:"Show all available slash commands",fullDescription:"显示所有可用的 slash commands 及其使用方法",usage:"/help",aliases:["h"],async handler($,Y){return o().addAssistantMessage(`\uD83D\uDD27 **可用的 Slash Commands:**
|
|
1151
1151
|
|
|
1152
1152
|
**/init** - 分析当前项目并生成 BLADE.md 配置文件
|
|
1153
1153
|
**/git** - Git 仓库查询和 AI 辅助 (status/log/diff/review/commit)
|
|
@@ -1165,7 +1165,7 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1165
1165
|
- 在命令前加上 \`/\` 即可执行 slash command
|
|
1166
1166
|
- 普通消息会发送给 AI 助手处理
|
|
1167
1167
|
- 按 Ctrl+C 退出程序
|
|
1168
|
-
- 按 Ctrl+L 快速清屏`),{success:!0,message:"帮助信息已显示"}}}
|
|
1168
|
+
- 按 Ctrl+L 快速清屏`),{success:!0,message:"帮助信息已显示"}}},JQ={name:"clear",description:"Clear conversation history and free up context",fullDescription:"清除屏幕内容和对话历史",usage:"/clear",aliases:["cls"],async handler($,Y){return{success:!0,message:"clear_screen"}}},qQ={name:"version",description:"Show Blade Code version information",fullDescription:"显示 Blade Code 版本信息和构建详情",usage:"/version",aliases:["v"],async handler($,Y){try{let Q=`\uD83D\uDDE1️ **Blade Code v${(()=>{throw new Error("Cannot require module "+"../../../package.json");})().version||"1.3.0"}**
|
|
1169
1169
|
|
|
1170
1170
|
**构建信息:**
|
|
1171
1171
|
- Node.js: ${process.version}
|
|
@@ -1178,7 +1178,7 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1178
1178
|
- \uD83D\uDCDD 自定义系统提示
|
|
1179
1179
|
- \uD83C\uDFAF 多工具集成支持`;return o().addAssistantMessage(Q),{success:!0,message:"版本信息已显示"}}catch(Z){return o().addAssistantMessage(`\uD83D\uDDE1️ **Blade Code**
|
|
1180
1180
|
|
|
1181
|
-
版本信息获取失败`),{success:!0,message:"版本信息已显示"}}}},
|
|
1181
|
+
版本信息获取失败`),{success:!0,message:"版本信息已显示"}}}},GQ={name:"status",description:"Show current configuration status",fullDescription:"显示当前项目配置状态和环境信息",usage:"/status",async handler($,Y){let{cwd:Z}=Y,X=A0("path"),Q=A0("fs").promises;try{let J=X.join(Z,"BLADE.md"),q=await Q.access(J).then(()=>!0).catch(()=>!1),G=X.join(Z,"package.json"),K="未知项目",W="未知类型";try{let U=await Q.readFile(G,"utf-8"),H=JSON.parse(U);K=H.name||"未知项目";let _={...H.dependencies,...H.devDependencies};if(_.react)W="React 项目";else if(_.vue)W="Vue 项目";else if(_.next)W="Next.js 项目";else if(_.express)W="Express 项目";else W="Node.js 项目"}catch{}let O=`\uD83D\uDCCA **当前状态**
|
|
1182
1182
|
|
|
1183
1183
|
**项目信息:**
|
|
1184
1184
|
- 名称: ${K}
|
|
@@ -1186,13 +1186,13 @@ Please continue the conversation from where we left it off without asking the us
|
|
|
1186
1186
|
- 路径: ${Z}
|
|
1187
1187
|
|
|
1188
1188
|
**配置状态:**
|
|
1189
|
-
- BLADE.md: ${
|
|
1189
|
+
- BLADE.md: ${q?"✅ 已配置":"❌ 未配置 (使用 /init 创建)"}
|
|
1190
1190
|
|
|
1191
1191
|
**环境信息:**
|
|
1192
1192
|
- 工作目录: ${process.cwd()}
|
|
1193
1193
|
- Node.js: ${process.version}
|
|
1194
1194
|
|
|
1195
|
-
${!
|
|
1195
|
+
${!q?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文件":""}`;return o().addAssistantMessage(O),{success:!0,message:"状态信息已显示"}}catch(J){return{success:!1,error:`获取状态信息失败: ${J instanceof Error?J.message:"未知错误"}`}}}},KQ={name:"exit",description:"Exit the REPL",fullDescription:"退出 Blade Code 命令行界面",usage:"/exit",aliases:["quit","q"],async handler($,Y){return{success:!0,message:"exit_application"}}},WQ={name:"config",description:"Open config panel",fullDescription:"打开配置面板,管理 Blade Code 设置",usage:"/config [theme]",async handler($,Y){return o().addAssistantMessage(`⚙️ **配置面板**
|
|
1196
1196
|
|
|
1197
1197
|
**当前配置:**
|
|
1198
1198
|
- 主题: Default
|
|
@@ -1204,7 +1204,7 @@ ${!G?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文
|
|
|
1204
1204
|
- \`/config lang\` - 切换语言
|
|
1205
1205
|
- \`/config debug\` - 切换调试模式
|
|
1206
1206
|
|
|
1207
|
-
\uD83D\uDCA1 **提示:** 配置更改会在下次启动时生效`),{success:!0,message:"配置面板已显示"}}},
|
|
1207
|
+
\uD83D\uDCA1 **提示:** 配置更改会在下次启动时生效`),{success:!0,message:"配置面板已显示"}}},UQ={name:"context",description:"Visualize current context usage as a colored grid",fullDescription:"可视化显示当前上下文使用情况",usage:"/context",async handler($,Y){let Z=`\uD83D\uDCCA **上下文使用情况**
|
|
1208
1208
|
|
|
1209
1209
|
**当前会话:**
|
|
1210
1210
|
- 消息数量: ${Math.floor(Math.random()*20)+5}
|
|
@@ -1216,7 +1216,7 @@ ${!G?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文
|
|
|
1216
1216
|
- 系统提示: ${Math.floor(Math.random()*500)+200} tokens
|
|
1217
1217
|
- 项目上下文: ${Math.floor(Math.random()*1000)+300} tokens
|
|
1218
1218
|
|
|
1219
|
-
\uD83D\uDFE2 正常 \uD83D\uDFE1 中等 \uD83D\uDD34 高负载`;return o().addAssistantMessage(Z),{success:!0,message:"上下文信息已显示"}}},
|
|
1219
|
+
\uD83D\uDFE2 正常 \uD83D\uDFE1 中等 \uD83D\uDD34 高负载`;return o().addAssistantMessage(Z),{success:!0,message:"上下文信息已显示"}}},OQ={name:"cost",description:"Show the total cost and duration of the current session",fullDescription:"显示当前会话的成本和持续时间",usage:"/cost",async handler($,Y){let Z=`\uD83D\uDCB0 **会话成本统计**
|
|
1220
1220
|
|
|
1221
1221
|
**时间统计:**
|
|
1222
1222
|
- 开始时间: ${new Date().toLocaleTimeString()}
|
|
@@ -1231,8 +1231,8 @@ ${!G?"\n\uD83D\uDCA1 **建议:** 运行 `/init` 命令来创建项目配置文
|
|
|
1231
1231
|
- 当前会话: $${(Math.random()*0.5+0.1).toFixed(3)}
|
|
1232
1232
|
- 今日总计: $${(Math.random()*2+0.5).toFixed(3)}
|
|
1233
1233
|
|
|
1234
|
-
\uD83D\uDCA1 **提示:** 成本基于当前 AI 模型定价估算`;return o().addAssistantMessage(Z),{success:!0,message:"成本信息已显示"}}},
|
|
1235
|
-
`),w
|
|
1234
|
+
\uD83D\uDCA1 **提示:** 成本基于当前 AI 模型定价估算`;return o().addAssistantMessage(Z),{success:!0,message:"成本信息已显示"}}},m5={help:QQ,clear:JQ,version:qQ,status:GQ,exit:KQ,config:WQ,context:UQ,cost:OQ,permissions:s2,resume:g5,compact:f5,mcp:p5,agents:C5};import{execFile as u5,spawn as HQ}from"child_process";import{promisify as _Q}from"util";var rN=_Q(u5);async function $2($,Y){return new Promise((Z)=>{u5("git",Y,{cwd:$,maxBuffer:10485760},(X,Q,J)=>{Z({code:X?X.code||1:0,stdout:Q||"",stderr:J||""})})})}async function FQ($,Y){let{code:Z}=await $2($,Y);return Z===0}async function N1($,Y){let{stdout:Z}=await $2($,Y);return Z.trim()}async function Y2($){return FQ($,["rev-parse","--is-inside-work-tree"])}async function Z8($){return(await N1($,["status","--porcelain"])).length>0}async function d5($){return N1($,["branch","--show-current"])}async function X8($,Y=10){return N1($,["log","-n",String(Y),"--pretty=format:%s"])}async function c5($){let{code:Y,stderr:Z}=await $2($,["add","."]);if(Y!==0){let X=Z||"Unknown error";if(X.includes("fatal: pathspec"))throw Error("Failed to stage files: Invalid file path or pattern");throw Error(`Failed to stage files: ${X}`)}}async function l5($,Y,Z=!1,X){let Q=["commit","-m",Y];if(Z)Q.push("--no-verify");if(!X){let{code:J,stderr:q}=await $2($,Q);if(J!==0)throw Error(q||"Commit failed");return}return new Promise((J,q)=>{let G=HQ("git",Q,{cwd:$}),K="",W=(H,_,z)=>{let w=(z+H.toString()).split(`
|
|
1235
|
+
`),L=w.pop()||"";for(let N of w)if(N.trim())X(N,_);return L},O="",U="";G.stdout?.on("data",(H)=>{O=W(H,"stdout",O)}),G.stderr?.on("data",(H)=>{K+=H.toString(),U=W(H,"stderr",U)}),G.on("error",(H)=>{q(H)}),G.on("close",(H)=>{if(O.trim())X(O,"stdout");if(U.trim())X(U,"stderr");if(H===0)J();else q(Error(K||"Commit failed"))})})}async function i5($){let{cwd:Y}=$;if(!await Y2(Y))return null;let[Z,X,Q,J,q]=await Promise.all([N1(Y,["branch","--show-current"]),N1(Y,["rev-parse","--abbrev-ref","origin/HEAD"]).then((K)=>K.replace("origin/","")).catch(()=>"main"),N1(Y,["status","--short"]),N1(Y,["log","--oneline","-n","5"]),N1(Y,["config","user.email"])]),G=q?await N1(Y,["log","--author",q,"--oneline","-n","5"]):"";return{branch:Z,mainBranch:X,status:Q,log:J,author:q,authorLog:G}}function r5($){if(!$)return null;return`
|
|
1236
1236
|
Git repository status (snapshot at conversation start):
|
|
1237
1237
|
Current branch: ${$.branch}
|
|
1238
1238
|
Main branch (target for PRs): ${$.mainBranch}
|
|
@@ -1245,14 +1245,14 @@ ${$.log||"(no commits)"}
|
|
|
1245
1245
|
|
|
1246
1246
|
Your recent commits:
|
|
1247
1247
|
${$.authorLog||"(no recent commits)"}
|
|
1248
|
-
`.trim()}async function
|
|
1248
|
+
`.trim()}async function t2($){return N1($,["diff","--cached","--name-status"])}async function e2($){let Z=["diff","--cached","--",...[":!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:X,stdout:Q,stderr:J}=await $2($,Z);if(X!==0){let G=J||"Unknown error";if(G.includes("bad revision"))throw Error("Failed to get staged diff: Invalid Git revision or corrupt repository");if(G.includes("fatal: not a git repository"))throw Error("Not a Git repository");throw Error(`Failed to get staged diff: ${G}`)}let q=102400;if(Q.length>q)return Q.substring(0,q)+`
|
|
1249
1249
|
|
|
1250
|
-
[Diff truncated due to size. Total diff size: `+(Q.length/1024).toFixed(2)+"KB]";return Q}var
|
|
1250
|
+
[Diff truncated due to size. Total diff size: `+(Q.length/1024).toFixed(2)+"KB]";return Q}var zQ={name:"git",description:"Git 仓库查询和 AI 辅助",usage:"/git [status|log|diff|review|commit]",aliases:["g"],examples:["/git","/git status","/git log 10","/git review","/git commit"],async handler($,Y){let{cwd:Z}=Y,X=$[0]?.toLowerCase();if(!await Y2(Z))return{success:!1,error:"❌ 当前目录不在 Git 仓库中"};try{switch(X){case"status":case"s":return a5(Z);case"log":case"l":return NQ(Z,$[1]);case"diff":case"d":return BQ(Z);case"review":case"r":return LQ(Z);case"commit":case"c":return wQ(Z);default:return a5(Z)}}catch(Q){return{success:!1,error:`Git 命令失败: ${Q instanceof Error?Q.message:"未知错误"}`}}}};async function a5($){let Y=await i5({cwd:$});if(!Y)return{success:!1,error:"无法获取 Git 状态"};let Z=r5(Y);if(Z)o().addAssistantMessage(`\`\`\`
|
|
1251
1251
|
${Z}
|
|
1252
|
-
\`\`\``);else o().addAssistantMessage("\uD83D\uDCED 无法获取 Git 状态信息");return{success:!0}}async function
|
|
1252
|
+
\`\`\``);else o().addAssistantMessage("\uD83D\uDCED 无法获取 Git 状态信息");return{success:!0}}async function NQ($,Y){let Z=Math.min(Math.max(parseInt(Y||"5",10)||5,1),50),X=await X8($,Z);if(!X)o().addAssistantMessage("\uD83D\uDCED 暂无提交记录");else o().addAssistantMessage(`**最近 ${Z} 条提交:**
|
|
1253
1253
|
\`\`\`
|
|
1254
1254
|
${X}
|
|
1255
|
-
\`\`\``);return{success:!0}}async function
|
|
1255
|
+
\`\`\``);return{success:!0}}async function BQ($){let Y=await t2($);if(!Y)return o().addAssistantMessage("\uD83D\uDCED 暂存区为空,没有待提交的改动"),{success:!0};let Z=await e2($),X=`**暂存文件:**
|
|
1256
1256
|
\`\`\`
|
|
1257
1257
|
${Y}
|
|
1258
1258
|
\`\`\`
|
|
@@ -1260,7 +1260,7 @@ ${Y}
|
|
|
1260
1260
|
**Diff:**
|
|
1261
1261
|
\`\`\`diff
|
|
1262
1262
|
${Z||"(无差异)"}
|
|
1263
|
-
\`\`\``;return o().addAssistantMessage(X),{success:!0}}async function
|
|
1263
|
+
\`\`\``;return o().addAssistantMessage(X),{success:!0}}async function LQ($){let Y=o().addAssistantMessage;if(!await Z8($))return Y("\uD83D\uDCED 没有未提交的改动,无需 Review"),{success:!0};Y("\uD83D\uDD0D 正在分析代码改动...");let Z=await t2($),X=await e2($);if(!X&&!Z)return Y("\uD83D\uDCA1 请先使用 `git add` 暂存要 Review 的文件"),{success:!0};let Q=await k0.create(),J=s().session.sessionId,q=`请对以下 Git 改动进行 Code Review。
|
|
1264
1264
|
|
|
1265
1265
|
**暂存文件:**
|
|
1266
1266
|
${Z||"(无)"}
|
|
@@ -1276,7 +1276,7 @@ ${X||"(无差异)"}
|
|
|
1276
1276
|
3. **潜在问题**:指出可能的 bug、安全问题或性能问题
|
|
1277
1277
|
4. **改进建议**:具体的代码改进建议
|
|
1278
1278
|
|
|
1279
|
-
如果改动很好,也请说明优点。保持简洁专业。`,
|
|
1279
|
+
如果改动很好,也请说明优点。保持简洁专业。`,G=await Q.chat(q,{messages:[],userId:"cli-user",sessionId:J||"git-review",workspaceRoot:$});return Y(G),{success:!0}}async function wQ($){let Y=o().addAssistantMessage;if(!await Z8($))return Y("\uD83D\uDCED 没有未提交的改动"),{success:!0};Y("\uD83D\uDCE6 暂存所有改动..."),await c5($);let Z=await t2($),X=await e2($);if(!Z)return Y("\uD83D\uDCED 没有需要提交的改动"),{success:!0};Y("\uD83E\uDD16 正在生成 commit message...");let Q=await X8($,5),J=await k0.create(),q=s().session.sessionId,G=`请根据以下 Git 改动生成一条简洁的 commit message。
|
|
1280
1280
|
|
|
1281
1281
|
**暂存文件:**
|
|
1282
1282
|
${Z}
|
|
@@ -1299,16 +1299,16 @@ ${Q||"(无历史提交)"}
|
|
|
1299
1299
|
feat: add user authentication module
|
|
1300
1300
|
|
|
1301
1301
|
- Add login/logout functionality
|
|
1302
|
-
- Implement JWT token handling`,W=(await J.chat(
|
|
1302
|
+
- Implement JWT token handling`,W=(await J.chat(G,{messages:[],userId:"cli-user",sessionId:q||"git-commit",workspaceRoot:$})).replace(/^```\w*\n?/,"").replace(/\n?```$/,"").trim();Y(`**生成的 Commit Message:**
|
|
1303
1303
|
\`\`\`
|
|
1304
1304
|
${W}
|
|
1305
|
-
\`\`\``);try{await
|
|
1306
|
-
`)[0]||"unknown",X=[];try{let{stdout:Q}=await
|
|
1307
|
-
`).filter(Boolean)}catch{}return{name:"VS Code",version:Z,extensions:X}}catch{return null}}static isRunningInIdeTerminal(){let $=process.env.TERM_PROGRAM,Y=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;return $==="vscode"||!!Y||!!Z}}import{exec as
|
|
1308
|
-
`)[0]||"unknown"}}catch{return null}}static async checkVsCodeInsiders(){try{let{stdout:$}=await
|
|
1309
|
-
`)[0]||"unknown"}}catch{return null}}static async checkCursor(){try{let{stdout:$}=await
|
|
1310
|
-
`)[0]||"unknown"}}catch{return null}}}var
|
|
1311
|
-
`)}async function
|
|
1305
|
+
\`\`\``);try{await l5($,W),Y("✅ 提交成功!")}catch(O){let U=O instanceof Error?O.message:"未知错误";return Y(`❌ 提交失败: ${U}`),{success:!1,error:U}}return{success:!0}}var n5=zQ;import{existsSync as DQ,readFileSync as IQ}from"fs";import{homedir as kQ}from"os";import{join as vQ}from"path";import{exec as AQ}from"child_process";import{promisify as RQ}from"util";var o5=RQ(AQ);class Q8{static async detectIde(){let $=process.env.TERM_PROGRAM,Y=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;if($==="vscode"||Y||Z)return await this.detectVsCode();let X=await this.detectVsCode();if(X)return X;return null}static async detectVsCode(){try{let{stdout:$}=await o5("code --version"),Z=$.trim().split(`
|
|
1306
|
+
`)[0]||"unknown",X=[];try{let{stdout:Q}=await o5("code --list-extensions");X=Q.trim().split(`
|
|
1307
|
+
`).filter(Boolean)}catch{}return{name:"VS Code",version:Z,extensions:X}}catch{return null}}static isRunningInIdeTerminal(){let $=process.env.TERM_PROGRAM,Y=process.env.VSCODE_INJECTION,Z=process.env.VSCODE_IPC_HOOK;return $==="vscode"||!!Y||!!Z}}import{exec as bQ}from"child_process";import{promisify as VQ}from"util";var $6=VQ(bQ);class Z2{static async getInstalledIdes(){let $=[],Y=await this.checkVsCode();if(Y)$.push(Y);let Z=await this.checkVsCodeInsiders();if(Z)$.push(Z);let X=await this.checkCursor();if(X)$.push(X);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 Y;switch($){case"vscode":Y="code --install-extension blade-code.blade-code";break;case"vscode-insiders":Y="code-insiders --install-extension blade-code.blade-code";break;case"cursor":Y="cursor --install-extension blade-code.blade-code";break;default:return{success:!1,message:"不支持的 IDE: "+$}}try{return await $6(Y),{success:!0,message:"扩展安装成功"}}catch(Z){return{success:!1,message:"安装失败: "+(Z instanceof Error?Z.message:"未知错误")}}}static async checkVsCode(){try{let{stdout:$}=await $6("code --version");return{id:"vscode",name:"VS Code",version:$.trim().split(`
|
|
1308
|
+
`)[0]||"unknown"}}catch{return null}}static async checkVsCodeInsiders(){try{let{stdout:$}=await $6("code-insiders --version");return{id:"vscode-insiders",name:"VS Code Insiders",version:$.trim().split(`
|
|
1309
|
+
`)[0]||"unknown"}}catch{return null}}static async checkCursor(){try{let{stdout:$}=await $6("cursor --version");return{id:"cursor",name:"Cursor",version:$.trim().split(`
|
|
1310
|
+
`)[0]||"unknown"}}catch{return null}}}var s5=vQ(kQ(),".blade","ide-port");var k$="disconnected",J8=null,q8=null;function MQ(){switch(k$){case"connected":return{type:"info",content:`\uD83D\uDFE2 已连接到 ${J8||"IDE"} (端口: ${q8})`};case"connecting":return{type:"info",content:"\uD83D\uDFE1 正在连接..."};default:return{type:"error",content:"\uD83D\uDD34 未连接到 IDE"}}}function t5(){try{if(DQ(s5)){let $=IQ(s5,"utf-8");return JSON.parse($)}}catch{}return null}function e5(){let $=process.env.BLADE_IDE_PORT;if($)return parseInt($,10);let Y=t5();if(Y)return Y.port;return null}async function yQ(){let $=[],Y=MQ();$.push(Y.content),$.push(""),$.push("\uD83D\uDCE6 已安装的 IDE:");let Z=await Z2.getInstalledIdes();if(Z.length===0)$.push(" (未检测到支持的 IDE)");else for(let q of Z)$.push(` • ${q.name} ${q.version}`);$.push("");let X=await Q8.detectIde();if(X){if($.push(`\uD83D\uDDA5️ 当前环境: ${X.name} ${X.version}`),X.extensions.length>0)$.push(` 已安装扩展: ${X.extensions.length} 个`)}let Q=e5(),J=t5();if(Q){if($.push(`\uD83D\uDD0C IDE 端口: ${Q}`),J&&J.workspaceFolders.length>0)$.push(` 工作区: ${J.workspaceFolders[0]}`)}else $.push(""),$.push("\uD83D\uDCA1 提示: 在 VS Code 中安装 Blade Code 插件后,运行 /ide connect 连接");return $.join(`
|
|
1311
|
+
`)}async function EQ(){let $=e5();if(!$)return`❌ 未检测到 IDE 端口
|
|
1312
1312
|
|
|
1313
1313
|
请确保:
|
|
1314
1314
|
1. 已在 VS Code 中安装 Blade Code 插件
|
|
@@ -1316,25 +1316,25 @@ ${W}
|
|
|
1316
1316
|
3. 在 VS Code 终端中运行 blade
|
|
1317
1317
|
|
|
1318
1318
|
或手动设置端口:
|
|
1319
|
-
export BLADE_IDE_PORT=9527`;
|
|
1319
|
+
export BLADE_IDE_PORT=9527`;k$="connecting";try{let Z=new(await import("ws")).default(`ws://127.0.0.1:${$}`);return await new Promise((X,Q)=>{let J=setTimeout(()=>{Z.close(),Q(Error("连接超时"))},5000);Z.on("open",()=>{clearTimeout(J),k$="connected",q8=$,J8="VS Code",Z.close(),X()}),Z.on("error",(q)=>{clearTimeout(J),Q(q)})}),`✅ 成功连接到 IDE (端口: ${$})
|
|
1320
1320
|
|
|
1321
1321
|
现在可以使用以下功能:
|
|
1322
1322
|
• 在 IDE 中打开文件
|
|
1323
1323
|
• 获取当前选中的代码
|
|
1324
|
-
• 查看打开的编辑器列表`}catch(Y){return
|
|
1324
|
+
• 查看打开的编辑器列表`}catch(Y){return k$="disconnected",`❌ 连接失败: ${Y instanceof Error?Y.message:"未知错误"}
|
|
1325
1325
|
|
|
1326
1326
|
请检查:
|
|
1327
1327
|
1. VS Code 插件是否正在运行
|
|
1328
1328
|
2. 端口 ${$} 是否正确
|
|
1329
|
-
3. 防火墙设置`}}async function
|
|
1329
|
+
3. 防火墙设置`}}async function jQ(){let $=[];if($.push("\uD83D\uDCE6 安装 Blade Code VS Code 插件"),$.push(""),!await Z2.isIdeInstalled("vscode"))return $.push("❌ 未检测到 VS Code"),$.push(""),$.push("请先安装 VS Code:"),$.push(" https://code.visualstudio.com/"),$.join(`
|
|
1330
1330
|
`);return $.push("✅ 检测到 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 vscode-extension && pnpm install && pnpm run package"),$.push(" code --install-extension blade-code-0.0.1.vsix"),$.push(""),$.push("安装完成后,在 VS Code 终端中运行 blade 即可自动连接"),$.join(`
|
|
1331
|
-
`)}async function
|
|
1331
|
+
`)}async function PQ(){if(k$==="disconnected")return"⚠️ 当前未连接到任何 IDE";return k$="disconnected",J8=null,q8=null,"✅ 已断开与 IDE 的连接"}var SQ={name:"ide",aliases:[],description:"Manage IDE integrations and show status",usage:"/ide [status|connect|install|disconnect]",category:"system",async handler($,Y){let Z=($[0]||"").toLowerCase(),X;switch(Z){case"":case"status":X=await yQ();break;case"connect":X=await EQ();break;case"install":X=await jQ();break;case"disconnect":X=await PQ();break;default:X=`未知的子命令: ${Z}
|
|
1332
1332
|
|
|
1333
1333
|
可用命令:
|
|
1334
1334
|
/ide status - 显示连接状态
|
|
1335
1335
|
/ide connect - 连接到 IDE
|
|
1336
1336
|
/ide install - 安装 VS Code 插件
|
|
1337
|
-
/ide disconnect - 断开连接`}return{success:!0,message:X}}}
|
|
1337
|
+
/ide disconnect - 断开连接`}return{success:!0,message:X}}},$3=SQ;import{promises as Q2}from"fs";import*as Z3 from"path";function X2($,Y){switch($){case"Write":return`Write(${Y.file_path||"file"})`;case"Edit":return`Edit(${Y.file_path||"file"})`;case"Read":return`Read(${Y.file_path||"file"})`;case"Bash":{let Z=Y.command;return`Bash(${Z?Z.substring(0,50):"command"}${Z&&Z.length>50?"...":""})`}case"Glob":return`Glob(${Y.pattern||"*"})`;case"Grep":{let{pattern:Z,path:X}=Y;if(X)return`Grep("${Z}" in ${X})`;return`Grep("${Z}")`}case"WebFetch":{let Z=Y.url;if(Z)try{return`WebFetch(${new URL(Z).hostname})`}catch{return`WebFetch(${Z.substring(0,30)}${Z.length>30?"...":""})`}return"WebFetch(url)"}case"WebSearch":return`WebSearch("${Y.query||"query"}")`;case"TodoWrite":return`TodoWrite(${Y.todos?.length||0} items)`;case"UndoEdit":return`UndoEdit(${Y.file_path||"file"})`;default:return`${$}()`}}function Y3($,Y){if(!Y?.displayContent)return!1;switch($){case"Write":return(Y.metadata?.file_size||0)<1e4;case"Edit":return!0;case"Bash":return(Y.metadata?.stdout_length||0)<1000;case"Read":case"TodoWrite":return!1;default:return!1}}var TQ={name:"init",description:"分析当前项目并生成 BLADE.md 配置文件",usage:"/init",async handler($,Y){try{let{cwd:Z}=Y,X=o().addAssistantMessage,Q=o().addToolMessage,J=s().session.sessionId,q=Z3.join(Z,"BLADE.md"),G=!1,K=!1;try{if(G=(await Q2.stat(q)).isFile(),G)K=(await Q2.readFile(q,"utf-8")).trim().length===0}catch{G=!1}if(G&&!K){X("⚠️ BLADE.md 已存在。"),X("\uD83D\uDCA1 正在分析现有文件并提供改进建议...");let H=await k0.create(),_=`Please analyze the existing BLADE.md file and provide improvement suggestions.
|
|
1338
1338
|
|
|
1339
1339
|
**Important**:
|
|
1340
1340
|
- After each step, briefly describe what you found before proceeding
|
|
@@ -1343,7 +1343,7 @@ ${W}
|
|
|
1343
1343
|
|
|
1344
1344
|
**Step-by-step process:**
|
|
1345
1345
|
|
|
1346
|
-
1. Read the current BLADE.md file at ${
|
|
1346
|
+
1. Read the current BLADE.md file at ${q} and summarize its current structure
|
|
1347
1347
|
|
|
1348
1348
|
2. Read package.json and note:
|
|
1349
1349
|
- Any new scripts or commands not documented
|
|
@@ -1361,7 +1361,7 @@ ${W}
|
|
|
1361
1361
|
- 具体的改进建议(附带示例)
|
|
1362
1362
|
- 如果需要重大修改,提供完整的改进版本内容
|
|
1363
1363
|
|
|
1364
|
-
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`,z=await H.chat(_,{messages:[],userId:"cli-user",sessionId:J||"init-session",workspaceRoot:Z},{onToolStart:(F)=>{if(F.type!=="function")return;try{let
|
|
1364
|
+
**Final output**: Return your analysis and suggestions as plain text. Do NOT use Write tool.`,z=await H.chat(_,{messages:[],userId:"cli-user",sessionId:J||"init-session",workspaceRoot:Z},{onToolStart:(F)=>{if(F.type!=="function")return;try{let w=JSON.parse(F.function.arguments),L=X2(F.function.name,w);Q(L,{toolName:F.function.name,phase:"start",summary:L,params:w})}catch{}},onToolResult:async(F,w)=>{if(F.type!=="function")return;if(w?.metadata?.summary)Q(w.metadata.summary,{toolName:F.function.name,phase:"complete",summary:w.metadata.summary})}});return X(z),{success:!0,message:"✅ 分析完成"}}if(K)X("⚠️ 检测到空的 BLADE.md 文件,将重新生成...");X("\uD83D\uDD0D 正在分析项目结构...");let W=await k0.create(),O=`Please analyze this codebase and generate BLADE.md content.
|
|
1365
1365
|
|
|
1366
1366
|
**Important**: After each step, briefly describe what you found before proceeding.
|
|
1367
1367
|
|
|
@@ -1394,7 +1394,7 @@ ${W}
|
|
|
1394
1394
|
- Focus on non-obvious insights
|
|
1395
1395
|
- Be concise but comprehensive
|
|
1396
1396
|
|
|
1397
|
-
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`,U=await W.chat(O,{messages:[],userId:"cli-user",sessionId:J||"init-session",workspaceRoot:Z},{onToolStart:(H)=>{if(H.type!=="function")return;try{let _=JSON.parse(H.function.arguments),z=
|
|
1397
|
+
**Final output**: Return ONLY the complete BLADE.md content (markdown format), ready to be written to the file.`,U=await W.chat(O,{messages:[],userId:"cli-user",sessionId:J||"init-session",workspaceRoot:Z},{onToolStart:(H)=>{if(H.type!=="function")return;try{let _=JSON.parse(H.function.arguments),z=X2(H.function.name,_);Q(z,{toolName:H.function.name,phase:"start",summary:z,params:_})}catch{}},onToolResult:async(H,_)=>{if(H.type!=="function")return;if(_?.metadata?.summary)Q(_.metadata.summary,{toolName:H.function.name,phase:"complete",summary:_.metadata.summary})}});if(!U||U.trim().length===0)throw Error("Agent 未能生成有效的 BLADE.md 内容");return X("✨ 正在写入 BLADE.md..."),await Q2.writeFile(q,U,"utf-8"),{success:!0,message:"✅ 已成功生成 BLADE.md 文件"}}catch(Z){return{success:!1,error:`初始化失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}},X3=TQ;var CQ={name:"model",description:"管理和切换模型配置",usage:"/model [子命令] [参数]",fullDescription:`
|
|
1398
1398
|
管理和切换模型配置
|
|
1399
1399
|
|
|
1400
1400
|
子命令:
|
|
@@ -1406,11 +1406,11 @@ ${W}
|
|
|
1406
1406
|
/model # 显示模型选择器
|
|
1407
1407
|
/model add # 添加新模型
|
|
1408
1408
|
/model remove 千问 # 删除名称包含"千问"的模型
|
|
1409
|
-
`,async handler($,Y){let Z=$[0];if(!Z){if(
|
|
1409
|
+
`,async handler($,Y){let Z=$[0];if(!Z){if(d$().length===0)return{success:!1,message:`❌ 没有可用的模型配置
|
|
1410
1410
|
|
|
1411
1411
|
使用 /model add 添加模型`};return{success:!0,message:"show_model_selector",data:{action:"show_model_selector"}}}switch(Z){case"add":return{success:!0,message:"show_model_add_wizard",data:{action:"show_model_add_wizard",mode:"add"}};case"remove":{let X=$.slice(1).join(" ");if(!X)return{success:!1,message:`❌ 请指定要删除的模型名称
|
|
1412
|
-
用法: /model remove <名称>`};let J=
|
|
1413
|
-
使用 /model 查看可用操作`}}}},e5=EQ;async function jQ($,Y){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var SQ={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:jQ},$3=SQ;var t2={...f5,init:t5,theme:$3,permissions:n2,model:e5,git:c5,ide:a5};function Y3($){return $.trim().startsWith("/")}function TQ($){let Y=$.trim();if(!Y.startsWith("/"))throw Error("不是有效的 slash command");let Z=Y.slice(1).split(/\s+/),X=Z[0]||"",Q=Z.slice(1);return{command:X,args:Q}}function CQ($){if(t2[$])return t2[$];for(let Y of Object.values(t2))if(Y.aliases?.includes($))return Y;return}async function Z3($,Y){try{let{command:Z,args:X}=TQ($),Q=CQ(Z);if(!Q)return{success:!1,error:`未知命令: /${Z}\\n使用 /help 查看可用命令`};return await Q.handler(X,Y)}catch(Z){return{success:!1,error:`命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}function X3($){let Y=($.startsWith("/")?$.slice(1):$).trim(),Z=Object.values(t2).map((G)=>({name:G.name,description:G.description,aliases:G.aliases||[],command:G}));if(!Y)return Z.map((G)=>({command:`/${G.name}`,description:G.description,matchScore:50}));return new PQ(Z,{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(Y).map((G)=>{let q=G.score??1,K=Math.round((1-q)*100);return{command:`/${G.item.name}`,description:G.item.description,matchScore:K}}).filter((G)=>(G.matchScore||0)>=40)}import{useMemoizedFn as Q3}from"ahooks";import{useRef as fQ}from"react";function J3($){let Y=fQ(void 0),Z=Q3(async()=>{let Q=await D0.create({systemPrompt:$.systemPrompt,appendSystemPrompt:$.appendSystemPrompt,maxTurns:$.maxTurns});return Y.current=Q,Q}),X=Q3(()=>{if(Y.current)Y.current=void 0});return{agentRef:Y,createAgent:Z,cleanupAgent:X}}var pQ=Q0("UI");function gQ($,Y,Z){switch($){case"show_theme_selector":return Z.setActiveModal("themeSelector"),!0;case"show_model_selector":return Z.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return Z.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return Z.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return Z.setActiveModal("agentsManager"),!0;case"show_agent_creation_wizard":return Z.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let X=Y?.sessions;return Z.showSessionSelector(X),!0}case"exit_application":return process.exit(0),!0;default:return!1}}var G3=($,Y,Z,X)=>{let Q=k5(),J=l2(),G=H5(),q=V$(),K=R$(),W=b$(),O=M5(),U=xQ(!1),{createAgent:H,cleanupAgent:_}=J3({systemPrompt:$,appendSystemPrompt:Y,maxTurns:X});hQ(()=>{return()=>{_()}},[_]);let z=Q8(()=>{if(!Q)return;if(!U.current)K.addAssistantMessage("✋ 任务已停止"),U.current=!0;O.abort(),W.setTodos([])}),F=Q8(async(w)=>{try{if(K.addUserMessage(w),Y3(w)){await w2();let N={cwd:process.cwd()},I=await Z3(w,N);if(I.message){if(gQ(I.message,I.data,W))return{success:!0}}if(!I.success&&I.error)return K.addAssistantMessage(`❌ ${I.error}`),{success:I.success,output:I.message,error:I.error,metadata:I.data};let C=I.message;if(I.success&&typeof C==="string"&&C.trim()!=="")K.addAssistantMessage(C);return{success:I.success,output:I.message,error:I.error,metadata:I.data}}let B=await H(),A=O.createAbortController(),V={messages:J.map((N)=>({role:N.role,content:N.content})),userId:"cli-user",sessionId:G,workspaceRoot:process.cwd(),signal:A.signal,confirmationHandler:Z,permissionMode:q},E={onContent:(N)=>{if(N.trim())K.addAssistantMessage(N)},onToolStart:(N)=>{if(N.type!=="function")return;if(N.function.name==="TodoWrite")return;try{let I=JSON.parse(N.function.arguments),C=Y2(N.function.name,I);K.addToolMessage(C,{toolName:N.function.name,phase:"start",summary:C,params:I})}catch(I){pQ.error("[useCommandHandler] onToolStart error:",I)}},onToolResult:async(N,I)=>{if(N.type!=="function")return;if(!I?.metadata?.summary)return;let C=o5(N.function.name,I)?I.displayContent:void 0;K.addToolMessage(I.metadata.summary,{toolName:N.function.name,phase:"complete",summary:I.metadata.summary,detail:C})},onTokenUsage:(N)=>{K.updateTokenUsage(N)},onCompacting:(N)=>{K.setCompacting(N)}},R=await B.chat(w,V,E);if(!R||R.trim()==="")return{success:!0,output:"任务已停止"};return{success:!0,output:R}}catch(B){let A=B instanceof Error?B.message:"未知错误",V={success:!1,error:A};return K.addAssistantMessage(`❌ ${A}`),V}}),L=Q8(async(w)=>{if(!w.trim())return;let B=w.trim();if(Q){O.enqueueCommand(B);return}W.setTodos([]),U.current=!1,O.setProcessing(!0),K.setThinking(!0);try{let A=await F(B);if(!A.success&&A.error)K.setError(A.error)}catch(A){if(A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")));else{let V=A instanceof Error?A.message:"未知错误";K.setError(`执行失败: ${V}`)}}finally{O.setProcessing(!1),K.setThinking(!1),O.clearAbortController();let A=O.dequeueCommand();if(A)setTimeout(()=>L(A),100)}});return{executeCommand:L,handleAbort:z,isProcessing:Q}};import{useMemoizedFn as e2}from"ahooks";import{useState as q3}from"react";var K3=()=>{let[$,Y]=q3([]),[Z,X]=q3(-1),Q=e2((K)=>{Y((W)=>[...W,K]),X(-1)}),J=e2(()=>{if($.length===0)return"";let K=Z===-1?$.length-1:Math.max(0,Z-1);return X(K),$[K]||""}),G=e2(()=>{if(Z===-1)return"";let K=Z+1;if(K>=$.length)return X(-1),"";else return X(K),$[K]||""}),q=e2(()=>{X(-1)});return{commandHistory:$,historyIndex:Z,addToHistory:Q,getPreviousCommand:J,getNextCommand:G,resetHistoryIndex:q}};import{useMemoizedFn as W3}from"ahooks";import{useMemo as uQ,useState as mQ}from"react";var U3=()=>{let[$,Y]=mQ({isVisible:!1,details:null,resolver:null}),Z=W3((J)=>{return new Promise((G)=>{Y({isVisible:!0,details:J,resolver:G})})}),X=W3((J)=>{if($.resolver)$.resolver(J);Y({isVisible:!1,details:null,resolver:null})}),Q=uQ(()=>({requestConfirmation:Z}),[Z]);return{confirmationState:$,confirmationHandler:Q,handleResponse:X}};import{useMemoizedFn as J8}from"ahooks";import{useState as dQ}from"react";function O3($="",Y=0){let[Z,X]=dQ({value:$,cursorPosition:Y}),Q=J8((q)=>{X((K)=>({value:q,cursorPosition:K.cursorPosition}))}),J=J8((q)=>{X((K)=>({...K,cursorPosition:Math.max(0,Math.min(q,K.value.length))}))}),G=J8(()=>{X({value:"",cursorPosition:0})});return{value:Z.value,cursorPosition:Z.cursorPosition,setValue:Q,setCursorPosition:J,clear:G}}import{useMemoizedFn as N3}from"ahooks";import{useInput as oQ}from"ink";import{useEffect as w3,useRef as L3,useState as W8}from"react";import{useMemoizedFn as lN}from"ahooks";import cQ from"fast-glob";import lQ from"fuse.js";import{useEffect as H3,useMemo as G8,useState as q8}from"react";var D$=null,iQ=5000;function rQ($,Y){let Z=[...$.matchAll(/(?:^|\s)(@(?:"[^"]*"|(?:[^\\ ]|\\ )*))/g)];for(let X of Z){let Q=X[1],J=X.index+(X[0].length-Q.length),G=J+Q.length;if(Y>=J&&Y<=G){let q=Q.slice(1),K=!1;if(q.startsWith('"')){if(K=!0,q=q.slice(1),q.endsWith('"'))q=q.slice(0,-1)}return{hasQuery:!0,query:q,startIndex:J,endIndex:G,quoted:K}}}return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1}}var nQ=[...F1.map(($)=>`${$}/**`),...F1,...Y4.map(($)=>`**/${$}`)];function _3($,Y,Z={}){let{cwd:X=process.cwd(),maxSuggestions:Q=15,ignorePatterns:J=nQ,debounceDelay:G=300,fuzzyMatch:q=!0}=Z,[K,W]=q8([]),[O,U]=q8(!1),[H,_]=q8(0),z=G8(()=>JSON.stringify(J),[J]),F=G8(()=>{if(Y===void 0)return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1};return rQ($,Y)},[$,Y]);H3(()=>{if(!$.includes("@")){W([]),U(!1);return}let w=Date.now();if(D$&&D$.cwd===X&&D$.ignoreKey===z&&w-D$.timestamp<iQ){W(D$.files),U(!1);return}let B=!1,V=setTimeout(async()=>{U(!0);try{let R=(await cQ("**/*",{cwd:X,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:J})).map((N)=>N.replace(/\\/g,"/"));if(!B)W(R),D$={cwd:X,ignoreKey:z,files:R,timestamp:w}}catch(E){if(console.error("Failed to load files for @ completion:",E),!B)W([])}finally{if(!B)U(!1)}},G);return()=>{B=!0,clearTimeout(V)}},[$,X,G,z]);let L=G8(()=>{if(!F.hasQuery||K.length===0)return[];let w=F.query.toLowerCase();if(w==="")return K.slice(0,Q);if(q)return new lQ(K,{threshold:0.4,ignoreLocation:!0,minMatchCharLength:1}).search(w).slice(0,Q).map((V)=>V.item);return K.filter((B)=>B.toLowerCase().includes(w)).slice(0,Q)},[F,K,Q,q]);return H3(()=>{_(0)},[L]),{...F,suggestions:L,selectedIndex:H,loading:O}}function aQ($,Y=!1){if($.includes(" ")||Y)return`@"${$}"`;return`@${$}`}function K8($,Y,Z){if(!Y.hasQuery)return{newInput:$,newCursorPos:$.length};let X=aQ(Z,Y.quoted),Q=$.slice(0,Y.startIndex),J=$.slice(Y.endIndex),G=Q+X+" "+J,q=Y.startIndex+X.length+1;return{newInput:G,newCursorPos:q}}import{useMemoizedFn as F3}from"ahooks";import{useEffect as z3,useRef as B3}from"react";var b0=($,Y)=>{let Z=B3(!1),X=B3(null),Q=F3(()=>{if(X.current)clearTimeout(X.current);X.current=setTimeout(()=>{Y1().setAwaitingSecondCtrlC(!1),Z.current=!1,X.current=null},3000)}),J=()=>{setTimeout(()=>{process.exit(0)},100)},G=F3(()=>{if(!Z.current){if(Z.current=!0,$&&Y)Y();Y1().setAwaitingSecondCtrlC(!0),Q()}else{if(X.current)clearTimeout(X.current),X.current=null;Y1().setAwaitingSecondCtrlC(!1),J()}});return z3(()=>{if($){if(Y1().setAwaitingSecondCtrlC(!1),Z.current=!1,X.current)clearTimeout(X.current),X.current=null}},[$]),z3(()=>{return()=>{if(X.current)clearTimeout(X.current)}},[]),G};var $6=Q0("UI"),A3=($,Y,Z,X,Q,J,G,q,K,W)=>{let U=l0()==="main-input",H=$.value,_=$.setValue,z=$.cursorPosition,F=R$(),[L,w]=W8(!1),[B,A]=W8([]),[V,E]=W8(0),R=_3(H,z,{cwd:process.cwd(),maxSuggestions:10}),N=b0(G||!1,J),I=L3(0),C=500,p=L3(!1);w3(()=>{if(G)p.current=!1},[G]),w3(()=>{if(H.startsWith("/"))if(H.includes(" "))w(!1),A([]);else{let P=X3(H);A(P),w(P.length>0),E(0)}else if(R.hasQuery&&R.suggestions.length>0){let i=R.suggestions.map((P)=>({command:P,description:P.endsWith("/")?`Directory: ${P}`:`File: ${P}`,matchScore:1}));A(i),w(!0),E(0)}else w(!1),A([])},[H,R.hasQuery,R.suggestions]);let y=N3(()=>{F.clearMessages(),F.setError(null)}),v=N3(()=>{$6.debug("[DIAG] handleSubmit called:",{input:H,showSuggestions:L});let i=H.trim();if(i)$6.debug("[DIAG] Submitting command:",i),w(!1),A([]),Q(i),$.clear(),Y(i),$6.debug("[DIAG] Command submitted to onSubmit callback");else $6.debug("[DIAG] Empty command, not submitting")});return oQ((i,P)=>{if(i==="?"&&!H){K?.(),setTimeout(()=>$.clear(),0);return}if(P.backspace||P.delete||P.leftArrow||P.rightArrow||P.pageUp||P.pageDown||!P.ctrl&&!P.meta&&!P.escape&&!P.tab&&!P.upArrow&&!P.downArrow&&!P.return&&!(i==="?"&&!H))return;if(P.ctrl&&i==="c"||P.meta&&i==="c"||P.ctrl&&i==="d"||P.meta&&i==="d"){N();return}if(P.ctrl&&i==="l"||P.meta&&i==="l"){y();return}if(P.escape){if(W)K?.();else if(G&&J){if(p.current)return;p.current=!0,J()}else if(L)w(!1),A([]);else if(H){let X0=Date.now();if(X0-I.current<500)$.clear(),I.current=0;else I.current=X0}return}if(P.tab&&P.shift){q?.();return}if(P.tab&&L&&B.length>0){let X0=B[V].command;if(R.hasQuery&&R.suggestions.includes(X0)){let{newInput:_0,newCursorPos:M1}=K8(H,R,X0);_(_0),$.setCursorPosition(M1)}else{let _0=X0+" ";_(_0),$.setCursorPosition(_0.length)}w(!1),A([]);return}if(P.return){if(L&&B.length>0){let X0=B[V].command;if(R.hasQuery&&R.suggestions.includes(X0)){let{newInput:_0,newCursorPos:M1}=K8(H,R,X0);_(_0),$.setCursorPosition(M1)}else{let _0=X0+" ";_(_0),$.setCursorPosition(_0.length)}w(!1),A([])}else v();return}if(P.upArrow){if(L&&B.length>0){let X0=B.length-1;E((_0)=>_0>0?_0-1:X0)}else{let X0=Z();if(X0!=="")_(X0),$.setCursorPosition(X0.length)}return}if(P.downArrow){if(L&&B.length>0){let X0=B.length-1;E((_0)=>_0<X0?_0+1:0)}else{let X0=X();if(X0!=="")_(X0),$.setCursorPosition(X0.length)}return}},{isActive:U}),{handleSubmit:v,showSuggestions:L,suggestions:B,selectedSuggestionIndex:V}};import{MultiSelect as sQ}from"@inkjs/ui";import{useMemoizedFn as Y6}from"ahooks";import{Box as g,Text as f,useFocus as tQ,useFocusManager as eQ,useInput as V3}from"ink";import Z6 from"ink-select-input";import $J from"ink-spinner";import X2 from"ink-text-input";import R3 from"node:fs";import YJ from"node:os";import U8 from"node:path";import{useEffect as b3,useState as M$}from"react";import{jsxDEV as b}from"react/jsx-dev-runtime";var ZJ=[{label:"\uD83D\uDD0D Glob - 文件搜索",value:"Glob"},{label:"\uD83D\uDD0E Grep - 内容搜索",value:"Grep"},{label:"\uD83D\uDCD6 Read - 读取文件",value:"Read"},{label:"✍️ Write - 写入文件",value:"Write"},{label:"✏️ Edit - 编辑文件",value:"Edit"},{label:"\uD83D\uDCBB Bash - 执行命令",value:"Bash"},{label:"✅ 所有工具 (不限制)",value:"all"}],XJ=[{label:"\uD83D\uDD34 红色 (red)",value:"red"},{label:"\uD83D\uDD35 蓝色 (blue)",value:"blue"},{label:"\uD83D\uDFE2 绿色 (green)",value:"green"},{label:"\uD83D\uDFE1 黄色 (yellow)",value:"yellow"},{label:"\uD83D\uDFE3 紫色 (purple)",value:"purple"},{label:"\uD83D\uDFE0 橙色 (orange)",value:"orange"},{label:"\uD83E\uDE77 粉色 (pink)",value:"pink"},{label:"\uD83E\uDE75 青色 (cyan)",value:"cyan"},{label:"⚪ 不设置颜色",value:"none"}];function QJ($){if(!$||$.trim()==="")return"名称不能为空";if(!/^[a-z0-9-]+$/.test($))return"名称只能包含小写字母、数字和连字符";if($.startsWith("-")||$.endsWith("-"))return"名称不能以连字符开头或结尾";return null}function Q2({onComplete:$,onCancel:Y,initialConfig:Z}){let[X,Q]=M$(Z?"name":"mode"),[J,G]=M$({name:Z?.name||"",description:Z?.description||"",tools:Z?.tools||[],color:Z?.color,location:Z?.location||"project",systemPrompt:Z?.systemPrompt||""}),[q,K]=M$(""),[W,O]=M$(!1),[U,H]=M$(""),[_,z]=M$(Z?"edit":"manual"),{focus:F}=eQ(),w={manual:["mode","name","description","tools","color","location","systemPrompt","confirm"],ai:["mode","aiPrompt","aiGenerating","confirm"],edit:["name","description","tools","color","location","systemPrompt","confirm"]}[_];b3(()=>{if(X==="name"||X==="description"||X==="systemPrompt"||X==="aiPrompt")return;F(`step-${X}`)},[X,F]);let B=Y6(()=>{let N=w.indexOf(X);if(N<w.length-1)Q(w[N+1])}),A=Y6(()=>{if(U)H("");if(X==="confirm"&&_==="ai"){Q("aiPrompt");return}let N=w.indexOf(X);if(N>0)Q(w[N-1]);else Y()}),V=Y6(async()=>{O(!0),H("");try{let N=await D0.create(),I=`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
|
|
1412
|
+
用法: /model remove <名称>`};let J=d$().find((q)=>q.name.toLowerCase().includes(X.toLowerCase()));if(!J)return{success:!1,message:`❌ 未找到匹配的模型配置: ${X}`};try{return await e().removeModel(J.id),{success:!0,message:`✅ 已删除模型配置: ${J.name}`}}catch(q){return{success:!1,message:`❌ ${q.message}`}}}default:return{success:!1,message:`❌ 未知的子命令: ${Z}
|
|
1413
|
+
使用 /model 查看可用操作`}}}},Q3=CQ;async function fQ($,Y){return{success:!0,message:"show_theme_selector",data:{action:"show_theme_selector"}}}var hQ={name:"theme",description:"打开交互式主题选择器",aliases:["themes","style"],usage:"/theme",examples:["/theme"],category:"ui",handler:fQ},J3=hQ;var Y6={...m5,init:X3,theme:J3,permissions:s2,model:Q3,git:n5,ide:$3};function q3($){return $.trim().startsWith("/")}function pQ($){let Y=$.trim();if(!Y.startsWith("/"))throw Error("不是有效的 slash command");let Z=Y.slice(1).split(/\s+/),X=Z[0]||"",Q=Z.slice(1);return{command:X,args:Q}}function gQ($){if(Y6[$])return Y6[$];for(let Y of Object.values(Y6))if(Y.aliases?.includes($))return Y;return}async function G3($,Y){try{let{command:Z,args:X}=pQ($),Q=gQ(Z);if(!Q)return{success:!1,error:`未知命令: /${Z}\\n使用 /help 查看可用命令`};return await Q.handler(X,Y)}catch(Z){return{success:!1,error:`命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}}function K3($){let Y=($.startsWith("/")?$.slice(1):$).trim(),Z=Object.values(Y6).map((q)=>({name:q.name,description:q.description,aliases:q.aliases||[],command:q}));if(!Y)return Z.map((q)=>({command:`/${q.name}`,description:q.description,matchScore:50}));return new xQ(Z,{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(Y).map((q)=>{let G=q.score??1,K=Math.round((1-G)*100);return{command:`/${q.item.name}`,description:q.item.description,matchScore:K}}).filter((q)=>(q.matchScore||0)>=40)}import{useMemoizedFn as W3}from"ahooks";import{useRef as mQ}from"react";function U3($){let Y=mQ(void 0),Z=W3(async()=>{let Q=await k0.create({systemPrompt:$.systemPrompt,appendSystemPrompt:$.appendSystemPrompt,maxTurns:$.maxTurns});return Y.current=Q,Q}),X=W3(()=>{if(Y.current)Y.current=void 0});return{agentRef:Y,createAgent:Z,cleanupAgent:X}}var cQ=Y0("UI");function lQ($,Y,Z){switch($){case"show_theme_selector":return Z.setActiveModal("themeSelector"),!0;case"show_model_selector":return Z.setActiveModal("modelSelector"),!0;case"show_model_add_wizard":return Z.setActiveModal("modelAddWizard"),!0;case"show_permissions_manager":return Z.setActiveModal("permissionsManager"),!0;case"show_agents_manager":return Z.setActiveModal("agentsManager"),!0;case"show_agent_creation_wizard":return Z.setActiveModal("agentCreationWizard"),!0;case"show_session_selector":{let X=Y?.sessions;return Z.showSessionSelector(X),!0}case"exit_application":return process.exit(0),!0;default:return!1}}var O3=($,Y,Z,X)=>{let Q=j5(),J=a2(),q=B5(),G=I$(),K=V$(),W=D$(),O=P5(),U=dQ(!1),{createAgent:H,cleanupAgent:_}=U3({systemPrompt:$,appendSystemPrompt:Y,maxTurns:X});uQ(()=>{return()=>{_()}},[_]);let z=G8(()=>{if(!Q)return;if(!U.current)K.addAssistantMessage("✋ 任务已停止"),U.current=!0;O.abort(),W.setTodos([])}),F=G8(async(L)=>{try{if(K.addUserMessage(L),q3(L)){await A2();let B={cwd:process.cwd()},D=await G3(L,B);if(D.message){if(lQ(D.message,D.data,W))return{success:!0}}if(!D.success&&D.error)return K.addAssistantMessage(`❌ ${D.error}`),{success:D.success,output:D.message,error:D.error,metadata:D.data};let C=D.message;if(D.success&&typeof C==="string"&&C.trim()!=="")K.addAssistantMessage(C);return{success:D.success,output:D.message,error:D.error,metadata:D.data}}let N=await H(),A=O.createAbortController(),V={messages:J.map((B)=>({role:B.role,content:B.content})),userId:"cli-user",sessionId:q,workspaceRoot:process.cwd(),signal:A.signal,confirmationHandler:Z,permissionMode:G},E={onContent:(B)=>{if(B.trim())K.addAssistantMessage(B)},onToolStart:(B)=>{if(B.type!=="function")return;if(B.function.name==="TodoWrite")return;try{let D=JSON.parse(B.function.arguments),C=X2(B.function.name,D);K.addToolMessage(C,{toolName:B.function.name,phase:"start",summary:C,params:D})}catch(D){cQ.error("[useCommandHandler] onToolStart error:",D)}},onToolResult:async(B,D)=>{if(B.type!=="function")return;if(!D?.metadata?.summary)return;let C=Y3(B.function.name,D)?D.displayContent:void 0;K.addToolMessage(D.metadata.summary,{toolName:B.function.name,phase:"complete",summary:D.metadata.summary,detail:C})},onTokenUsage:(B)=>{K.updateTokenUsage(B)},onCompacting:(B)=>{K.setCompacting(B)}},R=await N.chat(L,V,E);if(!R||R.trim()==="")return{success:!0,output:"任务已停止"};return{success:!0,output:R}}catch(N){let A=N instanceof Error?N.message:"未知错误",V={success:!1,error:A};return K.addAssistantMessage(`❌ ${A}`),V}}),w=G8(async(L)=>{if(!L.trim())return;let N=L.trim();if(Q){O.enqueueCommand(N);return}W.setTodos([]),U.current=!1,O.setProcessing(!0),K.setThinking(!0);try{let A=await F(N);if(!A.success&&A.error)K.setError(A.error)}catch(A){if(A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")));else{let V=A instanceof Error?A.message:"未知错误";K.setError(`执行失败: ${V}`)}}finally{O.setProcessing(!1),K.setThinking(!1),O.clearAbortController();let A=O.dequeueCommand();if(A)setTimeout(()=>w(A),100)}});return{executeCommand:w,handleAbort:z,isProcessing:Q}};import{useMemoizedFn as Z6}from"ahooks";import{useState as H3}from"react";var _3=()=>{let[$,Y]=H3([]),[Z,X]=H3(-1),Q=Z6((K)=>{Y((W)=>[...W,K]),X(-1)}),J=Z6(()=>{if($.length===0)return"";let K=Z===-1?$.length-1:Math.max(0,Z-1);return X(K),$[K]||""}),q=Z6(()=>{if(Z===-1)return"";let K=Z+1;if(K>=$.length)return X(-1),"";else return X(K),$[K]||""}),G=Z6(()=>{X(-1)});return{commandHistory:$,historyIndex:Z,addToHistory:Q,getPreviousCommand:J,getNextCommand:q,resetHistoryIndex:G}};import{useMemoizedFn as F3}from"ahooks";import{useMemo as iQ,useState as rQ}from"react";var z3=()=>{let[$,Y]=rQ({isVisible:!1,details:null,resolver:null}),Z=F3((J)=>{return new Promise((q)=>{Y({isVisible:!0,details:J,resolver:q})})}),X=F3((J)=>{if($.resolver)$.resolver(J);Y({isVisible:!1,details:null,resolver:null})}),Q=iQ(()=>({requestConfirmation:Z}),[Z]);return{confirmationState:$,confirmationHandler:Q,handleResponse:X}};import{useMemoizedFn as K8}from"ahooks";import{useState as aQ}from"react";function N3($="",Y=0){let[Z,X]=aQ({value:$,cursorPosition:Y}),Q=K8((G)=>{X((K)=>({value:G,cursorPosition:K.cursorPosition}))}),J=K8((G)=>{X((K)=>({...K,cursorPosition:Math.max(0,Math.min(G,K.value.length))}))}),q=K8(()=>{X({value:"",cursorPosition:0})});return{value:Z.value,cursorPosition:Z.cursorPosition,setValue:Q,setCursorPosition:J,clear:q}}import{useMemoizedFn as b3}from"ahooks";import{useInput as YJ}from"ink";import{useEffect as V3,useRef as D3,useState as H8}from"react";import{useMemoizedFn as tB}from"ahooks";import nQ from"fast-glob";import oQ from"fuse.js";import{useEffect as B3,useMemo as W8,useState as U8}from"react";var v$=null,sQ=5000;function tQ($,Y){let Z=[...$.matchAll(/(?:^|\s)(@(?:"[^"]*"|(?:[^\\ ]|\\ )*))/g)];for(let X of Z){let Q=X[1],J=X.index+(X[0].length-Q.length),q=J+Q.length;if(Y>=J&&Y<=q){let G=Q.slice(1),K=!1;if(G.startsWith('"')){if(K=!0,G=G.slice(1),G.endsWith('"'))G=G.slice(0,-1)}return{hasQuery:!0,query:G,startIndex:J,endIndex:q,quoted:K}}}return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1}}var eQ=[...F1.map(($)=>`${$}/**`),...F1,...Q4.map(($)=>`**/${$}`)];function L3($,Y,Z={}){let{cwd:X=process.cwd(),maxSuggestions:Q=15,ignorePatterns:J=eQ,debounceDelay:q=300,fuzzyMatch:G=!0}=Z,[K,W]=U8([]),[O,U]=U8(!1),[H,_]=U8(0),z=W8(()=>JSON.stringify(J),[J]),F=W8(()=>{if(Y===void 0)return{hasQuery:!1,query:"",startIndex:-1,endIndex:-1,quoted:!1};return tQ($,Y)},[$,Y]);B3(()=>{if(!$.includes("@")){W([]),U(!1);return}let L=Date.now();if(v$&&v$.cwd===X&&v$.ignoreKey===z&&L-v$.timestamp<sQ){W(v$.files),U(!1);return}let N=!1,V=setTimeout(async()=>{U(!0);try{let R=(await nQ("**/*",{cwd:X,dot:!1,followSymbolicLinks:!1,onlyFiles:!1,markDirectories:!0,unique:!0,ignore:J})).map((B)=>B.replace(/\\/g,"/"));if(!N)W(R),v$={cwd:X,ignoreKey:z,files:R,timestamp:L}}catch(E){if(console.error("Failed to load files for @ completion:",E),!N)W([])}finally{if(!N)U(!1)}},q);return()=>{N=!0,clearTimeout(V)}},[$,X,q,z]);let w=W8(()=>{if(!F.hasQuery||K.length===0)return[];let L=F.query.toLowerCase();if(L==="")return K.slice(0,Q);if(G)return new oQ(K,{threshold:0.4,ignoreLocation:!0,minMatchCharLength:1}).search(L).slice(0,Q).map((V)=>V.item);return K.filter((N)=>N.toLowerCase().includes(L)).slice(0,Q)},[F,K,Q,G]);return B3(()=>{_(0)},[w]),{...F,suggestions:w,selectedIndex:H,loading:O}}function $J($,Y=!1){if($.includes(" ")||Y)return`@"${$}"`;return`@${$}`}function O8($,Y,Z){if(!Y.hasQuery)return{newInput:$,newCursorPos:$.length};let X=$J(Z,Y.quoted),Q=$.slice(0,Y.startIndex),J=$.slice(Y.endIndex),q=Q+X+" "+J,G=Y.startIndex+X.length+1;return{newInput:q,newCursorPos:G}}import{useMemoizedFn as w3}from"ahooks";import{useEffect as A3,useRef as R3}from"react";var b0=($,Y)=>{let Z=R3(!1),X=R3(null),Q=w3(()=>{if(X.current)clearTimeout(X.current);X.current=setTimeout(()=>{Z1().setAwaitingSecondCtrlC(!1),Z.current=!1,X.current=null},3000)}),J=()=>{i2().shutdown("SIGINT",0)},q=w3(()=>{if(!Z.current){if(Z.current=!0,$&&Y)Y();Z1().setAwaitingSecondCtrlC(!0),Q()}else{if(X.current)clearTimeout(X.current),X.current=null;Z1().setAwaitingSecondCtrlC(!1),J()}});return A3(()=>{if($){if(Z1().setAwaitingSecondCtrlC(!1),Z.current=!1,X.current)clearTimeout(X.current),X.current=null}},[$]),A3(()=>{return()=>{if(X.current)clearTimeout(X.current)}},[]),q};var X6=Y0("UI"),I3=($,Y,Z,X,Q,J,q,G,K,W)=>{let U=i0()==="main-input",H=$.value,_=$.setValue,z=$.cursorPosition,F=V$(),[w,L]=H8(!1),[N,A]=H8([]),[V,E]=H8(0),R=L3(H,z,{cwd:process.cwd(),maxSuggestions:10}),B=b0(q||!1,J),D=D3(0),C=500,p=D3(!1);V3(()=>{if(q)p.current=!1},[q]),V3(()=>{if(H.startsWith("/"))if(H.includes(" "))L(!1),A([]);else{let S=K3(H);A(S),L(S.length>0),E(0)}else if(R.hasQuery&&R.suggestions.length>0){let i=R.suggestions.map((S)=>({command:S,description:S.endsWith("/")?`Directory: ${S}`:`File: ${S}`,matchScore:1}));A(i),L(!0),E(0)}else L(!1),A([])},[H,R.hasQuery,R.suggestions]);let y=b3(()=>{F.clearMessages(),F.setError(null)}),M=b3(()=>{X6.debug("[DIAG] handleSubmit called:",{input:H,showSuggestions:w});let i=H.trim();if(i)X6.debug("[DIAG] Submitting command:",i),L(!1),A([]),Q(i),$.clear(),Y(i),X6.debug("[DIAG] Command submitted to onSubmit callback");else X6.debug("[DIAG] Empty command, not submitting")});return YJ((i,S)=>{if(i==="?"&&!H){K?.(),setTimeout(()=>$.clear(),0);return}if(S.backspace||S.delete||S.leftArrow||S.rightArrow||S.pageUp||S.pageDown||!S.ctrl&&!S.meta&&!S.escape&&!S.tab&&!S.upArrow&&!S.downArrow&&!S.return&&!(i==="?"&&!H))return;if(S.ctrl&&i==="c"||S.meta&&i==="c"||S.ctrl&&i==="d"||S.meta&&i==="d"){B();return}if(S.ctrl&&i==="l"||S.meta&&i==="l"){y();return}if(S.escape){if(W)K?.();else if(q&&J){if(p.current)return;p.current=!0,J()}else if(w)L(!1),A([]);else if(H){let Q0=Date.now();if(Q0-D.current<500)$.clear(),D.current=0;else D.current=Q0}return}if(S.tab&&S.shift){G?.();return}if(S.tab&&w&&N.length>0){let Q0=N[V].command;if(R.hasQuery&&R.suggestions.includes(Q0)){let{newInput:_0,newCursorPos:M1}=O8(H,R,Q0);_(_0),$.setCursorPosition(M1)}else{let _0=Q0+" ";_(_0),$.setCursorPosition(_0.length)}L(!1),A([]);return}if(S.return){if(w&&N.length>0){let Q0=N[V].command;if(R.hasQuery&&R.suggestions.includes(Q0)){let{newInput:_0,newCursorPos:M1}=O8(H,R,Q0);_(_0),$.setCursorPosition(M1)}else{let _0=Q0+" ";_(_0),$.setCursorPosition(_0.length)}L(!1),A([])}else M();return}if(S.upArrow){if(w&&N.length>0){let Q0=N.length-1;E((_0)=>_0>0?_0-1:Q0)}else{let Q0=Z();if(Q0!=="")_(Q0),$.setCursorPosition(Q0.length)}return}if(S.downArrow){if(w&&N.length>0){let Q0=N.length-1;E((_0)=>_0<Q0?_0+1:0)}else{let Q0=X();if(Q0!=="")_(Q0),$.setCursorPosition(Q0.length)}return}},{isActive:U}),{handleSubmit:M,showSuggestions:w,suggestions:N,selectedSuggestionIndex:V}};import{MultiSelect as ZJ}from"@inkjs/ui";import{useMemoizedFn as Q6}from"ahooks";import{Box as g,Text as f,useFocus as XJ,useFocusManager as QJ,useInput as M3}from"ink";import J6 from"ink-select-input";import JJ from"ink-spinner";import J2 from"ink-text-input";import k3 from"node:fs";import qJ from"node:os";import _8 from"node:path";import{useEffect as v3,useState as y$}from"react";import{jsxDEV as b}from"react/jsx-dev-runtime";var GJ=[{label:"\uD83D\uDD0D Glob - 文件搜索",value:"Glob"},{label:"\uD83D\uDD0E Grep - 内容搜索",value:"Grep"},{label:"\uD83D\uDCD6 Read - 读取文件",value:"Read"},{label:"✍️ Write - 写入文件",value:"Write"},{label:"✏️ Edit - 编辑文件",value:"Edit"},{label:"\uD83D\uDCBB Bash - 执行命令",value:"Bash"},{label:"✅ 所有工具 (不限制)",value:"all"}],KJ=[{label:"\uD83D\uDD34 红色 (red)",value:"red"},{label:"\uD83D\uDD35 蓝色 (blue)",value:"blue"},{label:"\uD83D\uDFE2 绿色 (green)",value:"green"},{label:"\uD83D\uDFE1 黄色 (yellow)",value:"yellow"},{label:"\uD83D\uDFE3 紫色 (purple)",value:"purple"},{label:"\uD83D\uDFE0 橙色 (orange)",value:"orange"},{label:"\uD83E\uDE77 粉色 (pink)",value:"pink"},{label:"\uD83E\uDE75 青色 (cyan)",value:"cyan"},{label:"⚪ 不设置颜色",value:"none"}];function WJ($){if(!$||$.trim()==="")return"名称不能为空";if(!/^[a-z0-9-]+$/.test($))return"名称只能包含小写字母、数字和连字符";if($.startsWith("-")||$.endsWith("-"))return"名称不能以连字符开头或结尾";return null}function q2({onComplete:$,onCancel:Y,initialConfig:Z}){let[X,Q]=y$(Z?"name":"mode"),[J,q]=y$({name:Z?.name||"",description:Z?.description||"",tools:Z?.tools||[],color:Z?.color,location:Z?.location||"project",systemPrompt:Z?.systemPrompt||""}),[G,K]=y$(""),[W,O]=y$(!1),[U,H]=y$(""),[_,z]=y$(Z?"edit":"manual"),{focus:F}=QJ(),L={manual:["mode","name","description","tools","color","location","systemPrompt","confirm"],ai:["mode","aiPrompt","aiGenerating","confirm"],edit:["name","description","tools","color","location","systemPrompt","confirm"]}[_];v3(()=>{if(X==="name"||X==="description"||X==="systemPrompt"||X==="aiPrompt")return;F(`step-${X}`)},[X,F]);let N=Q6(()=>{let B=L.indexOf(X);if(B<L.length-1)Q(L[B+1])}),A=Q6(()=>{if(U)H("");if(X==="confirm"&&_==="ai"){Q("aiPrompt");return}let B=L.indexOf(X);if(B>0)Q(L[B-1]);else Y()}),V=Q6(async()=>{O(!0),H("");try{let B=await k0.create(),D=`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
|
|
1414
1414
|
|
|
1415
1415
|
## 可用工具列表
|
|
1416
1416
|
|
|
@@ -1447,7 +1447,7 @@ ${W}
|
|
|
1447
1447
|
4. **color**: 选择一个合适的颜色用于 UI 区分
|
|
1448
1448
|
5. **systemPrompt**: 详细说明 agent 的职责、使用的工具、输出格式等,使用 Markdown 格式
|
|
1449
1449
|
|
|
1450
|
-
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,p=(await
|
|
1450
|
+
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,p=(await B.chatWithSystem(`你是一个 Subagent 配置生成专家。用户会描述他们想要创建的 agent,你需要根据描述生成一个完整的 agent 配置。
|
|
1451
1451
|
|
|
1452
1452
|
## 可用工具列表
|
|
1453
1453
|
|
|
@@ -1484,27 +1484,27 @@ ${W}
|
|
|
1484
1484
|
4. **color**: 选择一个合适的颜色用于 UI 区分
|
|
1485
1485
|
5. **systemPrompt**: 详细说明 agent 的职责、使用的工具、输出格式等,使用 Markdown 格式
|
|
1486
1486
|
|
|
1487
|
-
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,
|
|
1487
|
+
**重要**:请直接返回 JSON,不要添加任何额外的解释或文字。`,G)).trim(),y=p.match(/```(?:json)?\s*\n([\s\S]*?)\n```/);if(y)p=y[1];let M=JSON.parse(p);if(!M.name||!M.description||!M.systemPrompt)throw Error("Missing required fields: name, description, or systemPrompt");if(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(M.name))throw Error("Invalid name format. Must be kebab-case (lowercase, numbers, hyphens only)");q({name:M.name,description:M.description,tools:Array.isArray(M.tools)?M.tools:[],color:M.color||"blue",location:"project",systemPrompt:M.systemPrompt}),Q("confirm")}catch(B){H(B instanceof Error?B.message:String(B))}finally{O(!1)}});v3(()=>{if(X==="aiGenerating"&&!W&&!U)V()},[X,W,U,V]);let E=Q6(async()=>{try{let B=J.location==="project"?_8.join(process.cwd(),".blade","agents"):_8.join(qJ.homedir(),".blade","agents");await k3.promises.mkdir(B,{recursive:!0});let D=["---",`name: ${J.name}`,`description: ${J.description}`];if(J.tools.length>0&&!J.tools.includes("all")){D.push("tools:");for(let y of J.tools)D.push(` - ${y}`)}if(J.color)D.push(`color: ${J.color}`);D.push("---");let C=[D.join(`
|
|
1488
1488
|
`),"",`# ${J.name} Subagent`,"",J.systemPrompt||"你是一个专门的代理,负责执行特定任务。",""].join(`
|
|
1489
|
-
`),p=U8.join(N,`${J.name}.md`);await R3.promises.writeFile(p,C,"utf-8"),$()}catch(N){console.error("保存配置失败:",N)}}),R=b0(!1,Y);if(V3((N,I)=>{if(I.escape)A();else if(I.ctrl&&N==="c"||I.meta&&N==="c")R()},{isActive:X!=="tools"}),X==="mode")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83C\uDFAF 选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(Z6,{items:[{label:"\uD83E\uDD16 AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"✍️ 手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(N)=>{if(N.value==="ai")z("ai"),Q("aiPrompt");else z("manual"),Q("name")}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiPrompt")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83E\uDD16 AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"描述: "},void 0,!1,void 0,this),b(X2,{value:q,onChange:K,onSubmit:(N)=>{if(!N.trim())return;Q("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiGenerating"){if(U)return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"red",children:"❌ AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{color:"red",children:U},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"yellow",children:[b($J,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:['根据你的描述:"',q,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="name"){let N=_==="edit";return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:["\uD83D\uDCDD Step 1/7: ",N?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:N?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"名称: "},void 0,!1,void 0,this),N?b(f,{children:J.name},void 0,!1,void 0,this):b(X2,{value:J.name,onChange:(I)=>G({...J,name:I}),onSubmit:(I)=>{if(QJ(I))return;B()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:N?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),N&&b(X2,{value:"",onChange:()=>{},onSubmit:B,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="description")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCDD Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"描述: "},void 0,!1,void 0,this),b(X2,{value:J.description,onChange:(N)=>G({...J,description:N}),onSubmit:(N)=>{if(!N.trim())return;B()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="tools")return b(JJ,{config:J,setConfig:G,onNext:B,onPrev:A},void 0,!1,void 0,this);if(X==="color")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83C\uDFA8 Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(Z6,{items:XJ,onSelect:(N)=>{let I=N.value==="none"?void 0:N.value;G({...J,color:I}),B()}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="location")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(Z6,{items:[{label:"\uD83D\uDCC1 项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"\uD83C\uDFE0 用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(N)=>{G({...J,location:N.value}),B()}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="systemPrompt")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCAC Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"提示词: "},void 0,!1,void 0,this),b(X2,{value:J.systemPrompt,onChange:(N)=>G({...J,systemPrompt:N}),onSubmit:()=>B()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="confirm")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"✅ Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[b(f,{children:[b(f,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),b(f,{children:J.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),b(f,{children:J.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),b(f,{children:J.tools.includes("all")?"所有工具":J.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),b(f,{children:J.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),b(f,{children:J.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),b(f,{children:J.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b(Z6,{items:[{label:"✅ 确认并保存",value:"save"},{label:"⬅️ 返回上一步",value:"back"},{label:"❌ 取消",value:"cancel"}],onSelect:(N)=>{if(N.value==="save")E();else if(N.value==="back")A();else Y()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function JJ({config:$,setConfig:Y,onNext:Z,onPrev:X}){let{isFocused:Q}=tQ({id:"step-tools"});V3((G,q)=>{if(q.escape)X()},{isActive:Q});let J=(G)=>{if(G.includes("all"))Y({...$,tools:["all"]});else Y({...$,tools:G});Z()};return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDD27 Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(sQ,{options:ZJ,defaultValue:$.tools,onSubmit:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useMemoizedFn as J2}from"ahooks";import{Box as J0,Text as O0,useInput as GJ}from"ink";import O8 from"ink-select-input";import qJ from"node:fs";import{useMemo as KJ,useState as H8}from"react";import{jsxDEV as T}from"react/jsx-dev-runtime";function I3({initialMode:$="menu",onComplete:Y,onCancel:Z}){let[X,Q]=H8($),[J,G]=H8(null),[q,K]=H8(0),W=J2(()=>{B0.clear(),B0.loadFromStandardLocations(),K((B)=>B+1)}),O=KJ(()=>{return B0.getAllSubagents()},[q]),U=[{key:"list",label:"\uD83D\uDCCB 查看所有 Agents",value:"list"},{key:"create",label:"➕ 创建新 Agent",value:"create"},{key:"edit",label:"✏️ 编辑 Agent",value:"edit"},{key:"delete",label:"\uD83D\uDDD1️ 删除 Agent",value:"delete"},{key:"cancel",label:"❌ 取消",value:"cancel"}],H=J2((B)=>{if(B.value==="cancel"){Z?.();return}Q(B.value)}),_=J2((B)=>{if(G(B.value),X==="edit")Q("editWizard");else if(X==="delete")Q("deleteConfirm")}),z=J2(async()=>{if(!J?.configPath)return;try{await qJ.promises.unlink(J.configPath),W(),F()}catch(B){console.error("删除失败:",B)}}),F=J2(()=>{Q("menu"),G(null)}),L=b0(!1,Z);if(GJ((B,A)=>{if(A.escape){if(X==="menu")Z?.();else if(X==="list"||X==="edit"||X==="delete")F();else if(X==="deleteConfirm")F()}else if(A.ctrl&&B==="c"||A.meta&&B==="c")L()},{isActive:X!=="create"&&X!=="editWizard"}),X==="menu")return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(O8,{items:U,onSelect:H},void 0,!1,void 0,this),T(J0,{marginTop:1,children:T(O0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="list"){if(O.length===0)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{color:"gray",children:"\uD83D\uDCA1 配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:[T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this),T(O0,{color:"gray",children:[" (找到 ",O.length," 个)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),O.map((B)=>T(J0,{flexDirection:"column",paddingLeft:2,children:[T(J0,{children:T(O0,{children:[T(O0,{bold:!0,color:B.color||"white",children:["• ",B.name]},void 0,!0,void 0,this),T(O0,{color:"gray",children:[" - ",B.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),B.tools&&B.tools.length>0&&T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:["工具: ",B.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),B.configPath&&T(J0,{paddingLeft:2,children:T(O0,{color:"gray",dimColor:!0,children:B.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},B.name,!0,void 0,this)),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let w=(B)=>{if(O.length===0)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:B},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let A=O.map((V)=>({key:V.name,label:`${V.name} - ${V.description}`,value:V}));return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:B},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(O8,{items:A,onSelect:_},void 0,!1,void 0,this),T(J0,{marginTop:1,children:T(O0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(X==="create")return T(Q2,{onComplete:()=>{W(),F()},onCancel:F},void 0,!1,void 0,this);if(X==="edit")return w("✏️ 编辑 Agent");if(X==="editWizard"&&J){let B={name:J.name,description:J.description,tools:J.tools||[],color:J.color,location:J.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:J.systemPrompt||""};return T(Q2,{initialConfig:B,onComplete:()=>{W(),F()},onCancel:F},void 0,!1,void 0,this)}if(X==="delete")return w("\uD83D\uDDD1️ 删除 Agent");if(X==="deleteConfirm"&&J)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"red",children:"⚠️ 确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{children:["你确定要删除 Agent"," ",T(O0,{bold:!0,color:"yellow",children:J.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:["文件路径: ",J.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(O8,{items:[{label:"\uD83D\uDDD1️ 确认删除",value:"confirm"},{label:"❌ 取消",value:"cancel"}],onSelect:(B)=>{if(B.value==="confirm")z();else F()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as v$,Text as H0}from"ink";import UJ from"react";import{useEffect as WJ,useState as D3}from"react";function k3($=process.cwd(),Y=5000){let[Z,X]=D3(null),[Q,J]=D3(!0);return WJ(()=>{let G=!0,q=async()=>{try{let W=await e$($);if(!G)return;if(!W){X(null),J(!1);return}let O=await x5($);if(!G)return;X(O)}catch{if(G)X(null)}finally{if(G)J(!1)}};q();let K=null;if(Y>0)K=setInterval(q,Y);return()=>{if(G=!1,K)clearInterval(K)}},[$,Y]),{branch:Z,loading:Q}}import{jsxDEV as t,Fragment as X6}from"react/jsx-dev-runtime";var M3=UJ.memo(()=>{let $=r2(),Y=C1(),Z=V$(),Q=i2()==="shortcuts",J=A5(),{branch:G}=k3(),q=V5(),K=F5(),W=_5(),U=(()=>{if(Z==="default")return null;if(Z==="autoEdit")return t(H0,{color:"magenta",children:["▶▶ auto edit on ",t(H0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="plan")return t(H0,{color:"cyan",children:["‖ plan mode on ",t(H0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="yolo")return t(H0,{color:"red",children:["⚡ yolo mode on ",t(H0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),H=U!==null,_=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","↑/↓:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"]];return t(v$,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Q?t(v$,{flexDirection:"column",gap:0,children:_.map((z,F)=>t(v$,{flexDirection:"row",children:[z.map((L,w)=>{let[B,A]=L.split(":");return t(v$,{flexDirection:"row",width:20,children:[t(H0,{color:"yellow",children:B},void 0,!1,void 0,this),t(H0,{color:"gray",children:":"},void 0,!1,void 0,this),t(H0,{color:"white",children:A},void 0,!1,void 0,this)]},w,!0,void 0,this)}),F===_.length-1&&t(H0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},F,!0,void 0,this))},void 0,!1,void 0,this):t(v$,{flexDirection:"row",gap:1,children:[G&&t(X6,{children:[t(H0,{color:"gray",children:[" ",G]},void 0,!0,void 0,this),t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U,H&&t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(v$,{flexDirection:"row",gap:1,children:!$?t(H0,{color:"red",children:"⚠ API 密钥未配置"},void 0,!1,void 0,this):t(X6,{children:[q&&t(H0,{color:"gray",children:q.model},void 0,!1,void 0,this),t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),W?t(H0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):t(H0,{color:K<20?"red":K<50?"yellow":"gray",children:[K,"%"]},void 0,!0,void 0,this),Y&&t(X6,{children:[t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"yellow",children:"Processing..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J&&t(X6,{children:[t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as _8,Text as F8}from"ink";import OJ from"react";import{jsxDEV as y$}from"react/jsx-dev-runtime";var v3=OJ.memo(({suggestions:$,selectedIndex:Y,visible:Z,maxDisplay:X=8})=>{if(!Z||$.length===0)return null;let Q=0,J=Math.min(X,$.length),G=Y>=$.length;if(Y>=X&&!G)Q=Y-X+1,J=Y+1;let q=$.slice(Q,J),K=$.length>X;return y$(_8,{flexDirection:"column",paddingX:2,paddingY:0,children:[q.map((W,O)=>{let H=Q+O===Y;return y$(_8,{justifyContent:"space-between",paddingX:1,children:[y$(F8,{color:H?"cyan":"white",bold:H,children:W.command},void 0,!1,void 0,this),y$(F8,{color:H?"cyan":"gray",dimColor:!H,children:W.description},void 0,!1,void 0,this)]},W.command,!0,void 0,this)}),K&&y$(_8,{paddingX:1,children:y$(F8,{color:G?"cyan":"gray",bold:G,dimColor:!G,children:["... and ",$.length-X," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as o0,Text as K1,useInput as nJ}from"ink";import aJ from"ink-select-input";import{useMemo as oJ}from"react";import{useEffect as HJ,useState as _J}from"react";import{useStdout as FJ}from"ink";import{debounce as zJ}from"lodash-es";function E$($=200){let{stdout:Y}=FJ(),[Z,X]=_J(Y.columns||80);return HJ(()=>{let Q=zJ(()=>{X(Y.columns||80)},$);return Q(),Y.on("resize",Q),()=>{Y.off("resize",Q),Q.cancel()}},[Y,$]),Z}import{Box as k0,Text as T0}from"ink";import q6 from"react";var BJ={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},NJ={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},wJ={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},LJ={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},AJ={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},RJ={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},bJ={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},VJ={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#9a6700",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},IJ={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},DJ={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},kJ={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},MJ={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},vJ={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},N1=[{id:"ayu-dark",label:"Ayu Dark",theme:BJ,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:NJ,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:wJ,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:LJ,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:AJ,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:RJ,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:bJ,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:VJ,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:IJ,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:DJ,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:kJ,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:MJ,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:vJ,tags:["dark","japanese"]}];function Q6($){if(!$||typeof $!=="object")return!1;if(!$.name||typeof $.name!=="string")return!1;if(!$.colors||typeof $.colors!=="object")return!1;let Y=["primary","secondary","accent","success","warning","error","info","light","dark","muted","highlight"];for(let J of Y)if(!$.colors[J]||typeof $.colors[J]!=="string")return!1;if(!$.colors.text||typeof $.colors.text!=="object")return!1;if(!$.colors.background||typeof $.colors.background!=="object")return!1;if(!$.colors.border||typeof $.colors.border!=="object")return!1;let Z=["primary","secondary","muted","light"],X=["primary","secondary","dark"],Q=["light","dark"];for(let J of Z)if(!$.colors.text[J]||typeof $.colors.text[J]!=="string")return!1;for(let J of X)if(!$.colors.background[J]||typeof $.colors.background[J]!=="string")return!1;for(let J of Q)if(!$.colors.border[J]||typeof $.colors.border[J]!=="string")return!1;if(!$.spacing||typeof $.spacing!=="object")return!1;if(!$.typography||typeof $.typography!=="object")return!1;if(!$.borderRadius||typeof $.borderRadius!=="object")return!1;if(!$.boxShadow||typeof $.boxShadow!=="object")return!1;return!0}var y3={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},J6={name:"default",colors:y3,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},E3={...J6,name:"dark",colors:{...y3,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class z8{currentTheme=J6;themes=new Map;constructor(){this.themes.set("default",J6),this.themes.set("dark",E3);for(let $ of N1)this.themes.set($.id,$.theme)}setTheme($){let Y=this.themes.get($);if(Y)this.currentTheme=Y;else throw Error(`Theme '${$}' not found`)}getTheme(){return this.currentTheme}addTheme($,Y){if(!Q6(Y))throw Error(`Invalid theme configuration for '${$}'`);this.themes.set($,Y)}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName($){return this.themes.get($)}removeTheme($){if($==="default"||$==="dark"||N1.some((Z)=>Z.id===$))throw Error(`Cannot remove built-in theme '${$}'`);this.themes.delete($)}hasTheme($){return this.themes.has($)}validateTheme($){return Q6($)}}var $0=new z8;import{Box as j$,Text as f1}from"ink";import{common as yJ,createLowlight as EJ}from"lowlight";import jJ from"react";import{jsxDEV as j0}from"react/jsx-dev-runtime";var B8=EJ(yJ);function G6($,Y,Z=0){if($.type==="text")return j0(f1,{children:$.value},Z,!1,void 0,this);if($.type==="element"){let X=$.properties?.className?.[0]||"",Q=Y.default;if(X.includes("comment"))Q=Y.comment;else if(X.includes("string"))Q=Y.string;else if(X.includes("number"))Q=Y.number;else if(X.includes("keyword"))Q=Y.keyword;else if(X.includes("function"))Q=Y.function;else if(X.includes("variable"))Q=Y.variable;else if(X.includes("operator"))Q=Y.operator;else if(X.includes("type"))Q=Y.type;else if(X.includes("tag"))Q=Y.tag;else if(X.includes("attr"))Q=Y.attr;let J=$.children?.map((G,q)=>G6(G,Y,q));return j0(f1,{color:Q,children:J},Z,!1,void 0,this)}if($.type==="root"&&$.children)return j0(jJ.Fragment,{children:$.children.map((X,Q)=>G6(X,Y,Q))},Z,!1,void 0,this);return j0(f1,{},Z,!1,void 0,this)}function SJ($,Y,Z,X){let Q=Z||$0.getTheme().colors.syntax,J=$;if(X&&$.length>X)J=$.slice(0,X-3)+"...";try{if(!Y||!B8.registered(Y)){let q=B8.highlightAuto(J);return G6(q,Q)}let G=B8.highlight(Y,J);return G6(G,Q)}catch(G){return j0(f1,{color:Q.default,children:J},void 0,!1,void 0,this)}}var N8=({content:$,language:Y,showLineNumbers:Z=!0,terminalWidth:X,availableHeight:Q})=>{let J=$0.getTheme(),G=$.split(`
|
|
1490
|
-
`),
|
|
1491
|
-
`),Z=[],X=0,Q=0;for(let J of Y){if(J.startsWith("---")||J.startsWith("+++"))continue;if(J.startsWith("@@")){let
|
|
1489
|
+
`),p=_8.join(B,`${J.name}.md`);await k3.promises.writeFile(p,C,"utf-8"),$()}catch(B){console.error("保存配置失败:",B)}}),R=b0(!1,Y);if(M3((B,D)=>{if(D.escape)A();else if(D.ctrl&&B==="c"||D.meta&&B==="c")R()},{isActive:X!=="tools"}),X==="mode")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83C\uDFAF 选择创建方式"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"你可以手动配置每个细节,或让 AI 根据你的描述自动生成配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(J6,{items:[{label:"\uD83E\uDD16 AI 智能生成 - 根据描述自动生成完整配置",value:"ai"},{label:"✍️ 手动配置 - 逐步配置每个选项",value:"manual"}],onSelect:(B)=>{if(B.value==="ai")z("ai"),Q("aiPrompt");else z("manual"),Q("name")}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiPrompt")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83E\uDD16 AI 智能生成"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:'描述你想要创建的 Agent(例如:"一个专门用于代码审查的 agent,能够分析代码质量和潜在bug")'},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"描述: "},void 0,!1,void 0,this),b(J2,{value:G,onChange:K,onSubmit:(B)=>{if(!B.trim())return;Q("aiGenerating")}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 开始生成 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="aiGenerating"){if(U)return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"red",children:"❌ AI 生成失败"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{color:"red",children:U},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"按 ESC 返回修改描述"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"yellow",children:[b(JJ,{type:"dots"},void 0,!1,void 0,this)," AI 正在生成配置..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:['根据你的描述:"',G,'"']},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{color:"gray",children:"正在调用 LLM 生成 agent 配置,请稍候..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="name"){let B=_==="edit";return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:["\uD83D\uDCDD Step 1/7: ",B?"Agent 名称(不可修改)":"输入 Agent 名称"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:B?"编辑模式下名称不可修改(修改名称相当于创建新 Agent)":"名称只能包含小写字母、数字和连字符(例如:code-reviewer)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"名称: "},void 0,!1,void 0,this),B?b(f,{children:J.name},void 0,!1,void 0,this):b(J2,{value:J.name,onChange:(D)=>q({...J,name:D}),onSubmit:(D)=>{if(WJ(D))return;N()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:B?"按 Enter 继续 | ESC 返回":"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this),B&&b(J2,{value:"",onChange:()=>{},onSubmit:N,showCursor:!1},"edit-mode-dummy-input",!1,void 0,this)]},void 0,!0,void 0,this)}if(X==="description")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCDD Step 2/7: 输入描述信息"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"简短描述这个 Agent 的用途和使用场景(这将帮助主 Agent 决定何时使用它)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"描述: "},void 0,!1,void 0,this),b(J2,{value:J.description,onChange:(B)=>q({...J,description:B}),onSubmit:(B)=>{if(!B.trim())return;N()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="tools")return b(UJ,{config:J,setConfig:q,onNext:N,onPrev:A},void 0,!1,void 0,this);if(X==="color")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83C\uDFA8 Step 4/7: 选择背景颜色"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"为 Agent 选择一个颜色标识(用于在 UI 中区分不同的 Agents)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(J6,{items:KJ,onSelect:(B)=>{let D=B.value==="none"?void 0:B.value;q({...J,color:D}),N()}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="location")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 Step 5/7: 选择保存位置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"项目级配置仅在当前项目生效,用户级配置全局可用"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(J6,{items:[{label:"\uD83D\uDCC1 项目级 (.blade/agents/) - 仅当前项目",value:"project"},{label:"\uD83C\uDFE0 用户级 (~/.blade/agents/) - 全局可用",value:"user"}],onSelect:(B)=>{q({...J,location:B.value}),N()}},void 0,!1,void 0,this),b(g,{marginTop:1,children:b(f,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="systemPrompt")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDCAC Step 6/7: 输入系统提示词"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"定义 Agent 的行为和职责(可选,留空将使用默认提示)"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:[b(f,{color:"green",children:"提示词: "},void 0,!1,void 0,this),b(J2,{value:J.systemPrompt,onChange:(B)=>q({...J,systemPrompt:B}),onSubmit:()=>N()},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(g,{children:b(f,{dimColor:!0,children:"按 Enter 继续 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="confirm")return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"✅ Step 7/7: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{flexDirection:"column",paddingLeft:2,marginBottom:1,children:[b(f,{children:[b(f,{bold:!0,color:"green",children:["名称:"," "]},void 0,!0,void 0,this),b(f,{children:J.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["描述:"," "]},void 0,!0,void 0,this),b(f,{children:J.description},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["工具:"," "]},void 0,!0,void 0,this),b(f,{children:J.tools.includes("all")?"所有工具":J.tools.join(", ")||"所有工具"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["颜色:"," "]},void 0,!0,void 0,this),b(f,{children:J.color||"默认"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["位置:"," "]},void 0,!0,void 0,this),b(f,{children:J.location==="project"?"项目级":"用户级"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),b(f,{children:[b(f,{bold:!0,color:"green",children:["提示词:"," "]},void 0,!0,void 0,this),b(f,{children:J.systemPrompt||"(使用默认)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),b(J6,{items:[{label:"✅ 确认并保存",value:"save"},{label:"⬅️ 返回上一步",value:"back"},{label:"❌ 取消",value:"cancel"}],onSelect:(B)=>{if(B.value==="save")E();else if(B.value==="back")A();else Y()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}function UJ({config:$,setConfig:Y,onNext:Z,onPrev:X}){let{isFocused:Q}=XJ({id:"step-tools"});M3((q,G)=>{if(G.escape)X()},{isActive:Q});let J=(q)=>{if(q.includes("all"))Y({...$,tools:["all"]});else Y({...$,tools:q});Z()};return b(g,{flexDirection:"column",paddingY:1,children:[b(g,{marginBottom:1,children:b(f,{bold:!0,color:"cyan",children:"\uD83D\uDD27 Step 3/7: 选择可用工具"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(g,{marginBottom:1,children:b(f,{dimColor:!0,children:"方向键导航,空格切换勾选,Enter 确认进入下一步 | ESC 返回上一步"},void 0,!1,void 0,this)},void 0,!1,void 0,this),b(ZJ,{options:GJ,defaultValue:$.tools,onSubmit:J},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}import{useMemoizedFn as G2}from"ahooks";import{Box as J0,Text as O0,useInput as OJ}from"ink";import F8 from"ink-select-input";import HJ from"node:fs";import{useMemo as _J,useState as z8}from"react";import{jsxDEV as T}from"react/jsx-dev-runtime";function y3({initialMode:$="menu",onComplete:Y,onCancel:Z}){let[X,Q]=z8($),[J,q]=z8(null),[G,K]=z8(0),W=G2(()=>{N0.clear(),N0.loadFromStandardLocations(),K((N)=>N+1)}),O=_J(()=>{return N0.getAllSubagents()},[G]),U=[{key:"list",label:"\uD83D\uDCCB 查看所有 Agents",value:"list"},{key:"create",label:"➕ 创建新 Agent",value:"create"},{key:"edit",label:"✏️ 编辑 Agent",value:"edit"},{key:"delete",label:"\uD83D\uDDD1️ 删除 Agent",value:"delete"},{key:"cancel",label:"❌ 取消",value:"cancel"}],H=G2((N)=>{if(N.value==="cancel"){Z?.();return}Q(N.value)}),_=G2((N)=>{if(q(N.value),X==="edit")Q("editWizard");else if(X==="delete")Q("deleteConfirm")}),z=G2(async()=>{if(!J?.configPath)return;try{await HJ.promises.unlink(J.configPath),W(),F()}catch(N){console.error("删除失败:",N)}}),F=G2(()=>{Q("menu"),q(null)}),w=b0(!1,Z);if(OJ((N,A)=>{if(A.escape){if(X==="menu")Z?.();else if(X==="list"||X==="edit"||X==="delete")F();else if(X==="deleteConfirm")F()}else if(A.ctrl&&N==="c"||A.meta&&N==="c")w()},{isActive:X!=="create"&&X!=="editWizard"}),X==="menu")return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB Agents 管理"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(F8,{items:U,onSelect:H},void 0,!1,void 0,this),T(J0,{marginTop:1,children:T(O0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(X==="list"){if(O.length===0)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{color:"gray",children:"\uD83D\uDCA1 配置文件位置: .blade/agents/ 或 ~/.blade/agents/"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:[T(O0,{bold:!0,color:"cyan",children:"\uD83D\uDCCB 所有 Agents"},void 0,!1,void 0,this),T(O0,{color:"gray",children:[" (找到 ",O.length," 个)"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),O.map((N)=>T(J0,{flexDirection:"column",paddingLeft:2,children:[T(J0,{children:T(O0,{children:[T(O0,{bold:!0,color:N.color||"white",children:["• ",N.name]},void 0,!0,void 0,this),T(O0,{color:"gray",children:[" - ",N.description]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.tools&&N.tools.length>0&&T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:["工具: ",N.tools.join(", ")]},void 0,!0,void 0,this)},void 0,!1,void 0,this),N.configPath&&T(J0,{paddingLeft:2,children:T(O0,{color:"gray",dimColor:!0,children:N.configPath},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},N.name,!0,void 0,this)),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let L=(N)=>{if(O.length===0)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{paddingLeft:2,children:T(O0,{color:"gray",children:"❌ 没有找到任何 agent 配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginTop:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:"按 ESC 返回菜单"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this);let A=O.map((V)=>({key:V.name,label:`${V.name} - ${V.description}`,value:V}));return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"cyan",children:N},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(F8,{items:A,onSelect:_},void 0,!1,void 0,this),T(J0,{marginTop:1,children:T(O0,{dimColor:!0,children:"使用方向键选择 | Enter 确认 | ESC 返回"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};if(X==="create")return T(q2,{onComplete:()=>{W(),F()},onCancel:F},void 0,!1,void 0,this);if(X==="edit")return L("✏️ 编辑 Agent");if(X==="editWizard"&&J){let N={name:J.name,description:J.description,tools:J.tools||[],color:J.color,location:J.configPath?.includes(".blade/agents")?"project":"user",systemPrompt:J.systemPrompt||""};return T(q2,{initialConfig:N,onComplete:()=>{W(),F()},onCancel:F},void 0,!1,void 0,this)}if(X==="delete")return L("\uD83D\uDDD1️ 删除 Agent");if(X==="deleteConfirm"&&J)return T(J0,{flexDirection:"column",paddingY:1,children:[T(J0,{marginBottom:1,children:T(O0,{bold:!0,color:"red",children:"⚠️ 确认删除"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{children:["你确定要删除 Agent"," ",T(O0,{bold:!0,color:"yellow",children:J.name},void 0,!1,void 0,this)," ","吗?"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{dimColor:!0,children:["文件路径: ",J.configPath]},void 0,!0,void 0,this)},void 0,!1,void 0,this),T(J0,{marginBottom:1,paddingLeft:2,children:T(O0,{color:"red",children:"此操作无法撤销!"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T(F8,{items:[{label:"\uD83D\uDDD1️ 确认删除",value:"confirm"},{label:"❌ 取消",value:"cancel"}],onSelect:(N)=>{if(N.value==="confirm")z();else F()}},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null}import{Box as E$,Text as H0}from"ink";import zJ from"react";import{useEffect as FJ,useState as E3}from"react";function j3($=process.cwd(),Y=5000){let[Z,X]=E3(null),[Q,J]=E3(!0);return FJ(()=>{let q=!0,G=async()=>{try{let W=await Y2($);if(!q)return;if(!W){X(null),J(!1);return}let O=await d5($);if(!q)return;X(O)}catch{if(q)X(null)}finally{if(q)J(!1)}};G();let K=null;if(Y>0)K=setInterval(G,Y);return()=>{if(q=!1,K)clearInterval(K)}},[$,Y]),{branch:Z,loading:Q}}import{jsxDEV as t,Fragment as q6}from"react/jsx-dev-runtime";var P3=zJ.memo(()=>{let $=o2(),Y=f1(),Z=I$(),Q=n2()==="shortcuts",J=I5(),{branch:q}=j3(),G=M5(),K=w5(),W=L5(),U=(()=>{if(Z==="default")return null;if(Z==="autoEdit")return t(H0,{color:"magenta",children:["▶▶ auto edit on ",t(H0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="plan")return t(H0,{color:"cyan",children:["‖ plan mode on ",t(H0,{color:"gray",children:"(shift+tab to cycle)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);if(Z==="yolo")return t(H0,{color:"red",children:["⚡ yolo mode on ",t(H0,{color:"gray",children:"(all tools auto-approved)"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return null})(),H=U!==null,_=[["Enter:发送","Shift+Enter:换行","Esc:中止"],["Shift+Tab:切换模式","↑/↓:历史","Tab:补全"],["Ctrl+A:行首","Ctrl+E:行尾","Ctrl+K:删到尾"],["Ctrl+U:删到首","Ctrl+W:删单词","Ctrl+C:退出"]];return t(E$,{flexDirection:"row",justifyContent:"space-between",paddingX:2,paddingY:0,children:[Q?t(E$,{flexDirection:"column",gap:0,children:_.map((z,F)=>t(E$,{flexDirection:"row",children:[z.map((w,L)=>{let[N,A]=w.split(":");return t(E$,{flexDirection:"row",width:20,children:[t(H0,{color:"yellow",children:N},void 0,!1,void 0,this),t(H0,{color:"gray",children:":"},void 0,!1,void 0,this),t(H0,{color:"white",children:A},void 0,!1,void 0,this)]},L,!0,void 0,this)}),F===_.length-1&&t(H0,{color:"cyan",children:" ? 关闭"},void 0,!1,void 0,this)]},F,!0,void 0,this))},void 0,!1,void 0,this):t(E$,{flexDirection:"row",gap:1,children:[q&&t(q6,{children:[t(H0,{color:"gray",children:[" ",q]},void 0,!0,void 0,this),t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),U,H&&t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"gray",children:"? for shortcuts"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),t(E$,{flexDirection:"row",gap:1,children:!$?t(H0,{color:"red",children:"⚠ API 密钥未配置"},void 0,!1,void 0,this):t(q6,{children:[G&&t(H0,{color:"gray",children:G.model},void 0,!1,void 0,this),t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),W?t(H0,{color:"yellow",children:"压缩中..."},void 0,!1,void 0,this):t(H0,{color:K<20?"red":K<50?"yellow":"gray",children:[K,"%"]},void 0,!0,void 0,this),Y&&t(q6,{children:[t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"yellow",children:"Processing..."},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J&&t(q6,{children:[t(H0,{color:"gray",children:"·"},void 0,!1,void 0,this),t(H0,{color:"yellow",children:"再按一次 Ctrl+C 退出"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as N8,Text as B8}from"ink";import NJ from"react";import{jsxDEV as j$}from"react/jsx-dev-runtime";var S3=NJ.memo(({suggestions:$,selectedIndex:Y,visible:Z,maxDisplay:X=8})=>{if(!Z||$.length===0)return null;let Q=0,J=Math.min(X,$.length),q=Y>=$.length;if(Y>=X&&!q)Q=Y-X+1,J=Y+1;let G=$.slice(Q,J),K=$.length>X;return j$(N8,{flexDirection:"column",paddingX:2,paddingY:0,children:[G.map((W,O)=>{let H=Q+O===Y;return j$(N8,{justifyContent:"space-between",paddingX:1,children:[j$(B8,{color:H?"cyan":"white",bold:H,children:W.command},void 0,!1,void 0,this),j$(B8,{color:H?"cyan":"gray",dimColor:!H,children:W.description},void 0,!1,void 0,this)]},W.command,!0,void 0,this)}),K&&j$(N8,{paddingX:1,children:j$(B8,{color:q?"cyan":"gray",bold:q,dimColor:!q,children:["... and ",$.length-X," more"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as s0,Text as K1,useInput as eJ}from"ink";import $q from"ink-select-input";import{useMemo as Yq}from"react";import{useEffect as BJ,useState as LJ}from"react";import{useStdout as wJ}from"ink";import{debounce as AJ}from"lodash-es";function P$($=200){let{stdout:Y}=wJ(),[Z,X]=LJ(Y.columns||80);return BJ(()=>{let Q=AJ(()=>{X(Y.columns||80)},$);return Q(),Y.on("resize",Q),()=>{Y.off("resize",Q),Q.cancel()}},[Y,$]),Z}import{Box as v0,Text as f0}from"ink";import U6 from"react";var RJ={name:"ayu-dark",colors:{primary:"#ffcc66",secondary:"#bae67e",accent:"#73d0ff",success:"#bae67e",warning:"#ffcc66",error:"#ff3333",info:"#73d0ff",light:"#f0f0f0",dark:"#000000",muted:"#5c6773",highlight:"#2d323b",text:{primary:"#e6e1cf",secondary:"#bae67e",muted:"#5c6773",light:"#ffffff"},background:{primary:"#0f1419",secondary:"#14191f",dark:"#000000"},border:{light:"#2d323b",dark:"#000000"},syntax:{comment:"#5c6773",string:"#bae67e",number:"#ffcc66",keyword:"#ff8f40",function:"#73d0ff",variable:"#e6e1cf",operator:"#f29e74",type:"#73d0ff",tag:"#ff8f40",attr:"#ffd580",default:"#e6e1cf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.2)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.3), 0 1px 2px 0 rgba(0, 0, 0, 0.2)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.2)"}},bJ={name:"dracula",colors:{primary:"#bd93f9",secondary:"#ffb86c",accent:"#ff79c6",success:"#50fa7b",warning:"#f1fa8c",error:"#ff5555",info:"#8be9fd",light:"#f8f8f2",dark:"#282a36",muted:"#6272a4",highlight:"#44475a",text:{primary:"#f8f8f2",secondary:"#f1fa8c",muted:"#6272a4",light:"#ffffff"},background:{primary:"#282a36",secondary:"#44475a",dark:"#21222c"},border:{light:"#44475a",dark:"#000000"},syntax:{comment:"#6272a4",string:"#f1fa8c",number:"#bd93f9",keyword:"#ff79c6",function:"#50fa7b",variable:"#f8f8f2",operator:"#ff79c6",type:"#8be9fd",tag:"#ff79c6",attr:"#50fa7b",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 42, 54, 0.2)",base:"0 1px 3px 0 rgba(40, 42, 54, 0.3), 0 1px 2px 0 rgba(40, 42, 54, 0.2)",lg:"0 10px 15px -3px rgba(40, 42, 54, 0.3), 0 4px 6px -2px rgba(40, 42, 54, 0.2)"}},VJ={name:"monokai",colors:{primary:"#66d9ef",secondary:"#a6e22e",accent:"#f92672",success:"#a6e22e",warning:"#e6db74",error:"#f92672",info:"#66d9ef",light:"#f8f8f2",dark:"#272822",muted:"#75715e",highlight:"#3e3d32",text:{primary:"#f8f8f2",secondary:"#e6db74",muted:"#75715e",light:"#ffffff"},background:{primary:"#272822",secondary:"#3e3d32",dark:"#1e1f1c"},border:{light:"#3e3d32",dark:"#000000"},syntax:{comment:"#75715e",string:"#e6db74",number:"#ae81ff",keyword:"#f92672",function:"#a6e22e",variable:"#f8f8f2",operator:"#f92672",type:"#66d9ef",tag:"#f92672",attr:"#a6e22e",default:"#f8f8f2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(39, 40, 34, 0.2)",base:"0 1px 3px 0 rgba(39, 40, 34, 0.3), 0 1px 2px 0 rgba(39, 40, 34, 0.2)",lg:"0 10px 15px -3px rgba(39, 40, 34, 0.3), 0 4px 6px -2px rgba(39, 40, 34, 0.2)"}},DJ={name:"nord",colors:{primary:"#88c0d0",secondary:"#81a1c1",accent:"#b48ead",success:"#a3be8c",warning:"#ebcb8b",error:"#bf616a",info:"#88c0d0",light:"#eceff4",dark:"#2e3440",muted:"#4c566a",highlight:"#434c5e",text:{primary:"#eceff4",secondary:"#d8dee9",muted:"#4c566a",light:"#ffffff"},background:{primary:"#2e3440",secondary:"#3b4252",dark:"#242933"},border:{light:"#434c5e",dark:"#000000"},syntax:{comment:"#616e88",string:"#a3be8c",number:"#b48ead",keyword:"#81a1c1",function:"#88c0d0",variable:"#d8dee9",operator:"#81a1c1",type:"#8fbcbb",tag:"#81a1c1",attr:"#8fbcbb",default:"#eceff4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(46, 52, 64, 0.2)",base:"0 1px 3px 0 rgba(46, 52, 64, 0.3), 0 1px 2px 0 rgba(46, 52, 64, 0.2)",lg:"0 10px 15px -3px rgba(46, 52, 64, 0.3), 0 4px 6px -2px rgba(46, 52, 64, 0.2)"}},IJ={name:"solarized-light",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#93a1a1",highlight:"#eee8d5",text:{primary:"#586e75",secondary:"#657b83",muted:"#93a1a1",light:"#002b36"},background:{primary:"#fdf6e3",secondary:"#eee8d5",dark:"#073642"},border:{light:"#eee8d5",dark:"#073642"},syntax:{comment:"#93a1a1",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#657b83",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#657b83"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(253, 246, 227, 0.2)",base:"0 1px 3px 0 rgba(253, 246, 227, 0.3), 0 1px 2px 0 rgba(253, 246, 227, 0.2)",lg:"0 10px 15px -3px rgba(253, 246, 227, 0.3), 0 4px 6px -2px rgba(253, 246, 227, 0.2)"}},kJ={name:"solarized-dark",colors:{primary:"#268bd2",secondary:"#2aa198",accent:"#d33682",success:"#859900",warning:"#b58900",error:"#dc322f",info:"#268bd2",light:"#fdf6e3",dark:"#073642",muted:"#586e75",highlight:"#073642",text:{primary:"#839496",secondary:"#93a1a1",muted:"#586e75",light:"#fdf6e3"},background:{primary:"#002b36",secondary:"#073642",dark:"#001f29"},border:{light:"#073642",dark:"#000000"},syntax:{comment:"#586e75",string:"#2aa198",number:"#d33682",keyword:"#859900",function:"#268bd2",variable:"#839496",operator:"#859900",type:"#b58900",tag:"#268bd2",attr:"#93a1a1",default:"#839496"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 43, 54, 0.2)",base:"0 1px 3px 0 rgba(0, 43, 54, 0.3), 0 1px 2px 0 rgba(0, 43, 54, 0.2)",lg:"0 10px 15px -3px rgba(0, 43, 54, 0.3), 0 4px 6px -2px rgba(0, 43, 54, 0.2)"}},vJ={name:"tokyo-night",colors:{primary:"#7aa2f7",secondary:"#7dcfff",accent:"#bb9af7",success:"#9ece6a",warning:"#e0af68",error:"#f7768e",info:"#7aa2f7",light:"#c0caf5",dark:"#1a1b26",muted:"#565f89",highlight:"#292e42",text:{primary:"#a9b1d6",secondary:"#c0caf5",muted:"#565f89",light:"#ffffff"},background:{primary:"#1a1b26",secondary:"#292e42",dark:"#16161e"},border:{light:"#292e42",dark:"#000000"},syntax:{comment:"#565f89",string:"#9ece6a",number:"#ff9e64",keyword:"#bb9af7",function:"#7aa2f7",variable:"#c0caf5",operator:"#89ddff",type:"#7dcfff",tag:"#f7768e",attr:"#7aa2f7",default:"#a9b1d6"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(26, 27, 38, 0.2)",base:"0 1px 3px 0 rgba(26, 27, 38, 0.3), 0 1px 2px 0 rgba(26, 27, 38, 0.2)",lg:"0 10px 15px -3px rgba(26, 27, 38, 0.3), 0 4px 6px -2px rgba(26, 27, 38, 0.2)"}},MJ={name:"github",colors:{primary:"#0969da",secondary:"#8250df",accent:"#bc4c00",success:"#1a7f37",warning:"#9a6700",error:"#d1242f",info:"#0969da",light:"#f6f8fa",dark:"#24292f",muted:"#6e7781",highlight:"#ddf4ff",text:{primary:"#24292f",secondary:"#57606a",muted:"#6e7781",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f6f8fa",dark:"#24292f"},border:{light:"#d0d7de",dark:"#24292f"},syntax:{comment:"#6e7781",string:"#0a3069",number:"#0550ae",keyword:"#cf222e",function:"#8250df",variable:"#24292f",operator:"#cf222e",type:"#0550ae",tag:"#116329",attr:"#0550ae",default:"#24292f"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(255, 255, 255, 0.2)",base:"0 1px 3px 0 rgba(255, 255, 255, 0.3), 0 1px 2px 0 rgba(255, 255, 255, 0.2)",lg:"0 10px 15px -3px rgba(255, 255, 255, 0.3), 0 4px 6px -2px rgba(255, 255, 255, 0.2)"}},yJ={name:"gruvbox",colors:{primary:"#83a598",secondary:"#8ec07c",accent:"#d3869b",success:"#b8bb26",warning:"#fabd2f",error:"#fb4934",info:"#83a598",light:"#fbf1c7",dark:"#282828",muted:"#928374",highlight:"#3c3836",text:{primary:"#ebdbb2",secondary:"#d5c4a1",muted:"#928374",light:"#ffffff"},background:{primary:"#282828",secondary:"#3c3836",dark:"#1d2021"},border:{light:"#3c3836",dark:"#000000"},syntax:{comment:"#928374",string:"#b8bb26",number:"#d3869b",keyword:"#fb4934",function:"#8ec07c",variable:"#ebdbb2",operator:"#fe8019",type:"#fabd2f",tag:"#fb4934",attr:"#b8bb26",default:"#ebdbb2"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 40, 40, 0.2)",base:"0 1px 3px 0 rgba(40, 40, 40, 0.3), 0 1px 2px 0 rgba(40, 40, 40, 0.2)",lg:"0 10px 15px -3px rgba(40, 40, 40, 0.3), 0 4px 6px -2px rgba(40, 40, 40, 0.2)"}},EJ={name:"one-dark",colors:{primary:"#61afef",secondary:"#c678dd",accent:"#e5c07b",success:"#98c379",warning:"#e5c07b",error:"#e06c75",info:"#56b6c2",light:"#abb2bf",dark:"#282c34",muted:"#5c6370",highlight:"#3e4451",text:{primary:"#abb2bf",secondary:"#c6c8d0",muted:"#5c6370",light:"#ffffff"},background:{primary:"#282c34",secondary:"#3e4451",dark:"#21252b"},border:{light:"#3e4451",dark:"#000000"},syntax:{comment:"#5c6370",string:"#98c379",number:"#d19a66",keyword:"#c678dd",function:"#61afef",variable:"#e06c75",operator:"#56b6c2",type:"#e5c07b",tag:"#e06c75",attr:"#d19a66",default:"#abb2bf"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(40, 44, 52, 0.2)",base:"0 1px 3px 0 rgba(40, 44, 52, 0.3), 0 1px 2px 0 rgba(40, 44, 52, 0.2)",lg:"0 10px 15px -3px rgba(40, 44, 52, 0.3), 0 4px 6px -2px rgba(40, 44, 52, 0.2)"}},jJ={name:"catppuccin",colors:{primary:"#89b4fa",secondary:"#cba6f7",accent:"#f5c2e7",success:"#a6e3a1",warning:"#f9e2af",error:"#f38ba8",info:"#89dceb",light:"#cdd6f4",dark:"#11111b",muted:"#6c7086",highlight:"#181825",text:{primary:"#cdd6f4",secondary:"#bac2de",muted:"#6c7086",light:"#ffffff"},background:{primary:"#1e1e2e",secondary:"#181825",dark:"#11111b"},border:{light:"#181825",dark:"#000000"},syntax:{comment:"#6c7086",string:"#a6e3a1",number:"#fab387",keyword:"#cba6f7",function:"#89b4fa",variable:"#cdd6f4",operator:"#89dceb",type:"#f5c2e7",tag:"#f38ba8",attr:"#89b4fa",default:"#cdd6f4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(30, 30, 46, 0.2)",base:"0 1px 3px 0 rgba(30, 30, 46, 0.3), 0 1px 2px 0 rgba(30, 30, 46, 0.2)",lg:"0 10px 15px -3px rgba(30, 30, 46, 0.3), 0 4px 6px -2px rgba(30, 30, 46, 0.2)"}},PJ={name:"rose-pine",colors:{primary:"#9ccfd8",secondary:"#c4a7e7",accent:"#f6c177",success:"#31748f",warning:"#f6c177",error:"#eb6f92",info:"#9ccfd8",light:"#e0def4",dark:"#191724",muted:"#6e6a86",highlight:"#1f1d2e",text:{primary:"#e0def4",secondary:"#cecacd",muted:"#6e6a86",light:"#ffffff"},background:{primary:"#191724",secondary:"#1f1d2e",dark:"#12101a"},border:{light:"#1f1d2e",dark:"#000000"},syntax:{comment:"#6e6a86",string:"#9ccfd8",number:"#ea9a97",keyword:"#c4a7e7",function:"#31748f",variable:"#e0def4",operator:"#f6c177",type:"#9ccfd8",tag:"#eb6f92",attr:"#f6c177",default:"#e0def4"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(25, 23, 36, 0.2)",base:"0 1px 3px 0 rgba(25, 23, 36, 0.3), 0 1px 2px 0 rgba(25, 23, 36, 0.2)",lg:"0 10px 15px -3px rgba(25, 23, 36, 0.3), 0 4px 6px -2px rgba(25, 23, 36, 0.2)"}},SJ={name:"kanagawa",colors:{primary:"#8ba4b0",secondary:"#a292a3",accent:"#c47fd5",success:"#76946a",warning:"#c0a36e",error:"#c34043",info:"#7e9cd8",light:"#dcd7ba",dark:"#1f1f28",muted:"#727169",highlight:"#2a2a37",text:{primary:"#dcd7ba",secondary:"#c8c093",muted:"#727169",light:"#ffffff"},background:{primary:"#1f1f28",secondary:"#2a2a37",dark:"#16161d"},border:{light:"#2a2a37",dark:"#000000"},syntax:{comment:"#727169",string:"#98bb6c",number:"#d27e99",keyword:"#957fb8",function:"#7e9cd8",variable:"#dcd7ba",operator:"#c0a36e",type:"#7aa89f",tag:"#c34043",attr:"#7fb4ca",default:"#dcd7ba"}},spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(31, 31, 40, 0.2)",base:"0 1px 3px 0 rgba(31, 31, 40, 0.3), 0 1px 2px 0 rgba(31, 31, 40, 0.2)",lg:"0 10px 15px -3px rgba(31, 31, 40, 0.3), 0 4px 6px -2px rgba(31, 31, 40, 0.2)"}},B1=[{id:"ayu-dark",label:"Ayu Dark",theme:RJ,tags:["dark","popular"]},{id:"dracula",label:"Dracula",theme:bJ,tags:["dark","popular"]},{id:"monokai",label:"Monokai",theme:VJ,tags:["dark","classic"]},{id:"nord",label:"Nord",theme:DJ,tags:["dark","minimal"]},{id:"solarized-light",label:"Solarized Light",theme:IJ,tags:["light"]},{id:"solarized-dark",label:"Solarized Dark",theme:kJ,tags:["dark"]},{id:"tokyo-night",label:"Tokyo Night",theme:vJ,tags:["dark","popular"]},{id:"github",label:"GitHub",theme:MJ,tags:["light","minimal"]},{id:"gruvbox",label:"Gruvbox",theme:yJ,tags:["dark","warm"]},{id:"one-dark",label:"One Dark",theme:EJ,tags:["dark","popular"]},{id:"catppuccin",label:"Catppuccin",theme:jJ,tags:["dark","pastel"]},{id:"rose-pine",label:"Rose Pine",theme:PJ,tags:["dark","elegant"]},{id:"kanagawa",label:"Kanagawa",theme:SJ,tags:["dark","japanese"]}];function G6($){if(!$||typeof $!=="object")return!1;if(!$.name||typeof $.name!=="string")return!1;if(!$.colors||typeof $.colors!=="object")return!1;let Y=["primary","secondary","accent","success","warning","error","info","light","dark","muted","highlight"];for(let J of Y)if(!$.colors[J]||typeof $.colors[J]!=="string")return!1;if(!$.colors.text||typeof $.colors.text!=="object")return!1;if(!$.colors.background||typeof $.colors.background!=="object")return!1;if(!$.colors.border||typeof $.colors.border!=="object")return!1;let Z=["primary","secondary","muted","light"],X=["primary","secondary","dark"],Q=["light","dark"];for(let J of Z)if(!$.colors.text[J]||typeof $.colors.text[J]!=="string")return!1;for(let J of X)if(!$.colors.background[J]||typeof $.colors.background[J]!=="string")return!1;for(let J of Q)if(!$.colors.border[J]||typeof $.colors.border[J]!=="string")return!1;if(!$.spacing||typeof $.spacing!=="object")return!1;if(!$.typography||typeof $.typography!=="object")return!1;if(!$.borderRadius||typeof $.borderRadius!=="object")return!1;if(!$.boxShadow||typeof $.boxShadow!=="object")return!1;return!0}var T3={primary:"#0066cc",secondary:"#6c757d",accent:"#e83e8c",success:"#28a745",warning:"#ffc107",error:"#dc3545",info:"#17a2b8",light:"#f8f9fa",dark:"#343a40",muted:"#6c757d",highlight:"#fff3cd",text:{primary:"#212529",secondary:"#6c757d",muted:"#6c757d",light:"#ffffff"},background:{primary:"#ffffff",secondary:"#f8f9fa",dark:"#343a40"},border:{light:"#dee2e6",dark:"#495057"},syntax:{comment:"#6c757d",string:"#28a745",number:"#e83e8c",keyword:"#007bff",function:"#17a2b8",variable:"#495057",operator:"#ffc107",type:"#007bff",tag:"#dc3545",attr:"#ffc107",default:"#212529"}},K6={name:"default",colors:T3,spacing:{xs:0.25,sm:0.5,md:1,lg:1.5,xl:2},typography:{fontSize:{xs:0.75,sm:0.875,base:1,lg:1.125,xl:1.25,"2xl":1.5,"3xl":1.875},fontWeight:{light:300,normal:400,medium:500,semibold:600,bold:700}},borderRadius:{sm:0.125,base:0.25,lg:0.5,xl:0.75},boxShadow:{sm:"0 1px 2px 0 rgba(0, 0, 0, 0.05)",base:"0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)",lg:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)"}},C3={...K6,name:"dark",colors:{...T3,text:{primary:"#ffffff",secondary:"#e2e8f0",muted:"#94a3b8",light:"#000000"},background:{primary:"#1e293b",secondary:"#334155",dark:"#0f172a"},border:{light:"#475569",dark:"#64748b"},syntax:{comment:"#94a3b8",string:"#34d399",number:"#f472b6",keyword:"#60a5fa",function:"#06b6d4",variable:"#e2e8f0",operator:"#fbbf24",type:"#60a5fa",tag:"#fb7185",attr:"#fbbf24",default:"#ffffff"}}};class L8{currentTheme=K6;themes=new Map;constructor(){this.themes.set("default",K6),this.themes.set("dark",C3);for(let $ of B1)this.themes.set($.id,$.theme)}setTheme($){let Y=this.themes.get($);if(Y)this.currentTheme=Y;else throw Error(`Theme '${$}' not found`)}getTheme(){return this.currentTheme}addTheme($,Y){if(!G6(Y))throw Error(`Invalid theme configuration for '${$}'`);this.themes.set($,Y)}getAvailableThemes(){return Array.from(this.themes.keys())}getCurrentThemeName(){return this.currentTheme.name}getThemeByName($){return this.themes.get($)}removeTheme($){if($==="default"||$==="dark"||B1.some((Z)=>Z.id===$))throw Error(`Cannot remove built-in theme '${$}'`);this.themes.delete($)}hasTheme($){return this.themes.has($)}validateTheme($){return G6($)}}var $0=new L8;import{Box as S$,Text as h1}from"ink";import{common as TJ,createLowlight as CJ}from"lowlight";import fJ from"react";import{jsxDEV as j0}from"react/jsx-dev-runtime";var w8=CJ(TJ);function W6($,Y,Z=0){if($.type==="text")return j0(h1,{children:$.value},Z,!1,void 0,this);if($.type==="element"){let X=$.properties?.className?.[0]||"",Q=Y.default;if(X.includes("comment"))Q=Y.comment;else if(X.includes("string"))Q=Y.string;else if(X.includes("number"))Q=Y.number;else if(X.includes("keyword"))Q=Y.keyword;else if(X.includes("function"))Q=Y.function;else if(X.includes("variable"))Q=Y.variable;else if(X.includes("operator"))Q=Y.operator;else if(X.includes("type"))Q=Y.type;else if(X.includes("tag"))Q=Y.tag;else if(X.includes("attr"))Q=Y.attr;let J=$.children?.map((q,G)=>W6(q,Y,G));return j0(h1,{color:Q,children:J},Z,!1,void 0,this)}if($.type==="root"&&$.children)return j0(fJ.Fragment,{children:$.children.map((X,Q)=>W6(X,Y,Q))},Z,!1,void 0,this);return j0(h1,{},Z,!1,void 0,this)}function hJ($,Y,Z,X){let Q=Z||$0.getTheme().colors.syntax,J=$;if(X&&$.length>X)J=$.slice(0,X-3)+"...";try{if(!Y||!w8.registered(Y)){let G=w8.highlightAuto(J);return W6(G,Q)}let q=w8.highlight(Y,J);return W6(q,Q)}catch(q){return j0(h1,{color:Q.default,children:J},void 0,!1,void 0,this)}}var A8=({content:$,language:Y,showLineNumbers:Z=!0,terminalWidth:X,availableHeight:Q})=>{let J=$0.getTheme(),q=$.split(`
|
|
1490
|
+
`),G=0;if(Q&&q.length>Q){let H=Math.max(Q,5);if(q.length>H)G=q.length-H,q=q.slice(G)}let K=q.length+G,W=String(K).length+1,O=Math.max(20,X-W-6);return j0(S$,{borderStyle:"round",borderColor:J.colors.border.light,paddingX:1,paddingY:0,marginY:1,flexDirection:"column",children:[Y&&j0(S$,{marginBottom:0,children:j0(h1,{color:J.colors.text.secondary,children:Y},void 0,!1,void 0,this)},void 0,!1,void 0,this),G>0&&j0(S$,{marginBottom:0,children:j0(h1,{color:J.colors.text.muted,dimColor:!0,children:["... ",G," lines hidden ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this),q.map((U,H)=>{let _=H+G+1;return j0(S$,{flexDirection:"row",children:[Z&&j0(S$,{width:W,children:j0(h1,{color:J.colors.text.muted,dimColor:!0,children:String(_).padStart(W-1," ")},void 0,!1,void 0,this)},void 0,!1,void 0,this),j0(S$,{flexShrink:1,children:U.trim()===""?j0(h1,{children:" "},void 0,!1,void 0,this):hJ(U,Y,J.colors.syntax,O)},void 0,!1,void 0,this)]},H,!0,void 0,this)})]},void 0,!0,void 0,this)};import{Box as f3,Text as L1}from"ink";import{jsxDEV as r0}from"react/jsx-dev-runtime";function xJ($){let Y=$.split(`
|
|
1491
|
+
`),Z=[],X=0,Q=0;for(let J of Y){if(J.startsWith("---")||J.startsWith("+++"))continue;if(J.startsWith("@@")){let q=J.match(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/);if(q)X=parseInt(q[1],10),Q=parseInt(q[3],10);Z.push({type:"header",content:J});continue}if(J.startsWith("-")){Z.push({type:"remove",content:J.substring(1),lineNumber:X}),X++;continue}if(J.startsWith("+")){Z.push({type:"add",content:J.substring(1),lineNumber:Q}),Q++;continue}if(J.startsWith(" ")||J===""){Z.push({type:"context",content:J.substring(1),lineNumber:Q}),X++,Q++;continue}}return Z}var R8=({patch:$,startLine:Y,matchLine:Z,terminalWidth:X,maxLines:Q=20})=>{let J=$0.getTheme(),q=xJ($),K=Math.max(...q.map((_)=>_.lineNumber||0)).toString().length+1,W=q.length,O=W>Q,U=O?q.slice(0,Q):q,H=W-Q;return r0(f3,{flexDirection:"column",marginTop:1,marginBottom:1,children:[r0(L1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,X)))},void 0,!1,void 0,this),O&&r0(L1,{color:J.colors.info,children:["\uD83D\uDCCA 显示前 ",Q," 行,共 ",W," 行 diff"]},void 0,!0,void 0,this),O&&r0(L1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,X)))},void 0,!1,void 0,this),U.map((_,z)=>{if(_.type==="header")return r0(L1,{color:J.colors.muted,dimColor:!0,children:_.content},z,!1,void 0,this);let F=_.lineNumber?_.lineNumber.toString().padStart(K," "):" ".repeat(K),w=" ",L,N;if(_.type==="add")w="+",N=J.colors.success,L=void 0;else if(_.type==="remove")w="-",N=J.colors.error,L=void 0;else N=J.colors.text.primary;let A=Math.max(0,X-K-2),V=_.content;if(V.length>A)V=V.substring(0,A-3)+"...";return r0(L1,{color:N,backgroundColor:L,children:[r0(L1,{dimColor:!0,children:F},void 0,!1,void 0,this),r0(L1,{children:w},void 0,!1,void 0,this),r0(L1,{children:[" ",V]},void 0,!0,void 0,this)]},z,!0,void 0,this)}),O&&r0(f3,{marginTop:1,children:r0(L1,{color:J.colors.warning,dimColor:!0,children:["⚠️ 已隐藏剩余 ",H," 行 diff(总共 ",W," 行)"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),r0(L1,{color:J.colors.muted,children:"─".repeat(Math.max(0,Math.min(60,X)))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Text as q1}from"ink";import gJ from"react";import pJ from"string-width";var Z$=($)=>{let Y=$.replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/`(.*?)`/g,"$1").replace(/<u>(.*?)<\/u>/g,"$1").replace(/\[(.*?)\]\(.*?\)/g,"$1");return pJ(Y)},h3=($,Y,Z="...")=>{if(Z$($)<=Y)return $;if(Y<=Z.length)return Z.substring(0,Y);let Q=0,J=$.length,q="";while(Q<=J){let G=Math.floor((Q+J)/2),K=$.substring(0,G);if(Z$(K)<=Y-Z.length)q=K,Q=G+1;else J=G-1}return q+Z},x3=($)=>{return/[*_~`<[\]https?:]/.test($)};import{jsxDEV as a0,Fragment as uJ}from"react/jsx-dev-runtime";var b8=2,V8=1,D8=2;var mJ=({text:$})=>{let Y=$0.getTheme();if(!x3($))return a0(q1,{children:$},void 0,!1,void 0,this);let Z=[],X=0,Q=/(\*\*.*?\*\*|\*(?!\s).*?(?<!\s)\*|_(?!\s).*?(?<!\s)_|~~.*?~~|`+[^`]+`+|\[.*?\]\(.*?\)|https?:\/\/\S+)/g,J;while((J=Q.exec($))!==null){if(J.index>X)Z.push(a0(q1,{children:$.slice(X,J.index)},`t-${X}`,!1,void 0,this));let q=J[0],G=null,K=`m-${J.index}`;try{if(q.startsWith("**")&&q.endsWith("**")&&q.length>b8*2)G=a0(q1,{bold:!0,children:q.slice(b8,-b8)},K,!1,void 0,this);else if(q.length>V8*2&&(q.startsWith("*")&&q.endsWith("*")||q.startsWith("_")&&q.endsWith("_"))){let W=$.substring(J.index-1,J.index),O=$.substring(Q.lastIndex,Q.lastIndex+1);if(!(/\w/.test(W)||/\w/.test(O)||/[./\\]/.test(W+O)))G=a0(q1,{italic:!0,children:q.slice(V8,-V8)},K,!1,void 0,this)}else if(q.startsWith("~~")&&q.endsWith("~~")&&q.length>D8*2)G=a0(q1,{strikethrough:!0,children:q.slice(D8,-D8)},K,!1,void 0,this);else if(q.startsWith("`")&&q.endsWith("`")){let W=q.match(/^(`+)([^`]+)\1$/);if(W&&W[2])G=a0(q1,{color:Y.colors.syntax.keyword,backgroundColor:Y.colors.background.secondary,bold:!0,children:` ${W[2]} `},K,!1,void 0,this)}else if(q.startsWith("[")&&q.includes("](")&&q.endsWith(")")){let W=q.match(/\[(.*?)\]\((.*?)\)/);if(W){let O=W[1],U=W[2];G=a0(q1,{children:[O,a0(q1,{color:Y.colors.info,children:[" (",U,")"]},void 0,!0,void 0,this)]},K,!0,void 0,this)}}else if(q.match(/^https?:\/\//))G=a0(q1,{color:Y.colors.info,children:q},K,!1,void 0,this)}catch(W){console.error("InlineRenderer 解析错误:",q,W),G=null}Z.push(G??a0(q1,{children:q},K,!1,void 0,this)),X=Q.lastIndex}if(X<$.length)Z.push(a0(q1,{children:$.slice(X)},`t-${X}`,!1,void 0,this));return a0(uJ,{children:Z.filter((q)=>q!==null)},void 0,!1,void 0,this)},n0=gJ.memo(mJ);import{Box as I8,Text as p3}from"ink";import dJ from"react";import{jsxDEV as T$}from"react/jsx-dev-runtime";var cJ=({itemText:$,type:Y,marker:Z,leadingWhitespace:X=""})=>{let Q=Y==="ol"?`${Z}. `:`${Z} `,J=Q.length,q=X.length;return T$(I8,{paddingLeft:q+1,flexDirection:"row",children:[T$(I8,{width:J,children:T$(p3,{children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),T$(I8,{flexGrow:1,children:T$(p3,{wrap:"wrap",children:T$(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},g3=dJ.memo(cJ);import{Box as lJ,Text as X$}from"ink";import m3 from"react";import{jsxDEV as o0}from"react/jsx-dev-runtime";var u3=({headers:$,rows:Y,terminalWidth:Z})=>{let X=$0.getTheme();if($.length===0||Y.length===0)return null;let Q=$.map((H,_)=>{let z=Z$(H),F=Math.max(...Y.map((w)=>Z$(w[_]||"")));return Math.max(z,F)+2}),J=$.length+1,q=Q.reduce((H,_)=>H+_,0)+J,G=q>Z?Z/q:1,K=Q.map((H)=>Math.floor(H*G)),W=(H,_,z=!1)=>{let F=Math.max(0,_-2),w=Z$(H),L=H;if(w>F)L=h3(H,F);let N=Z$(L),A=Math.max(0,F-N);return o0(X$,{children:[z?o0(X$,{bold:!0,color:X.colors.primary,children:o0(n0,{text:L},void 0,!1,void 0,this)},void 0,!1,void 0,this):o0(n0,{text:L},void 0,!1,void 0,this)," ".repeat(A)]},void 0,!0,void 0,this)},O=(H)=>{let z={top:{left:"┌",middle:"┬",right:"┐",horizontal:"─"},middle:{left:"├",middle:"┼",right:"┤",horizontal:"─"},bottom:{left:"└",middle:"┴",right:"┘",horizontal:"─"}}[H],F=K.map((L)=>z.horizontal.repeat(L)),w=z.left+F.join(z.middle)+z.right;return o0(X$,{color:X.colors.text.muted,dimColor:!0,children:w},void 0,!1,void 0,this)},U=(H,_=!1)=>{let z=H.map((F,w)=>{let L=K[w]||0;return W(F||"",L,_)});return o0(X$,{children:[o0(X$,{color:X.colors.text.muted,children:"│ "},void 0,!1,void 0,this),z.map((F,w)=>o0(m3.Fragment,{children:[F,w<z.length-1&&o0(X$,{color:X.colors.text.muted,children:" │ "},void 0,!1,void 0,this)]},w,!0,void 0,this)),o0(X$,{color:X.colors.text.muted,children:" │"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};return o0(lJ,{flexDirection:"column",marginY:1,children:[O("top"),U($,!0),O("middle"),Y.map((H,_)=>o0(m3.Fragment,{children:U(H)},_,!1,void 0,this)),O("bottom")]},void 0,!0,void 0,this)};import{jsxDEV as x}from"react/jsx-dev-runtime";var iJ=($,Y)=>{let X=$0.getTheme().colors;switch($){case"user":return{color:X.info,prefix:"> "};case"assistant":return{color:X.success,prefix:"• "};case"system":return{color:X.warning,prefix:"⚙ "};case"tool":{let Q=Y&&"phase"in Y?Y.phase:void 0;return{color:X.text.secondary,prefix:Q==="start"?"• ":Q==="complete"?" └ ":" "}}default:return{color:X.text.primary,prefix:" "}}},G1={codeBlock:/^```(\w+)?\s*$/,heading:/^ *(#{1,4}) +(.+)/,ulItem:/^([ \t]*)([-*+]) +(.+)/,olItem:/^([ \t]*)(\d+)\. +(.+)/,hr:/^ *([-*_] *){3,} *$/,table:/^\|(.+)\|$/,tableSeparator:/^\|[\s]*:?-+:?[\s]*(\|[\s]*:?-+:?[\s]*)+\|?$/,diffStart:/^<<<DIFF>>>$/,diffEnd:/^<<<\/DIFF>>>$/};function rJ($){let Y=[],Z=$.split(/\r?\n/),X=!1,Q=[],J=null,q=!1,G=[],K=[],W=!1,O=[],U=!0;for(let H=0;H<Z.length;H++){let _=Z[H];if(W){if(_.match(G1.diffEnd)){try{let E=JSON.parse(O.join(`
|
|
1492
1492
|
`));Y.push({type:"diff",content:"",diffData:{patch:E.patch,startLine:E.startLine,matchLine:E.matchLine}})}catch(E){Y.push({type:"text",content:O.join(`
|
|
1493
|
-
`)})}W=!1,O=[],U=!1;continue}O.push(_);continue}if(_.match(
|
|
1494
|
-
`),language:J||void 0}),X=!1,Q=[],J=null,U=!1;else Q.push(_);continue}let z=_.match(
|
|
1495
|
-
`),language:J||void 0});if(G
|
|
1496
|
-
`),J=Q.length>50,
|
|
1497
|
-
`),K=q.includes("<<<DIFF>>>"),W=q.includes("```");if(K){let O=q.match(/<<<DIFF>>>\s*({[\s\S]*?})\s*<<<\/DIFF>>>/);if(O)try{let U=JSON.parse(O[1]);return x(k0,{flexDirection:"column",children:[x(w8,{patch:U.patch,startLine:U.startLine,matchLine:U.matchLine,terminalWidth:Y},void 0,!1,void 0,this),J&&x(k0,{marginTop:1,children:x(T0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}catch{}}if(W){let O=q.match(/```(\w+)?\s*\n([\s\S]*?)\n```/);if(O){let U=O[1]||"text",H=O[2];return x(k0,{flexDirection:"column",children:[x(N8,{content:H,language:U,showLineNumbers:!1,terminalWidth:Y},void 0,!1,void 0,this),J&&x(k0,{marginTop:1,children:x(T0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return x(k0,{flexDirection:"column",children:[G.map((O,U)=>x(T0,{color:Z.colors.text.primary,children:O},U,!1,void 0,this)),J&&x(k0,{marginTop:1,children:x(T0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),G2=q6.memo(({content:$,role:Y,terminalWidth:Z,metadata:X,isPending:Q=!1})=>{let J=q6.useMemo(()=>uJ(Y,X),[Y,X]),{color:G,prefix:q}=J;if(Y==="tool"&&X&&"detail"in X){let W=X;if(W.detail)return x(k0,{flexDirection:"column",marginBottom:1,children:[x(k0,{flexDirection:"row",children:[x(k0,{marginRight:1,children:x(T0,{color:G,bold:!0,children:q},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(T0,{color:G,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x(k0,{marginLeft:q.length+1,marginTop:1,children:x(rJ,{detail:W.detail,terminalWidth:Z-(q.length+1)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let K=q6.useMemo(()=>mJ($),[$]);return x(k0,{flexDirection:"column",marginBottom:1,children:K.map((W,O)=>{if(W.type==="empty")return x(k0,{height:1},O,!1,void 0,this);return x(k0,{flexDirection:"row",children:[O===0&&x(k0,{marginRight:1,children:x(T0,{color:G,bold:!0,children:q},void 0,!1,void 0,this)},void 0,!1,void 0,this),O>0&&x(k0,{width:q.length+1},void 0,!1,void 0,this),x(k0,{flexGrow:1,children:W.type==="code"?x(dJ,{content:W.content,language:W.language,terminalWidth:Z-(q.length+1)},void 0,!1,void 0,this):W.type==="table"&&W.tableData?x(h3,{headers:W.tableData.headers,rows:W.tableData.rows,terminalWidth:Z-(q.length+1)},void 0,!1,void 0,this):W.type==="heading"?x(cJ,{content:W.content,level:W.level||1},void 0,!1,void 0,this):W.type==="list"?x(C3,{type:W.listType||"ul",marker:W.marker||"-",itemText:W.content,leadingWhitespace:" ".repeat(W.indentation||0)},void 0,!1,void 0,this):W.type==="hr"?x(lJ,{terminalWidth:Z-(q.length+1)},void 0,!1,void 0,this):W.type==="diff"&&W.diffData?x(w8,{patch:W.diffData.patch,startLine:W.diffData.startLine,matchLine:W.diffData.matchLine,terminalWidth:Z-(q.length+1)},void 0,!1,void 0,this):x(iJ,{content:W.content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},O,!0,void 0,this)})},void 0,!1,void 0,this)},($,Y)=>{return $.content===Y.content&&$.role===Y.role&&$.terminalWidth===Y.terminalWidth&&$.isPending===Y.isPending&&JSON.stringify($.metadata)===JSON.stringify(Y.metadata)});import{jsxDEV as W0}from"react/jsx-dev-runtime";var sJ=({label:$,isSelected:Y})=>W0(K1,{color:Y?"yellow":void 0,children:$},void 0,!1,void 0,this),x3=({details:$,onResponse:Y})=>{let Z=E$(),Q=l0()==="confirmation-prompt",J=b0(!1);nJ((U,H)=>{if(H.ctrl&&U==="c"||H.meta&&U==="c"){J();return}if(H.escape){Y({approved:!1,reason:"用户取消"});return}let _=U.toLowerCase();if(G){if(_==="y"){Y({approved:!0,targetMode:"autoEdit"});return}if(_==="s"){Y({approved:!0,targetMode:"default"});return}if(_==="n"){Y({approved:!1,reason:"方案需要改进"});return}}else if(q){if(_==="y"){Y({approved:!0});return}if(_==="n"){Y({approved:!1,reason:"用户拒绝进入 Plan 模式"});return}}else{if(_==="y"){Y({approved:!0,scope:"once"});return}if(_==="s"){Y({approved:!0,scope:"session"});return}if(_==="n"){Y({approved:!1,reason:"用户拒绝"});return}}},{isActive:Q});let G=$.type==="exitPlanMode",q=$.type==="enterPlanMode",K=oJ(()=>{if(G)return[{key:"approve-auto",label:"[Y] Yes, execute with auto-edit mode",value:{approved:!0,targetMode:"autoEdit"}},{key:"approve-default",label:"[S] Yes, execute with default mode (ask for each operation)",value:{approved:!0,targetMode:"default"}},{key:"reject",label:"[N] No, keep planning",value:{approved:!1,reason:"方案需要改进"}}];if(q)return[{key:"approve",label:"[Y] Yes, enter Plan mode",value:{approved:!0}},{key:"reject",label:"[N] No, proceed directly",value:{approved:!1,reason:"用户拒绝进入 Plan 模式"}}];return[{key:"approve-once",label:"[Y] Yes (once only)",value:{approved:!0,scope:"once"}},{key:"approve-session",label:"[S] Yes, remember for this project (Shift+Tab)",value:{approved:!0,scope:"session"}},{key:"reject",label:"[N] No",value:{approved:!1,reason:"用户拒绝"}}]},[G,q]),O=(()=>{if(G)return{color:"cyan",title:"\uD83D\uDD35 Plan Mode - Review Implementation Plan"};if(q)return{color:"magenta",title:"\uD83D\uDFE3 Enter Plan Mode?"};return{color:"yellow",title:"\uD83D\uDD14 Confirmation Required"}})();return W0(o0,{flexDirection:"column",borderStyle:"round",borderColor:Q?O.color:"gray",padding:1,children:[W0(o0,{marginBottom:1,children:W0(K1,{bold:!0,color:O.color,children:O.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.title&&W0(o0,{marginBottom:1,children:W0(K1,{bold:!0,children:$.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),W0(o0,{marginBottom:1,children:W0(K1,{children:$.message},void 0,!1,void 0,this)},void 0,!1,void 0,this),($.planContent||$.details)&&W0(o0,{flexDirection:"column",marginBottom:1,borderStyle:"single",borderColor:O.color,padding:1,children:[W0(K1,{bold:!0,color:O.color,children:G?"\uD83D\uDCCB Implementation Plan:":q?"\uD83D\uDCDD Details:":"\uD83D\uDCC4 Operation Details:"},void 0,!1,void 0,this),W0(o0,{marginTop:1,children:W0(G2,{content:$.planContent||$.details||"",role:"assistant",terminalWidth:Z-4},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$.risks&&$.risks.length>0&&W0(o0,{flexDirection:"column",marginBottom:1,children:[W0(K1,{color:"red",bold:!0,children:"⚠️ 风险提示:"},void 0,!1,void 0,this),$.risks.map((U,H)=>W0(o0,{marginLeft:2,children:W0(K1,{color:"red",children:["• ",U]},void 0,!0,void 0,this)},H,!1,void 0,this))]},void 0,!0,void 0,this),$.affectedFiles&&$.affectedFiles.length>0&&W0(o0,{flexDirection:"column",marginBottom:1,children:[W0(K1,{color:"yellow",children:"\uD83D\uDCC1 影响的文件:"},void 0,!1,void 0,this),$.affectedFiles.slice(0,3).map((U,H)=>W0(o0,{marginLeft:2,children:W0(K1,{children:["• ",U]},void 0,!0,void 0,this)},H,!1,void 0,this)),$.affectedFiles.length>3&&W0(o0,{marginLeft:2,children:W0(K1,{color:"gray",children:["...还有 ",$.affectedFiles.length-3," 个文件"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W0(o0,{flexDirection:"column",children:[W0(K1,{color:"gray",children:"使用 ↑ ↓ 选择,回车确认(支持 Y/S/N 快捷键,ESC 取消)"},void 0,!1,void 0,this),W0(aJ,{items:K,isFocused:Q,itemComponent:sJ,onSelect:(U)=>{Y(U.value)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as r3}from"ahooks";import{Box as NG,Text as wG}from"ink";import LG from"react";import{writeFileSync as tJ}from"node:fs";import{join as eJ}from"node:path";import{tmpdir as $G}from"node:os";import{nanoid as YG}from"nanoid";function p3($,Y,Z){let X=ZG(Y),Q=Date.now(),J=YG(8),G=Z||`blade_image_${Q}_${J}.${X}`,q=$G(),K=eJ(q,G),W=Buffer.from($,"base64");tJ(K,W);let O=`[Image: ${G}]`;return console.log(`[ImageHandler] Saved image to: ${K}`),console.log(`[ImageHandler] Size: ${(W.length/1024).toFixed(2)} KB`),{filePath:K,filename:G,tag:O}}function ZG($){return{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","image/svg+xml":"svg"}[$]||"png"}import{useMemoizedFn as UG}from"ahooks";import X$ from"chalk";import{Text as OG,useInput as HG}from"ink";import{useEffect as l3,useRef as _G}from"react";var h1={TIMEOUT_MS:100,RAPID_INPUT_THRESHOLD_MS:150,LARGE_INPUT_THRESHOLD:300,MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD:200};import{execSync as XG}from"node:child_process";import{existsSync as UA,readFileSync as g3}from"node:fs";import{basename as u3,isAbsolute as QG}from"node:path";function JG(){let $=process.platform,Y={darwin:"No image found in clipboard. Use Cmd + Ctrl + Shift + 4 to copy a screenshot to clipboard.",win32:"No image found in clipboard. Use Print Screen to copy a screenshot to clipboard.",linux:"No image found in clipboard. Use appropriate screenshot tool to copy a screenshot to clipboard."};return Y[$]||Y.linux}var HA=JG();function GG($){try{let Y=Buffer.from($,"base64");if(Y.length<4)return"image/png";if(Y[0]===137&&Y[1]===80&&Y[2]===78&&Y[3]===71)return"image/png";if(Y[0]===255&&Y[1]===216&&Y[2]===255)return"image/jpeg";if(Y[0]===71&&Y[1]===73&&Y[2]===70)return"image/gif";if(Y[0]===82&&Y[1]===73&&Y[2]===70&&Y[3]===70){if(Y.length>=12&&Y[8]===87&&Y[9]===69&&Y[10]===66&&Y[11]===80)return"image/webp"}return"image/png"}catch{return"image/png"}}function qG(){let $=process.platform,Y={darwin:"/tmp/blade_cli_latest_screenshot.png",linux:"/tmp/blade_cli_latest_screenshot.png",win32:process.env.TEMP?`${process.env.TEMP}\\blade_cli_latest_screenshot.png`:"C:\\Temp\\blade_cli_latest_screenshot.png"},Z={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:(X)=>`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${X}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:(X)=>`rm -f "${X}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o | grep -E "image/(png|jpeg|jpg|gif|webp)"',saveImage:(X)=>`xclip -selection clipboard -t image/png -o > "${X}" || wl-paste --type image/png > "${X}"`,getPath:"xclip -selection clipboard -t text/plain -o",deleteFile:(X)=>`rm -f "${X}"`},win32:{checkImage:'powershell -Command "(Get-Clipboard -Format Image) -ne $null"',saveImage:(X)=>`powershell -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${X.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:'powershell -Command "Get-Clipboard"',deleteFile:(X)=>`del /f "${X}"`}};return{commands:Z[$]||Z.linux,screenshotPath:Y[$]||Y.linux}}function KG(){let{commands:$}=qG();try{return XG($.getPath,{encoding:"utf-8"}).trim()}catch(Y){return console.error("Failed to get clipboard path:",Y),null}}function m3($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}function d3($){if(process.platform==="win32")return $;let Y="__DOUBLE_BACKSLASH__";return $.replace(/\\\\/g,Y).replace(/\\(.)/g,"$1").replace(new RegExp(Y,"g"),"\\")}function V8($){let Y=m3($.trim()),Z=d3(Y);return/\.(png|jpe?g|gif|webp)$/i.test(Z)}function WG($){let Y=m3($.trim()),Z=d3(Y);if(V8(Z))return Z;return null}async function c3($){let Y=WG($);if(!Y)return null;let Z;try{if(QG(Y))Z=g3(Y);else{let G=KG();if(G&&Y===u3(G))Z=g3(G);else return null}}catch(G){return console.error("Failed to read image file:",G),null}let X=Z.toString("base64"),Q=GG(X),J=u3(Y);return{path:Y,base64:X,mediaType:Q,filename:J}}import{jsxDEV as BG}from"react/jsx-dev-runtime";var FG=/\r\n/g,zG=/\r/g;function K6($){if(!$.includes("\r"))return $;return $.replace(FG,`
|
|
1498
|
-
`).replace(
|
|
1499
|
-
`)}function
|
|
1500
|
-
`),V=
|
|
1501
|
-
`&&(F.shift||F.meta)){let{newValue:R,newCursorPosition:
|
|
1502
|
-
`)&&
|
|
1503
|
-
`).length,O=K.length,U=500,H=10;if(O>500||W>10){let _=K.slice(0,30).replace(/\n/g," ");return{prompt:`[Pasted: ${O} chars, ${W} lines] ${_}...`}}return{}}),q=r3(async(K,W,O)=>{try{return{prompt:`[Image saved to ${p3(K,W,O).filePath}. Note: Image attachments not yet supported by @ mentions] `}}catch(U){return console.error("[Image Paste] Failed to process image:",U),{prompt:`[Image paste failed: ${U instanceof Error?U.message:"Unknown error"}] `}}});return I8(NG,{flexDirection:"row",paddingX:2,paddingY:0,borderStyle:"round",borderColor:"gray",children:[I8(wG,{color:"blue",bold:!0,children:"> "},void 0,!1,void 0,this),I8(i3,{value:$,cursorPosition:Y,onChange:Z,onChangeCursorPosition:X,onPaste:G,onImagePaste:q,placeholder:" 输入命令...",focus:J,disabledKeys:["upArrow","downArrow","tab","return","escape"]},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as U6,Text as W1}from"ink";import IG,{useEffect as DG,useState as kG}from"react";import{useEffect as VG,useState as t3}from"react";import{useEffect as AG,useState as RG}from"react";var bG=15000,a3=["炼化代码灵气...","参悟 AST 道法...","推演算法天机...","重铸代码根基...","破解逻辑封印...","凝练类型真元...","铸就函数金丹...","渡劫编译雷劫...","打通模块任督二脉...","修炼 Tree-shaking 神功...","压缩代码乾坤...","布下 Source Map 阵法...","推演 Token 灵数...","炼制 Prompt 仙丹...","调息温度参数...","参透困惑度玄机...","驱动 LLM 灵力...","施展向量搜索术...","构筑 RAG 法阵...","凝聚 Embedding 道果...","勾连向量宝库...","破译函数咒语...","验证 Schema 真意...","封印工具参数...","注入系统道韵...","串联历史因果...","炼化抽象语法树...","破境重构神功...","感悟类型天道...","筑基模块根基...","施展词法轻功...","破解语法阵法...","参悟语义心法...","凝练中间内力...","修炼优化神功...","调息寄存器真气...","运转指令招式...","消除死码杂念...","折叠常量真元...","内联函数身法...","逃逸分析密探...","垃圾回收扫地僧...","标记清除掌法...","分代回收心诀...","增量收功法门...","JIT 即时顿悟...","解读字节码暗器...","V8 引擎神功...","召唤 WASM 傀儡...","开辟虚拟洞府...","丹田分配内存...","掌控栈帧乾坤...","捕获异常剑气...","尾调优化身法...","动态链接飞剑...","建立 TCP 金桥...","三次握手结契...","传送 HTTP 飞书...","破译响应符文...","TLS 秘境握手...","验证 SSL 信物...","WebSocket 通灵...","流式传功大法...","gRPC 御剑飞行...","Protobuf 封印术...","GraphQL 问道...","DNS 测算域名...","负载均衡五行阵...","CDN 边缘瞬移...","HTTP/2 分身术...","QUIC 闪现神通...","gzip 缩地成寸...","Brotli 玄冰压缩...","断点续传接续术...","分片上传合璧功...","参研 SQL 真经...","推演查询路径...","索引扫描神识...","全表扫描暴力突破...","执行 JOIN 双修大法...","聚合数据炼丹...","事务提交天地誓...","ACID 四象护法...","乐观锁道心无畏...","悲观锁剑阵守护...","分布式锁万里封禁...","Redis 炼药鼎缓存...","LRU 新陈代谢...","WAL 预写因果簿...","B+ 树平衡阴阳...","LSM 树合璧压缩...","向量宝库搜寻...","余弦相似度测算...","KNN 近邻追踪...","倒排索引翻阅秘籍...","快速排序剑法...","归并排序双刀...","堆排优化内功...","二分查找闪现...","深度优先潜行...","广度优先横扫...","Dijkstra 寻路神算...","A* 天机推演...","动态规划填棋盘...","回溯剑法剪枝...","贪心策略奇谋...","分治递归化身术...","哈希表扩容开天...","红黑树旋转太极...","AVL 树平衡阴阳...","跳表纵身轻功...","Trie 树千头万绪...","布隆过滤天罗地网...","一致性哈希环定乾坤...","最小生成树扎根...","Docker 镜像炼制...","Kubernetes 调兵遣将...","容器结界布阵...","卷挂载空间挪移...","Helm 符箓展开...","CI/CD 流水线作业...","GitHub 门派行动...","代码品鉴术...","漏洞探查密探...","依赖追溯寻根...","蓝绿部署换防...","金丝雀试探...","回滚时光倒流...","健康探查望闻问切...","日志归档藏经阁...","监控预警千里眼...","告警通知飞鸽传书...","性能调优筋骨重塑...","扩容缩容易筋经...","灰度发布声东击西...","React 虚影对决...","组件树调和大法...","Hooks 勾魂术...","useEffect 副作用因果...","Redux 中枢天宫...","Zustand 灵台藏识...","CSS-in-JS 画地为牢...","Tailwind 疾风步...","Webpack 热更换血重生...","Vite 按需凝形...","ESBuild 极速神行...","SWC 闪电炼形...","SSR 天地初开...","Hydration 魂归肉身...","Ink 终端墨宝...","虚拟 DOM 镜花水月...","事件冒泡顺流而上...","状态提升登峰造极...","懒加载厚积薄发...","代码分割庖丁解牛...","SHA-256 炼心咒...","AES-256 玄冰封印...","RSA 阴阳双钥...","JWT 信物令牌...","OAuth 门派授权...","CSRF 防御结界...","XSS 祛邪过滤...","SQL 注入克星...","PBKDF2 淬炼秘钥...","零知识誓言验证...","HTTPS 金钟罩...","签名验证印玺鉴定...","盐值加密炼丹配方...","双因素认证双重认证...","权限控制天条律令...","拜见图灵祖师爷...","冯·诺依曼传道...","Linus 大侠坐镇...","参悟 Rust 生命轮回...","逃离回调地狱轮回...","await 静待天时...","捕获野生 Bug 妖兽...","喂养橡皮鸭灵兽 \uD83E\uDD86...","炼丹调参秘术...","0xDEADBEEF 死亡凝视...","递归无限轮回...","闭包封印记忆...","Promise 未来契约...","async 异步神功...","Generator 分身术...","Proxy 替身傀儡...","Reflect 返照镜...","Symbol 独一无二印记...","WeakMap 过眼云烟...","Iterator 周而复始...","GitHub 武林大会...","Star 点赞声望...","Fork 拜师学艺...","Pull Request 挑战切磋...","Code Review 武功点评...","Issue 悬赏令...","Merge 收徒入门...","Commit 闭关修炼记录...","Branch 分支独辟蹊径...","Tag 里程碑界碑...","Release 出关发布...","License 门规戒律...","README 入门心法...","Documentation 武学秘籍...","Open Source 广纳贤才..."],o3=["Esc - 立即停止当前任务","Shift+Tab - 切换权限模式 (default/auto_edit/plan)","Tab - 智能补全斜杠命令","↑↓ - 浏览输入历史记录","双击 Esc - 快速清空输入框","Ctrl+C - 强制终止程序","Ctrl+D - 优雅退出 Blade","Ctrl+L - 清屏(保留历史)","Ctrl+R - 反向搜索历史","Ctrl+U - 清空当前行","/help - 查看完整帮助文档","/init - 生成 BLADE.md 项目配置","/resume - 恢复历史会话","/compact - 手动压缩上下文(节省 token)","/theme - 打开主题选择器","/config - 打开配置面板","/model - 管理与切换模型配置","/permissions - 管理工具权限规则","/mcp - 查看 MCP 服务器状态","/agents - 管理 Subagent 配置","/version - 显示版本信息","/clear - 清除屏幕内容","/status - 显示当前项目配置状态","/context - 可视化当前上下文使用情况","/cost - 显示会话成本统计","/exit - 退出 REPL","@ 文件路径 - 附加文件到上下文","@dir/ - 附加整个目录","@file.ts:10-20 - 附加指定行范围","Plan 模式 - 先规划后编码(/plan)","Auto Edit 模式 - 自动批准工具调用","MCP 协议 - 扩展外部工具集成","Subagents - 并行执行子任务","Hooks 系统 - 自定义工具执行流程","Context 压缩 - 自动总结历史对话","Loop 检测 - 防止无限循环","提示:使用 /init 让 AI 理解你的项目结构","提示:Plan 模式适合复杂多步骤任务","提示:Auto Edit 可加速重复性操作","提示:@ 引用可提供更精准的上下文","提示:定期 /compact 节省 token 成本","提示:使用 /permissions 控制工具权限","提示:Shift+Tab 快速切换模式","提示:Esc 可随时中断长时间任务","提示:/resume 继续未完成的对话","提示:/export 保存重要对话记录"];function s3($,Y){let[Z,X]=RG("");return AG(()=>{if(Y){X("等待用户确认...");return}if(!$){X("");return}let Q=()=>{if(Math.random()<0.16666666666666666){let K=Math.floor(Math.random()*o3.length);return o3[K]}let q=Math.floor(Math.random()*a3.length);return a3[q]};X(Q());let J=setInterval(()=>{X(Q())},bG);return()=>{clearInterval(J)}},[$,Y]),Z}function e3($,Y=!1){let[Z,X]=t3(0),[Q,J]=t3(null),G=s3($,Y);return VG(()=>{if(!$){X(0),J(null);return}if(Q===null)J(Date.now());let q=setInterval(()=>{if(Q!==null){let K=Math.floor((Date.now()-Q)/1000);X(K)}},1000);return()=>{clearInterval(q)}},[$,Q]),{currentPhrase:G,elapsedTime:Z}}import{jsxDEV as M0,Fragment as vG}from"react/jsx-dev-runtime";var D8=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],MG=80;function $Y($){if($<60)return`${$}s`;let Y=Math.floor($/60),Z=$%60;return`${Y}m ${Z}s`}var YY=IG.memo(({message:$})=>{let Y=C1(),Z=r2(),X=Y||!Z,[Q,J]=kG(0),G=$0.getTheme(),K=E$()>=MG,{currentPhrase:W,elapsedTime:O}=e3(X,!1);if(DG(()=>{if(!X){J(0);return}let H=setInterval(()=>{J((_)=>(_+1)%D8.length)},80);return()=>clearInterval(H)},[X]),!X)return null;let U=W||$||"正在思考中...";if(K)return M0(U6,{paddingX:2,paddingBottom:1,flexDirection:"row",gap:1,children:[M0(W1,{color:G.colors.warning,bold:!0,children:D8[Q]},void 0,!1,void 0,this),M0(W1,{color:G.colors.text.primary,children:U},void 0,!1,void 0,this),O>0&&M0(vG,{children:[M0(W1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:G.colors.info,children:["已用时: ",$Y(O)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),M0(W1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:G.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return M0(U6,{paddingX:2,paddingBottom:1,flexDirection:"column",children:[M0(U6,{flexDirection:"row",gap:1,children:[M0(W1,{color:G.colors.warning,bold:!0,children:D8[Q]},void 0,!1,void 0,this),M0(W1,{color:G.colors.text.primary,children:U},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O>0&&M0(U6,{marginLeft:2,flexDirection:"row",gap:1,children:[M0(W1,{color:G.colors.info,children:["已用时: ",$Y(O)]},void 0,!0,void 0,this),M0(W1,{color:G.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:G.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as W2,Static as TG}from"ink";import CG,{useMemo as M8}from"react";import{Box as q2,Text as K2}from"ink";import yG from"ink-big-text";import EG from"ink-gradient";import jG from"react";import{jsxDEV as s0}from"react/jsx-dev-runtime";var ZY=jG.memo(()=>{return s0(q2,{flexDirection:"column",paddingX:2,paddingTop:1,paddingBottom:1,children:[s0(q2,{flexDirection:"column",children:s0(EG,{name:"pastel",children:s0(yG,{text:"BLADE",font:"block"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),s0(q2,{marginBottom:1,children:s0(K2,{color:"white",dimColor:!0,children:C8()},void 0,!1,void 0,this)},void 0,!1,void 0,this),s0(q2,{flexDirection:"column",marginBottom:1,children:[s0(q2,{marginBottom:1,children:s0(K2,{color:"white",bold:!0,children:"使用指南:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),s0(K2,{color:"white",children:"1. 输入问题、编辑文件或运行命令"},void 0,!1,void 0,this),s0(K2,{color:"white",children:"2. 使用 /init 创建项目配置文件"},void 0,!1,void 0,this),s0(K2,{color:"white",children:"3. 输入 /help 查看所有 slash 命令"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as O6,Text as k8}from"ink";import{useState as XY}from"react";function SG(){let[$,Y]=XY($0.getTheme()),[Z,X]=XY($0.getCurrentThemeName()),Q=(K)=>{try{$0.setTheme(K),Y($0.getTheme()),X(K)}catch(W){console.error("Failed to change theme:",W)}},J=$0.getAvailableThemes();return{theme:$,themeName:Z,changeTheme:Q,availableThemes:J,hasTheme:(K)=>$0.hasTheme(K),getThemeByName:(K)=>$0.getThemeByName(K),colors:$.colors,spacing:$.spacing,typography:$.typography}}function QY(){let{colors:$}=SG();return $}import{jsxDEV as x1}from"react/jsx-dev-runtime";var JY=({todos:$,visible:Y=!0,compact:Z=!1})=>{let X=QY();if(!Y||$.length===0)return null;let Q={total:$.length,completed:$.filter((J)=>J.status==="completed").length,inProgress:$.filter((J)=>J.status==="in_progress").length};return x1(O6,{flexDirection:"column",borderStyle:"single",borderColor:X.border.light,paddingX:1,paddingY:Z?0:1,marginBottom:1,children:[x1(O6,{marginBottom:Z?0:1,children:[x1(k8,{dimColor:!0,children:"Tasks "},void 0,!1,void 0,this),x1(k8,{color:X.text.muted,children:[Q.completed,"/",Q.total]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),x1(O6,{flexDirection:"column",children:$.map((J,G)=>x1(PG,{todo:J,compact:Z},J.id||G,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},PG=({todo:$,compact:Y})=>{let Z,X=!1,Q;switch($.status){case"completed":Z="✓",X=!0,Q=$.content;break;case"in_progress":Z="▶",X=!1,Q=$.activeForm;break;case"pending":default:Z="○",X=!0,Q=$.content;break}return x1(O6,{paddingY:Y?0:0,children:x1(k8,{dimColor:X,children:[Z," ",Q]},void 0,!0,void 0,this)},void 0,!1,void 0,this)};import{jsxDEV as L1}from"react/jsx-dev-runtime";var GY=CG.memo(()=>{let $=l2(),Y=C1(),Z=N5(),X=R5(),Q=v5(),J=E$(),{completedMessages:G,streamingMessage:q}=M8(()=>{if(Y&&$.length>0)return{completedMessages:$.slice(0,-1),streamingMessage:$[$.length-1]};return{completedMessages:$,streamingMessage:null}},[$,Y]),K=M8(()=>{return Z.some((U)=>U.status==="pending"||U.status==="in_progress")},[Z]),W=(U,H,_=!1)=>L1(W2,{flexDirection:"column",children:L1(G2,{content:U.content,role:U.role,terminalWidth:J,metadata:U.metadata,isPending:_},void 0,!1,void 0,this)},U.id,!1,void 0,this),O=M8(()=>{let U=[];return U.push(L1(ZY,{},"header",!1,void 0,this)),G.forEach((H,_)=>{U.push(W(H,_))}),U},[G,J]);return L1(W2,{flexDirection:"column",flexGrow:1,paddingX:2,children:L1(W2,{flexDirection:"column",flexGrow:1,children:[L1(TG,{items:O,children:(U)=>U},void 0,!1,void 0,this),q&&W(q,G.length,!0),X&&K&&L1(W2,{marginTop:1,children:L1(JY,{todos:Z,visible:!0,compact:!1},void 0,!1,void 0,this)},void 0,!1,void 0,this),Q.map((U,H)=>L1(W2,{flexDirection:"column",children:L1(G2,{content:U,role:"user",terminalWidth:J},void 0,!1,void 0,this)},`pending-${H}`,!1,void 0,this))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});import{Box as l,Text as h,useFocus as qY,useFocusManager as fG,useInput as F6}from"ink";import hG from"ink-select-input";import xG from"ink-text-input";import{useEffect as pG,useState as U2}from"react";import{jsxDEV as D,Fragment as _6}from"react/jsx-dev-runtime";var gG=({isSelected:$})=>D(l,{marginRight:1,children:D(h,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),uG=({isSelected:$,label:Y})=>D(h,{bold:$,color:$?"yellow":void 0,children:Y},void 0,!1,void 0,this),mG=({onSelect:$,onCancel:Y,initialProvider:Z})=>{let{isFocused:X}=qY({id:"provider-step"});F6((G,q)=>{if(q.escape)Y()},{isActive:X});let Q=[{label:"⚡ OpenAI Compatible - 兼容 OpenAI API 的服务 (千问/豆包/DeepSeek等)",value:"openai-compatible"},{label:"\uD83E\uDD16 Anthropic Claude API - Claude 官方 API",value:"anthropic"}],J=Z?Math.max(0,Q.findIndex((G)=>G.value===Z)):0;return D(l,{flexDirection:"column",marginBottom:1,children:[D(l,{marginBottom:1,children:D(h,{bold:!0,color:"blue",children:"\uD83D\uDCE1 Step 2: 选择 API 提供商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:"根据您使用的 LLM 服务选择对应的 API 类型"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(hG,{items:Q,onSelect:(G)=>$(G.value),indicatorComponent:gG,itemComponent:uG,initialIndex:J},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},H6=({stepNumber:$,icon:Y,title:Z,description:X,hint:Q,examples:J,value:G,placeholder:q,mask:K,previousValue:W,onChange:O,onSubmit:U,onCancel:H})=>{return F6((_,z)=>{if(z.escape)H()},{isActive:!0}),D(l,{flexDirection:"column",marginBottom:1,children:[D(l,{marginBottom:1,children:D(h,{bold:!0,color:"blue",children:[Y," Step ",$,": ",Z]},void 0,!0,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:X},void 0,!1,void 0,this)},void 0,!1,void 0,this),W&&D(l,{marginBottom:1,children:D(h,{color:"green",children:["✓ ",W]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Q&&D(l,{marginBottom:1,children:D(h,{dimColor:!0,children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),J&&J.length>0&&D(_6,{children:[D(l,{marginBottom:1,children:D(h,{dimColor:!0,children:"常见示例:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,paddingLeft:2,children:D(h,{dimColor:!0,children:J.join(`
|
|
1504
|
-
`)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(l,{children:[D(h,{bold:!0,color:"cyan",children:["▶"," "]},void 0,!0,void 0,this),D(xG,{value:G,onChange:O,onSubmit:U,placeholder:q,mask:K},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},dG=({mode:$,config:Y,isSaving:Z,onConfirm:X,onBack:Q,onCancel:J})=>{let{isFocused:G}=qY({id:"confirm-step"});return F6((q,K)=>{if(Z)return;if(q==="y"||q==="Y")X();else if(q==="n"||q==="N")Q();else if(K.escape)J()},{isActive:G&&!Z}),D(l,{flexDirection:"column",marginBottom:1,children:[D(l,{marginBottom:1,children:D(h,{bold:!0,color:$==="edit"?"yellow":"blue",children:$==="edit"?"\uD83D\uDCBE 确认修改":"✅ Step 6: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:$==="edit"?"请确认修改内容,保存后将立即生效。":"请确认以下配置信息:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{flexDirection:"column",marginBottom:1,paddingLeft:2,children:[D(l,{marginBottom:1,children:[D(h,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),D(h,{bold:!0,color:"cyan",children:Y.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(l,{marginBottom:1,children:[D(h,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),D(h,{bold:!0,color:"cyan",children:Y.provider==="openai-compatible"?"⚡ OpenAI Compatible":"\uD83E\uDD16 Anthropic"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(l,{marginBottom:1,children:[D(h,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),D(h,{bold:!0,color:"blue",children:Y.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),D(l,{marginBottom:1,children:[D(h,{dimColor:!0,children:"API Key: "},void 0,!1,void 0,this),D(h,{bold:!0,color:"yellow",children:[Y.apiKey?.slice(0,8),"*".repeat(Math.min(32,(Y.apiKey?.length||0)-8))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D(l,{children:[D(h,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),D(h,{bold:!0,color:"cyan",children:Y.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!Z&&D(l,{marginTop:1,children:D(h,{children:[$==="edit"?"保存修改? ":"确认保存配置? ","[",D(h,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",D(h,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z&&D(l,{children:D(h,{color:"yellow",children:"⏳ 正在保存配置到 ~/.blade/config.json..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},v8=({mode:$,initialConfig:Y,modelId:Z,onComplete:X,onCancel:Q})=>{let J=$==="edit",[G,q]=U2("name"),[K,W]=U2(()=>J&&Y?{...Y}:{}),[O,U]=U2(J&&Y?Y.name:""),[H,_]=U2(!1),[z,F]=U2(null),L=b0(!1);F6((v,i)=>{if(i.ctrl&&v==="c"||i.meta&&v==="c")if($==="setup")L();else Q()},{isActive:!0});let{focus:w}=fG();pG(()=>{if(G==="provider")w("provider-step");else if(G==="confirm")w("confirm-step")},[G,w]);let B=()=>{if(!O.trim()){F("配置名称不能为空");return}W({...K,name:O}),U(""),F(null),q("provider")},A=(v)=>{W({...K,provider:v});let i=J?K.baseUrl??Y?.baseUrl??"":"";U(i),q("baseUrl")},V=()=>{if(!O.trim()){F("Base URL 不能为空");return}try{new URL(O)}catch{F("请输入有效的 URL (例如: https://api.openai.com/v1)");return}W({...K,baseUrl:O});let v=J?K.apiKey??Y?.apiKey??"":"";U(v),F(null),q("apiKey")},E=()=>{if(!O.trim()){F("API Key 不能为空");return}W({...K,apiKey:O});let v=J?K.model??Y?.model??"":"";U(v),F(null),q("model")},R=()=>{if(!O.trim()){F("Model 不能为空");return}W({...K,model:O}),U(""),F(null),q("confirm")},N=async()=>{_(!0),F(null);try{let v={name:K.name,provider:K.provider,baseUrl:K.baseUrl,apiKey:K.apiKey,model:K.model};if($==="setup")X(v);else if($==="add")await e().addModel(v),X(v);else{if(!Z)throw Error("未提供模型 ID,无法编辑");await e().updateModel(Z,v),X(v)}}catch(v){F(v instanceof Error?v.message:"配置失败"),_(!1)}},I=()=>{switch(F(null),U(""),G){case"provider":U(K.name||""),q("name");break;case"baseUrl":q("provider");break;case"apiKey":U(K.baseUrl||""),q("baseUrl");break;case"model":q("apiKey");break;case"confirm":U(K.model||""),q("model");break}},C=G==="name"?1:G==="provider"?2:G==="baseUrl"?3:G==="apiKey"?4:G==="model"?5:6,p=Math.floor((C-1)/5*40);return D(l,{...$==="setup"?{flexDirection:"column",padding:1}:$==="add"?{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1}:{flexDirection:"column",borderStyle:"round",borderColor:"yellow",padding:1},children:[$==="setup"?D(_6,{children:[D(l,{marginBottom:1,children:D(h,{bold:!0,color:"blue",children:"\uD83D\uDE80 欢迎使用 Blade Code"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:"AI 驱动的代码助手 - 让我们开始配置您的助手"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:[D(h,{bold:!0,color:"blue",children:"█".repeat(p)},void 0,!1,void 0,this),D(h,{dimColor:!0,children:"░".repeat(40-p)},void 0,!1,void 0,this),D(h,{children:" "},void 0,!1,void 0,this),D(h,{bold:!0,color:"cyan",children:[C,"/6"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),D(l,{marginBottom:1,children:D(h,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$==="add"?D(_6,{children:[D(l,{justifyContent:"center",marginBottom:1,children:D(h,{bold:!0,color:"blue",children:"添加新模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:["步骤: ",C,"/6"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):D(_6,{children:[D(l,{justifyContent:"center",marginBottom:1,children:D(h,{bold:!0,color:"yellow",children:"编辑模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),D(l,{marginBottom:1,children:D(h,{children:["步骤: ",C,"/6"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),G==="name"&&D(H6,{stepNumber:1,icon:"\uD83D\uDCDD",title:"配置名称",description:"给这个模型配置起一个易于识别的名称",value:O,placeholder:"例如: 千问工作账号",onChange:U,onSubmit:B,onCancel:Q},void 0,!1,void 0,this),G==="provider"&&D(mG,{onSelect:A,onCancel:Q,initialProvider:K.provider},void 0,!1,void 0,this),G==="baseUrl"&&D(H6,{stepNumber:3,icon:"\uD83C\uDF10",title:"配置 Base URL",description:"输入您的 API 端点地址(完整的 URL 包含协议)",examples:["• OpenAI: https://api.openai.com/v1","• 千问: https://dashscope.aliyuncs.com/compatible-mode/v1","• 豆包: https://ark.cn-beijing.volces.com/api/v3","• DeepSeek: https://api.deepseek.com/v1"],value:O,placeholder:"https://api.example.com/v1",onChange:U,onSubmit:V,onCancel:Q},void 0,!1,void 0,this),G==="apiKey"&&D(H6,{stepNumber:4,icon:"\uD83D\uDD11",title:"输入 API Key",description:"您的 API 密钥将被安全存储在 ~/.blade/config.json (权限 600)",hint:"\uD83D\uDCA1 提示: 输入时字符会被隐藏,支持粘贴 (Ctrl+V / Cmd+V)",previousValue:K.baseUrl?`✓ 当前 Base URL: ${K.baseUrl}`:void 0,value:O,placeholder:"sk-...",mask:"*",onChange:U,onSubmit:E,onCancel:Q},void 0,!1,void 0,this),G==="model"&&D(H6,{stepNumber:5,icon:"\uD83E\uDD16",title:"选择模型",description:"输入您想使用的模型名称(请参考您的 API 提供商文档)",examples:["• OpenAI: gpt-5, gpt-5-mini, gpt-5-nano","• Claude: claude-sonnet-4.5, claude-opus-4.1","• 千问: qwen3-max, qwen3-235b, qwen3-32b","• DeepSeek: deepseek-v3.1, deepseek-r1-0528","• 豆包: doubao-seed-1.6, doubao-seed-1.6-flash"],value:O,placeholder:"例如: gpt-5",onChange:U,onSubmit:R,onCancel:Q},void 0,!1,void 0,this),G==="confirm"&&D(dG,{mode:$,config:K,isSaving:H,onConfirm:N,onBack:I,onCancel:Q},void 0,!1,void 0,this),z&&D(l,{marginTop:1,borderStyle:"round",borderColor:"red",paddingX:1,children:D(h,{color:"red",children:["❌ ",z]},void 0,!0,void 0,this)},void 0,!1,void 0,this),D(l,{marginTop:1,children:D(h,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this),!H&&G==="provider"&&D(l,{marginTop:1,children:D(h,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",D(h,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择,",D(h,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",D(h,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!H&&G!=="confirm"&&G!=="provider"&&D(l,{marginTop:1,children:D(h,{dimColor:!0,children:["\uD83D\uDCA1 输入完成后按 ",D(h,{bold:!0,children:"Enter"},void 0,!1,void 0,this),",",D(h,{bold:!0,children:"Ctrl+C"},void 0,!1,void 0,this)," 退出"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!H&&G==="confirm"&&D(l,{marginTop:1,children:D(h,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",D(h,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","保存,",D(h,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回修改,",D(h,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as z6,useMount as cG}from"ahooks";import{Box as t0,Text as Z0,useFocus as lG,useFocusManager as iG,useInput as rG}from"ink";import nG from"ink-select-input";import{memo as aG,useMemo as oG,useState as B6}from"react";import{jsxDEV as m}from"react/jsx-dev-runtime";var sG=({isSelected:$})=>m(t0,{marginRight:1,children:m(Z0,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),tG=({isSelected:$,label:Y})=>m(Z0,{bold:$,color:$?"yellow":void 0,children:Y},void 0,!1,void 0,this),KY=aG(({onClose:$,onEdit:Y})=>{let Z=b5(),X=I5()??"",{isFocused:Q}=lG({id:"model-selector"}),J=iG(),[G,q]=B6(""),[K,W]=B6(!1),[O,U]=B6(null),H=b0(!1),[_]=B6(()=>{let R=process.stdout?.columns||80;return Math.max(20,R-8)});cG(()=>{if(J?.focus("model-selector"),Z.length>0)q(Z[0].id)}),rG((R,N)=>{if(K)return;if(N.ctrl&&R==="c"||N.meta&&R==="c"){H();return}if(N.escape){$();return}if(!Q)return;if(R==="d"||R==="D"){F();return}if((R==="e"||R==="E")&&Y)L()},{isActive:!0});let z=z6(async(R)=>{if(K)return;let N=R.value;if(N===X){$();return}W(!0),U(null);try{await e().setCurrentModel(N),$()}catch(I){U(I.message),W(!1)}}),F=z6(async()=>{if(K||G===X)return;W(!0),U(null);try{if(await e().removeModel(G),Z.length<=1)$()}catch(R){U(R.message)}finally{W(!1)}}),L=z6(()=>{if(K||!Y)return;let R=Z.find((N)=>N.id===G);if(!R)return;Y(R)}),w=z6((R)=>{q(R.value)}),B=oG(()=>{return Z.find((R)=>R.id===G)},[Z,G]),A=Z.map((R)=>({label:R.name+(R.id===X?" (当前)":""),value:R.id})),V=G===X;return m(t0,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:1,width:"100%",children:[m(t0,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[m(Z0,{bold:!0,color:"cyan",children:"模型管理"},void 0,!1,void 0,this),m(Z0,{dimColor:!0,children:[K?"⏳ 处理中...":V?"Enter=关闭 • E=编辑 • Esc=取消":"Enter=切换 • D=删除 • E=编辑 • Esc=取消"," • Ctrl+C=退出"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),m(t0,{flexDirection:"row",children:[m(t0,{flexDirection:"column",flexGrow:2,marginRight:2,borderStyle:"single",borderColor:"gray",padding:1,children:[m(Z0,{dimColor:!0,children:["已配置模型 (",Z.length,")"]},void 0,!0,void 0,this),m(t0,{marginTop:1,children:m(nG,{items:A,onSelect:z,onHighlight:w,indicatorComponent:sG,itemComponent:tG},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m(t0,{flexDirection:"column",flexGrow:3,borderStyle:"single",borderColor:"gray",padding:1,children:[m(Z0,{dimColor:!0,children:"模型详情"},void 0,!1,void 0,this),m(t0,{marginY:1,children:m(Z0,{color:V?"green":"yellow",children:V?"● 当前使用":"● 可切换"},void 0,!1,void 0,this)},void 0,!1,void 0,this),B?m(t0,{flexDirection:"column",children:[m(Z0,{children:[m(Z0,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),m(Z0,{bold:!0,color:"cyan",children:B.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m(Z0,{children:[m(Z0,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),m(Z0,{bold:!0,children:B.provider},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m(Z0,{children:[m(Z0,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),m(Z0,{bold:!0,children:B.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this),m(Z0,{children:[m(Z0,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),m(Z0,{color:"blueBright",children:B.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.temperature!==void 0&&m(Z0,{children:[m(Z0,{dimColor:!0,children:"Temperature: "},void 0,!1,void 0,this),m(Z0,{children:B.temperature},void 0,!1,void 0,this)]},void 0,!0,void 0,this),B.maxContextTokens!==void 0&&m(Z0,{children:[m(Z0,{dimColor:!0,children:"Context Window: "},void 0,!1,void 0,this),m(Z0,{children:B.maxContextTokens},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):m(Z0,{dimColor:!0,children:"请选择一个模型查看详情"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),O&&m(t0,{marginTop:1,children:m(Z0,{color:"red",children:["❌ ",O]},void 0,!0,void 0,this)},void 0,!1,void 0,this),m(t0,{justifyContent:"center",marginTop:1,children:m(Z0,{dimColor:!0,children:"─".repeat(_)},void 0,!1,void 0,this)},void 0,!1,void 0,this),m(t0,{justifyContent:"center",children:m(Z0,{dimColor:!0,children:"提示:D=删除 • E=编辑 • ↑↓=移动 • Enter/ESC=确认"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as O2}from"ahooks";import{promises as HY}from"fs";import{Box as h0,Text as U0,useInput as eG}from"ink";import WY from"ink-select-input";import $q from"ink-text-input";import Yq from"os";import N6 from"path";import{useEffect as Zq,useMemo as w6,useRef as Xq,useState as p1}from"react";import{jsxDEV as d}from"react/jsx-dev-runtime";var H2=[{key:"allow",label:"Allow"},{key:"ask",label:"Ask"},{key:"deny",label:"Deny"},{key:"info",label:"Info"}],Qq={allow:"Add a new rule...",ask:"Add a new rule...",deny:"Add a new rule..."},Jq={allow:"Allow permission rules",ask:"Ask permission rules",deny:"Deny permission rules"},UY={project:"[项目共享配置]",global:"[用户全局配置]",local:"[本地配置]"},Gq=["project","global","local"],qq={allow:[],ask:[],deny:[]},Kq={localExists:!1,projectExists:!1,globalExists:!1},OY={allow:[],ask:[],deny:[]};function Wq($){let Y=(X)=>Array.isArray(X)?X.filter((Q)=>typeof Q==="string"):[],Z=$?.permissions??{};return{allow:Y(Z?.allow),ask:Y(Z?.ask),deny:Y(Z?.deny)}}async function Uq($){try{let Y=await HY.readFile($,"utf-8"),Z=JSON.parse(Y);return{exists:!0,raw:Z,permissions:Wq(Z)}}catch(Y){if(Y.code==="ENOENT")return{exists:!1,raw:{},permissions:{...OY}};return console.warn(`[PermissionsManager] Failed to read ${$}:`,Y),{exists:!0,raw:{},permissions:{...OY}}}}function Oq($,Y){let Z=$.padEnd(32," "),X=Y==="local"?`${UY[Y]} ← 可删除`:UY[Y];return`${Z} ${X}`}var _Y=({onClose:$})=>{let Z=l0()==="permissions-manager",X=b0(!1),[Q,J]=p1(0),G=H2[Q].key,[q,K]=p1(qq),[W,O]=p1(Kq),[U,H]=p1(!0),[_,z]=p1("list"),[F,L]=p1(""),[w,B]=p1(null),[A,V]=p1(null),E=Xq(!1),R=w6(()=>N6.join(process.cwd(),".blade","settings.local.json"),[]),N=w6(()=>N6.join(process.cwd(),".blade","settings.json"),[]),I=w6(()=>N6.join(Yq.homedir(),".blade","settings.json"),[]),C=O2(async()=>{H(!0);let c=[{source:"local",path:R},{source:"project",path:N},{source:"global",path:I}],Y0=await Promise.all(c.map(async({source:L0,path:R1})=>{let u0=await Uq(R1);return{source:L0,path:R1,...u0}})),n={localExists:Y0.find((L0)=>L0.source==="local")?.exists??!1,projectExists:Y0.find((L0)=>L0.source==="project")?.exists??!1,globalExists:Y0.find((L0)=>L0.source==="global")?.exists??!1};O(n);let C0={allow:[],ask:[],deny:[]},m1=Object.fromEntries(Y0.map((L0)=>[L0.source,L0]));["allow","ask","deny"].forEach((L0)=>{Gq.forEach((R1)=>{(m1[R1]?.permissions[L0]??[]).forEach((e0,d1)=>{let V6={key:`${R1}:${d1}:${e0}`,rule:e0,source:R1};C0[L0].push(V6)})})}),K(C0),H(!1)});Zq(()=>{C()},[C]);let p=O2(async(c,Y0)=>{try{let n=N6.join(process.cwd(),".blade","settings.local.json"),C0={allow:[],ask:[],deny:[]};try{let L0=await HY.readFile(n,"utf-8"),u0=JSON.parse(L0).permissions||{};C0={allow:Array.isArray(u0.allow)?u0.allow:[],ask:Array.isArray(u0.ask)?u0.ask:[],deny:Array.isArray(u0.deny)?u0.deny:[]}}catch(L0){}let m1=Y0(C0);await e().updateConfig({permissions:m1},{scope:"local",immediate:!0}),await C()}catch(n){throw console.error("[PermissionsManager] 修改权限规则失败:",n),n}});eG((c,Y0)=>{if(Y0.ctrl&&c==="c"||Y0.meta&&c==="c"){X();return}if(_==="locked"){if(E.current){E.current=!1;return}z("list"),B(null),V(null);return}if(Y0.escape){if(_==="list"||G==="info")$();else z("list"),L(""),B(null),V(null);return}if(_==="list"){if(Y0.tab&&Y0.shift)J((n)=>(n-1+H2.length)%H2.length);else if(Y0.tab)J((n)=>(n+1)%H2.length);else if(c?.toLowerCase()==="q")$()}},{isActive:Z});let y=O2((c)=>{let Y0=c.value;if(G==="info")return;if(Y0.type==="add"){z("add"),L(""),V(null);return}if(Y0.entry.source!=="local"){z("locked"),E.current=!0,B({tab:G,entry:Y0.entry}),V({type:"error",text:Y0.entry.source==="project"?"此规则定义在项目共享配置中,无法在此删除。":"此规则来自用户全局配置,无法在此删除。"});return}z("confirm-delete"),B({tab:G,entry:Y0.entry}),V(null)}),v=O2(async()=>{if(G==="info")return;let c=F.trim();if(!c){V({type:"error",text:"Permission rule 不能为空"});return}if(q[G].map((n)=>n.rule).includes(c)){V({type:"error",text:"该规则已存在"});return}try{await p(G,(n)=>{let C0={allow:[...n.allow],ask:[...n.ask],deny:[...n.deny]};return C0[G]=[...new Set([...n[G],c])],C0}),z("list"),L(""),V({type:"success",text:"已添加本地权限规则"})}catch(n){V({type:"error",text:`保存失败: ${n instanceof Error?n.message:"未知错误"}`})}}),i=O2(async()=>{if(!w)return;let{tab:c,entry:Y0}=w;try{await p(c,(n)=>{let C0={allow:[...n.allow],ask:[...n.ask],deny:[...n.deny]};return C0[c]=n[c].filter((m1)=>m1!==Y0.rule),C0}),z("list"),B(null),V({type:"success",text:"已删除本地权限规则"})}catch(n){V({type:"error",text:`删除失败: ${n instanceof Error?n.message:"未知错误"}`})}}),P=w6(()=>{if(G==="info")return[];let c=G;return[{label:`› ${Qq[c]}`,value:{type:"add"}},...q[c].map((n)=>({label:Oq(n.rule,n.source),value:{type:"rule",entry:n}}))]},[G,q]),U1=()=>d(h0,{marginBottom:1,children:H2.map((c,Y0)=>d(h0,{marginRight:2,children:d(U0,{color:Y0===Q?"yellow":"gray",children:["[",c.label,"]"]},void 0,!0,void 0,this)},c.key,!1,void 0,this))},void 0,!1,void 0,this),X0=()=>d(h0,{flexDirection:"column",gap:1,children:[d(U0,{children:"配置文件优先级(从高到低):"},void 0,!1,void 0,this),d(h0,{flexDirection:"column",marginLeft:2,children:[d(U0,{children:["1. .blade/settings.local.json (本地配置,不提交 Git)"," ",W.localExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),d(U0,{children:["2. .blade/settings.json (项目配置,提交 Git)"," ",W.projectExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),d(U0,{children:["3. ~/.blade/settings.json (用户全局配置)"," ",W.globalExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d(U0,{children:"说明:"},void 0,!1,void 0,this),d(h0,{flexDirection:"column",marginLeft:2,children:[d(U0,{children:"- /permissions 命令只管理本地配置 (.blade/settings.local.json)"},void 0,!1,void 0,this),d(U0,{children:"- 修改全局或项目配置请直接编辑对应文件"},void 0,!1,void 0,this),d(U0,{children:"- 本地配置不会提交到 Git"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_0=(c)=>d(h0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:Jq[c]},void 0,!1,void 0,this),d(U0,{children:"Permission rules are a tool name, optionally followed by a specifier in parentheses."},void 0,!1,void 0,this),d(U0,{color:"gray",children:"例如: WebFetch 或 Bash(ls:*)"},void 0,!1,void 0,this),d(h0,{marginTop:1,children:d($q,{value:F,onChange:L,onSubmit:v},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(U0,{color:"gray",children:"Enter 提交 · Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M1=(c,Y0)=>d(h0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:["Delete ",c," permission rule?"]},void 0,!0,void 0,this),d(U0,{children:Y0.rule},void 0,!1,void 0,this),d(U0,{color:"gray",children:"From project local settings"},void 0,!1,void 0,this),d(U0,{children:"Are you sure you want to delete this permission rule?"},void 0,!1,void 0,this),d(WY,{items:[{label:"Yes",value:"yes"},{label:"No",value:"no"}],onSelect:(n)=>{if(n.value==="yes")i();else z("list"),B(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J$=(c)=>d(h0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:"Cannot delete this rule"},void 0,!1,void 0,this),d(U0,{children:c.rule},void 0,!1,void 0,this),d(U0,{color:"gray",children:c.source==="project"?"This rule is defined in .blade/settings.json. 请手动编辑该文件以移除规则。":"This rule is defined in ~/.blade/settings.json. 请手动编辑该文件以移除规则。"},void 0,!1,void 0,this),d(U0,{color:"gray",children:"按任意键继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),P$=(c)=>d(WY,{items:P,isFocused:_==="list",onSelect:y},void 0,!1,void 0,this),b6=()=>{if(U)return d(U0,{children:"加载中..."},void 0,!1,void 0,this);if(G==="info")return X0();if(_==="add")return _0(G);if(_==="confirm-delete"&&w)return M1(w.tab,w.entry);if(_==="locked"&&w)return J$(w.entry);return P$(G)};return d(h0,{flexDirection:"column",borderStyle:"round",borderColor:Z?"cyan":"gray",padding:1,width:80,children:[d(U0,{color:"cyan",bold:!0,children:"⚙️ 权限管理器"},void 0,!1,void 0,this),U1(),d(h0,{flexDirection:"column",gap:1,children:b6()},void 0,!1,void 0,this),A&&d(h0,{marginTop:1,children:d(U0,{color:A.type==="success"?"green":"red",children:A.text},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(h0,{marginTop:1,children:d(U0,{color:"gray",children:"Tab 切换视图 · Esc 关闭 · Q 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Box as L6,Text as g1,useInput as Hq}from"ink";import _q from"ink-select-input";import{useEffect as Fq,useMemo as zq,useState as FY}from"react";import{jsxDEV as x0}from"react/jsx-dev-runtime";function Bq($){let Y=new Date($),X=new Date().getTime()-Y.getTime(),Q=Math.floor(X/86400000);if(Q===0)return`今天 ${Y.getHours().toString().padStart(2,"0")}:${Y.getMinutes().toString().padStart(2,"0")}`;if(Q===1)return"昨天";if(Q<7)return`${Q}天前`;return`${Y.getMonth()+1}/${Y.getDate()}`}function Nq($){let Y=$.split("/");return Y[Y.length-1]||$}var wq=({isSelected:$})=>x0(L6,{marginRight:1,children:x0(g1,{color:$?"cyan":"gray",children:$?"❯":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),Lq=({isSelected:$,label:Y})=>x0(g1,{color:$?"cyan":"white",bold:$,children:Y},void 0,!1,void 0,this),zY=({sessions:$,onSelect:Y,onCancel:Z})=>{let[X,Q]=FY([]),[J,G]=FY(!1),K=l0()==="session-selector",W=b0(!1);Hq((_,z)=>{if(z.ctrl&&_==="c"||z.meta&&_==="c"){W();return}if(z.escape&&Z)Z()},{isActive:K}),Fq(()=>{if($){Q($);return}(async()=>{G(!0);try{let z=await z1.listSessions();Q(z)}catch(z){console.error("[SessionSelector] Failed to load sessions:",z),Q([])}finally{G(!1)}})()},[$]);let O=$||X,U=zq(()=>{return O.map((_)=>{let z=Nq(_.projectPath),F=Bq(_.lastMessageTime),L=_.gitBranch?` (${_.gitBranch})`:"",w=_.hasErrors?" ⚠️":"";return{label:`\uD83D\uDCC5 ${F} | ${z}${L} | ${_.messageCount} 条消息${w}`,value:_.sessionId}})},[O]),H=(_)=>{Y(_.value)};if(J)return x0(L6,{flexDirection:"column",paddingX:2,paddingY:1,children:x0(g1,{children:"⏳ 正在加载会话列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(O.length===0)return x0(L6,{flexDirection:"column",paddingX:2,paddingY:1,children:[x0(g1,{color:"yellow",children:"⚠️ 没有找到历史会话"},void 0,!1,void 0,this),x0(g1,{dimColor:!0,children:[`
|
|
1505
|
-
`,"提示: 开始一次对话后,会话历史将保存到 ~/.blade/projects/"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return
|
|
1493
|
+
`)})}W=!1,O=[],U=!1;continue}O.push(_);continue}if(_.match(G1.diffStart)){W=!0,O=[],U=!1;continue}if(X){if(_.match(G1.codeBlock))Y.push({type:"code",content:Q.join(`
|
|
1494
|
+
`),language:J||void 0}),X=!1,Q=[],J=null,U=!1;else Q.push(_);continue}let z=_.match(G1.codeBlock);if(z){X=!0,J=z[1]||null,U=!1;continue}let F=_.match(G1.table),w=_.match(G1.tableSeparator);if(F&&!q){if(H+1<Z.length){if(Z[H+1].match(G1.tableSeparator)){q=!0,G=F[1].split("|").map((R)=>R.trim()).filter((R)=>R.length>0),K=[],U=!1;continue}}}if(q&&w)continue;if(q&&F){let E=F[1].split("|").map((R)=>R.trim()).filter((R)=>R.length>0);while(E.length<G.length)E.push("");if(E.length>G.length)E.length=G.length;K.push(E);continue}if(q&&!F){if(G.length>0&&K.length>0)Y.push({type:"table",content:"",tableData:{headers:G,rows:K}});q=!1,G=[],K=[]}let L=_.match(G1.heading);if(L){Y.push({type:"heading",content:L[2],level:L[1].length}),U=!1;continue}let N=_.match(G1.ulItem);if(N){Y.push({type:"list",content:N[3],listType:"ul",marker:N[2],indentation:N[1].length}),U=!1;continue}let A=_.match(G1.olItem);if(A){Y.push({type:"list",content:A[3],listType:"ol",marker:A[2],indentation:A[1].length}),U=!1;continue}if(_.match(G1.hr)){Y.push({type:"hr",content:""}),U=!1;continue}if(_.trim().length===0){if(!U)Y.push({type:"empty",content:""}),U=!0;continue}Y.push({type:"text",content:_}),U=!1}if(X)Y.push({type:"code",content:Q.join(`
|
|
1495
|
+
`),language:J||void 0});if(q&&G.length>0&&K.length>0)Y.push({type:"table",content:"",tableData:{headers:G,rows:K}});return Y}var aJ=({content:$,language:Y,terminalWidth:Z})=>{return x(A8,{content:$,language:Y,showLineNumbers:!0,terminalWidth:Z},void 0,!1,void 0,this)},nJ=({content:$,level:Y})=>{let Z=$0.getTheme();switch(Y){case 1:return x(f0,{bold:!0,color:Z.colors.primary,children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 2:return x(f0,{bold:!0,color:Z.colors.primary,children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 3:return x(f0,{bold:!0,color:Z.colors.text.primary,children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);case 4:return x(f0,{italic:!0,color:Z.colors.text.muted,children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this);default:return x(f0,{children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)}},oJ=({terminalWidth:$})=>{let Y=$0.getTheme(),Z=Math.max(0,Math.min($-4,80));return x(f0,{dimColor:!0,color:Y.colors.text.muted,children:"─".repeat(Z)},void 0,!1,void 0,this)},sJ=({content:$})=>{return x(f0,{wrap:"wrap",children:x(n0,{text:$},void 0,!1,void 0,this)},void 0,!1,void 0,this)},tJ=U6.memo(({detail:$,terminalWidth:Y})=>{let Z=$0.getTheme(),X=50,Q=$.split(`
|
|
1496
|
+
`),J=Q.length>50,q=J?Q.slice(0,50):Q,G=q.join(`
|
|
1497
|
+
`),K=G.includes("<<<DIFF>>>"),W=G.includes("```");if(K){let O=G.match(/<<<DIFF>>>\s*({[\s\S]*?})\s*<<<\/DIFF>>>/);if(O)try{let U=JSON.parse(O[1]);return x(v0,{flexDirection:"column",children:[x(R8,{patch:U.patch,startLine:U.startLine,matchLine:U.matchLine,terminalWidth:Y},void 0,!1,void 0,this),J&&x(v0,{marginTop:1,children:x(f0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}catch{}}if(W){let O=G.match(/```(\w+)?\s*\n([\s\S]*?)\n```/);if(O){let U=O[1]||"text",H=O[2];return x(v0,{flexDirection:"column",children:[x(A8,{content:H,language:U,showLineNumbers:!1,terminalWidth:Y},void 0,!1,void 0,this),J&&x(v0,{marginTop:1,children:x(f0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}}return x(v0,{flexDirection:"column",children:[q.map((O,U)=>x(f0,{color:Z.colors.text.primary,children:O},U,!1,void 0,this)),J&&x(v0,{marginTop:1,children:x(f0,{dimColor:!0,color:Z.colors.text.muted,children:["... 省略 ",Q.length-50," 行 ..."]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}),K2=U6.memo(({content:$,role:Y,terminalWidth:Z,metadata:X,isPending:Q=!1})=>{let J=U6.useMemo(()=>iJ(Y,X),[Y,X]),{color:q,prefix:G}=J;if(Y==="tool"&&X&&"detail"in X){let W=X;if(W.detail)return x(v0,{flexDirection:"column",marginBottom:1,children:[x(v0,{flexDirection:"row",children:[x(v0,{marginRight:1,children:x(f0,{color:q,bold:!0,children:G},void 0,!1,void 0,this)},void 0,!1,void 0,this),x(f0,{color:q,children:$},void 0,!1,void 0,this)]},void 0,!0,void 0,this),x(v0,{marginLeft:G.length+1,marginTop:1,children:x(tJ,{detail:W.detail,terminalWidth:Z-(G.length+1)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)}let K=U6.useMemo(()=>rJ($),[$]);return x(v0,{flexDirection:"column",marginBottom:1,children:K.map((W,O)=>{if(W.type==="empty")return x(v0,{height:1},O,!1,void 0,this);return x(v0,{flexDirection:"row",children:[O===0&&x(v0,{marginRight:1,children:x(f0,{color:q,bold:!0,children:G},void 0,!1,void 0,this)},void 0,!1,void 0,this),O>0&&x(v0,{width:G.length+1},void 0,!1,void 0,this),x(v0,{flexGrow:1,children:W.type==="code"?x(aJ,{content:W.content,language:W.language,terminalWidth:Z-(G.length+1)},void 0,!1,void 0,this):W.type==="table"&&W.tableData?x(u3,{headers:W.tableData.headers,rows:W.tableData.rows,terminalWidth:Z-(G.length+1)},void 0,!1,void 0,this):W.type==="heading"?x(nJ,{content:W.content,level:W.level||1},void 0,!1,void 0,this):W.type==="list"?x(g3,{type:W.listType||"ul",marker:W.marker||"-",itemText:W.content,leadingWhitespace:" ".repeat(W.indentation||0)},void 0,!1,void 0,this):W.type==="hr"?x(oJ,{terminalWidth:Z-(G.length+1)},void 0,!1,void 0,this):W.type==="diff"&&W.diffData?x(R8,{patch:W.diffData.patch,startLine:W.diffData.startLine,matchLine:W.diffData.matchLine,terminalWidth:Z-(G.length+1)},void 0,!1,void 0,this):x(sJ,{content:W.content},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},O,!0,void 0,this)})},void 0,!1,void 0,this)},($,Y)=>{return $.content===Y.content&&$.role===Y.role&&$.terminalWidth===Y.terminalWidth&&$.isPending===Y.isPending&&JSON.stringify($.metadata)===JSON.stringify(Y.metadata)});import{jsxDEV as W0}from"react/jsx-dev-runtime";var Zq=({label:$,isSelected:Y})=>W0(K1,{color:Y?"yellow":void 0,children:$},void 0,!1,void 0,this),d3=({details:$,onResponse:Y})=>{let Z=P$(),Q=i0()==="confirmation-prompt",J=b0(!1);eJ((U,H)=>{if(H.ctrl&&U==="c"||H.meta&&U==="c"){J();return}if(H.escape){Y({approved:!1,reason:"用户取消"});return}let _=U.toLowerCase();if(q){if(_==="y"){Y({approved:!0,targetMode:"autoEdit"});return}if(_==="s"){Y({approved:!0,targetMode:"default"});return}if(_==="n"){Y({approved:!1,reason:"方案需要改进"});return}}else if(G){if(_==="y"){Y({approved:!0});return}if(_==="n"){Y({approved:!1,reason:"用户拒绝进入 Plan 模式"});return}}else{if(_==="y"){Y({approved:!0,scope:"once"});return}if(_==="s"){Y({approved:!0,scope:"session"});return}if(_==="n"){Y({approved:!1,reason:"用户拒绝"});return}}},{isActive:Q});let q=$.type==="exitPlanMode",G=$.type==="enterPlanMode",K=Yq(()=>{if(q)return[{key:"approve-auto",label:"[Y] Yes, execute with auto-edit mode",value:{approved:!0,targetMode:"autoEdit"}},{key:"approve-default",label:"[S] Yes, execute with default mode (ask for each operation)",value:{approved:!0,targetMode:"default"}},{key:"reject",label:"[N] No, keep planning",value:{approved:!1,reason:"方案需要改进"}}];if(G)return[{key:"approve",label:"[Y] Yes, enter Plan mode",value:{approved:!0}},{key:"reject",label:"[N] No, proceed directly",value:{approved:!1,reason:"用户拒绝进入 Plan 模式"}}];return[{key:"approve-once",label:"[Y] Yes (once only)",value:{approved:!0,scope:"once"}},{key:"approve-session",label:"[S] Yes, remember for this project (Shift+Tab)",value:{approved:!0,scope:"session"}},{key:"reject",label:"[N] No",value:{approved:!1,reason:"用户拒绝"}}]},[q,G]),O=(()=>{if(q)return{color:"cyan",title:"\uD83D\uDD35 Plan Mode - Review Implementation Plan"};if(G)return{color:"magenta",title:"\uD83D\uDFE3 Enter Plan Mode?"};return{color:"yellow",title:"\uD83D\uDD14 Confirmation Required"}})();return W0(s0,{flexDirection:"column",borderStyle:"round",borderColor:Q?O.color:"gray",padding:1,children:[W0(s0,{marginBottom:1,children:W0(K1,{bold:!0,color:O.color,children:O.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),$.title&&W0(s0,{marginBottom:1,children:W0(K1,{bold:!0,children:$.title},void 0,!1,void 0,this)},void 0,!1,void 0,this),W0(s0,{marginBottom:1,children:W0(K1,{children:$.message},void 0,!1,void 0,this)},void 0,!1,void 0,this),($.planContent||$.details)&&W0(s0,{flexDirection:"column",marginBottom:1,borderStyle:"single",borderColor:O.color,padding:1,children:[W0(K1,{bold:!0,color:O.color,children:q?"\uD83D\uDCCB Implementation Plan:":G?"\uD83D\uDCDD Details:":"\uD83D\uDCC4 Operation Details:"},void 0,!1,void 0,this),W0(s0,{marginTop:1,children:W0(K2,{content:$.planContent||$.details||"",role:"assistant",terminalWidth:Z-4},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),$.risks&&$.risks.length>0&&W0(s0,{flexDirection:"column",marginBottom:1,children:[W0(K1,{color:"red",bold:!0,children:"⚠️ 风险提示:"},void 0,!1,void 0,this),$.risks.map((U,H)=>W0(s0,{marginLeft:2,children:W0(K1,{color:"red",children:["• ",U]},void 0,!0,void 0,this)},H,!1,void 0,this))]},void 0,!0,void 0,this),$.affectedFiles&&$.affectedFiles.length>0&&W0(s0,{flexDirection:"column",marginBottom:1,children:[W0(K1,{color:"yellow",children:"\uD83D\uDCC1 影响的文件:"},void 0,!1,void 0,this),$.affectedFiles.slice(0,3).map((U,H)=>W0(s0,{marginLeft:2,children:W0(K1,{children:["• ",U]},void 0,!0,void 0,this)},H,!1,void 0,this)),$.affectedFiles.length>3&&W0(s0,{marginLeft:2,children:W0(K1,{color:"gray",children:["...还有 ",$.affectedFiles.length-3," 个文件"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),W0(s0,{flexDirection:"column",children:[W0(K1,{color:"gray",children:"使用 ↑ ↓ 选择,回车确认(支持 Y/S/N 快捷键,ESC 取消)"},void 0,!1,void 0,this),W0($q,{items:K,isFocused:Q,itemComponent:Zq,onSelect:(U)=>{Y(U.value)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as t3}from"ahooks";import{Box as bq,Text as Vq}from"ink";import Dq from"react";import{writeFileSync as Xq}from"node:fs";import{join as Qq}from"node:path";import{tmpdir as Jq}from"node:os";import{nanoid as qq}from"nanoid";function c3($,Y,Z){let X=Gq(Y),Q=Date.now(),J=qq(8),q=Z||`blade_image_${Q}_${J}.${X}`,G=Jq(),K=Qq(G,q),W=Buffer.from($,"base64");Xq(K,W);let O=`[Image: ${q}]`;return console.log(`[ImageHandler] Saved image to: ${K}`),console.log(`[ImageHandler] Size: ${(W.length/1024).toFixed(2)} KB`),{filePath:K,filename:q,tag:O}}function Gq($){return{"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/bmp":"bmp","image/svg+xml":"svg"}[$]||"png"}import{useMemoizedFn as zq}from"ahooks";import Q$ from"chalk";import{Text as Nq,useInput as Bq}from"ink";import{useEffect as o3,useRef as Lq}from"react";var x1={TIMEOUT_MS:100,RAPID_INPUT_THRESHOLD_MS:150,LARGE_INPUT_THRESHOLD:300,MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD:200};import{execSync as Kq}from"node:child_process";import{existsSync as LA,readFileSync as l3}from"node:fs";import{basename as i3,isAbsolute as Wq}from"node:path";function Uq(){let $=process.platform,Y={darwin:"No image found in clipboard. Use Cmd + Ctrl + Shift + 4 to copy a screenshot to clipboard.",win32:"No image found in clipboard. Use Print Screen to copy a screenshot to clipboard.",linux:"No image found in clipboard. Use appropriate screenshot tool to copy a screenshot to clipboard."};return Y[$]||Y.linux}var AA=Uq();function Oq($){try{let Y=Buffer.from($,"base64");if(Y.length<4)return"image/png";if(Y[0]===137&&Y[1]===80&&Y[2]===78&&Y[3]===71)return"image/png";if(Y[0]===255&&Y[1]===216&&Y[2]===255)return"image/jpeg";if(Y[0]===71&&Y[1]===73&&Y[2]===70)return"image/gif";if(Y[0]===82&&Y[1]===73&&Y[2]===70&&Y[3]===70){if(Y.length>=12&&Y[8]===87&&Y[9]===69&&Y[10]===66&&Y[11]===80)return"image/webp"}return"image/png"}catch{return"image/png"}}function Hq(){let $=process.platform,Y={darwin:"/tmp/blade_cli_latest_screenshot.png",linux:"/tmp/blade_cli_latest_screenshot.png",win32:process.env.TEMP?`${process.env.TEMP}\\blade_cli_latest_screenshot.png`:"C:\\Temp\\blade_cli_latest_screenshot.png"},Z={darwin:{checkImage:"osascript -e 'the clipboard as «class PNGf»'",saveImage:(X)=>`osascript -e 'set png_data to (the clipboard as «class PNGf»)' -e 'set fp to open for access POSIX file "${X}" with write permission' -e 'write png_data to fp' -e 'close access fp'`,getPath:"osascript -e 'get POSIX path of (the clipboard as «class furl»)'",deleteFile:(X)=>`rm -f "${X}"`},linux:{checkImage:'xclip -selection clipboard -t TARGETS -o | grep -E "image/(png|jpeg|jpg|gif|webp)"',saveImage:(X)=>`xclip -selection clipboard -t image/png -o > "${X}" || wl-paste --type image/png > "${X}"`,getPath:"xclip -selection clipboard -t text/plain -o",deleteFile:(X)=>`rm -f "${X}"`},win32:{checkImage:'powershell -Command "(Get-Clipboard -Format Image) -ne $null"',saveImage:(X)=>`powershell -Command "$img = Get-Clipboard -Format Image; if ($img) { $img.Save('${X.replace(/\\/g,"\\\\")}', [System.Drawing.Imaging.ImageFormat]::Png) }"`,getPath:'powershell -Command "Get-Clipboard"',deleteFile:(X)=>`del /f "${X}"`}};return{commands:Z[$]||Z.linux,screenshotPath:Y[$]||Y.linux}}function _q(){let{commands:$}=Hq();try{return Kq($.getPath,{encoding:"utf-8"}).trim()}catch(Y){return console.error("Failed to get clipboard path:",Y),null}}function r3($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $.slice(1,-1);return $}function a3($){if(process.platform==="win32")return $;let Y="__DOUBLE_BACKSLASH__";return $.replace(/\\\\/g,Y).replace(/\\(.)/g,"$1").replace(new RegExp(Y,"g"),"\\")}function k8($){let Y=r3($.trim()),Z=a3(Y);return/\.(png|jpe?g|gif|webp)$/i.test(Z)}function Fq($){let Y=r3($.trim()),Z=a3(Y);if(k8(Z))return Z;return null}async function n3($){let Y=Fq($);if(!Y)return null;let Z;try{if(Wq(Y))Z=l3(Y);else{let q=_q();if(q&&Y===i3(q))Z=l3(q);else return null}}catch(q){return console.error("Failed to read image file:",q),null}let X=Z.toString("base64"),Q=Oq(X),J=i3(Y);return{path:Y,base64:X,mediaType:Q,filename:J}}import{jsxDEV as Rq}from"react/jsx-dev-runtime";var wq=/\r\n/g,Aq=/\r/g;function O6($){if(!$.includes("\r"))return $;return $.replace(wq,`
|
|
1498
|
+
`).replace(Aq,`
|
|
1499
|
+
`)}function H6($,Y,Z){let X=Math.max(0,Math.min(Z,Y.length)),Q=Y.slice(0,X),J=Y.slice(X);return{newValue:Q+$+J,newCursorPosition:X+$.length}}function s3({value:$,placeholder:Y="",focus:Z=!0,onChange:X,cursorPosition:Q,onChangeCursorPosition:J,onPaste:q,onImagePaste:G,disabledKeys:K=[]}){let W=Lq({chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0});o3(()=>{return()=>{if(W.current.timeoutId)clearTimeout(W.current.timeoutId)}},[]),o3(()=>{if(Q>$.length)J($.length)},[$,Q,J]);let O=zq(()=>{let z=W.current;if(z.timeoutId)clearTimeout(z.timeoutId);let F=setTimeout(async()=>{let w=W.current.chunks,L=W.current.totalLength;if(w.length===0)return;let N=O6(w.join(""));if(W.current={chunks:[],timeoutId:null,firstInputTime:null,lastInputTime:null,totalLength:0},G&&k8(N))try{let D=await n3(N);if(D){let C=await G(D.base64,D.mediaType,D.filename);if(C?.prompt){let p=O6(C.prompt),{newValue:y,newCursorPosition:M}=H6(p,$,Q);X(y),J(M)}return}}catch(D){console.error("Failed to process image path:",D)}let A=N.includes(`
|
|
1500
|
+
`),V=L>x1.MEDIUM_SIZE_MULTI_CHUNK_THRESHOLD&&w.length>3;if((L>x1.LARGE_INPUT_THRESHOLD||A||V)&&q){let D=await q(N);if(D?.prompt){let C=O6(D.prompt),{newValue:p,newCursorPosition:y}=H6(C,$,Q);X(p),J(y);return}}let{newValue:R,newCursorPosition:B}=H6(N,$,Q);X(R),J(B)},x1.TIMEOUT_MS);W.current.timeoutId=F});Bq((z,F)=>{let w=O6(z);if(K.some((R)=>F[R])||F.ctrl&&z==="c"||F.shift&&F.tab||w==="?"&&$==="")return;let N=Date.now(),A=W.current,V=Q,E=$;if(F.leftArrow)V--;else if(F.rightArrow)V++;else if(F.backspace||F.delete){if(z===""){if(Q>0)E=$.slice(0,Q-1)+$.slice(Q,$.length),V--}else if(Q<$.length)E=$.slice(0,Q)+$.slice(Q+1,$.length)}else if(F.ctrl&&w==="a")V=0;else if(F.ctrl&&w==="e")V=$.length;else if(F.ctrl&&w==="k")E=$.slice(0,Q);else if(F.ctrl&&w==="u")E=$.slice(Q),V=0;else if(F.ctrl&&w==="w"){let B=$.slice(0,Q).match(/\s*\S+\s*$/);if(B){let D=B[0].length;E=$.slice(0,Q-D)+$.slice(Q),V-=D}}else if(F.pageUp)V=0;else if(F.pageDown)V=$.length;else if(w===`
|
|
1501
|
+
`&&(F.shift||F.meta)){let{newValue:R,newCursorPosition:B}=H6(w,$,Q);X(R),J(B);return}else if(!F.ctrl&&!F.meta){if(!A.firstInputTime)A.firstInputTime=N;A.lastInputTime=N;let R=N-(A.firstInputTime||N),B=w.length>x1.LARGE_INPUT_THRESHOLD,D=w.includes(`
|
|
1502
|
+
`)&&w.length>1,C=R<x1.RAPID_INPUT_THRESHOLD_MS&&A.chunks.length>0,p=R<x1.RAPID_INPUT_THRESHOLD_MS&&w.length>10,y=A.timeoutId!==null;if(q&&(B||D||C||p||y)){A.chunks.push(w),A.totalLength+=w.length,O();return}if(w.length===1&&!A.timeoutId)A.chunks=[],A.firstInputTime=null,A.lastInputTime=null,A.totalLength=0;E=$.slice(0,Q)+w+$.slice(Q,$.length),V+=w.length}if(V<0)V=0;if(V>E.length)V=E.length;if(E!==$)X(E);if(V!==Q)J(V)},{isActive:Z});let U=Z,H=$,_=Y?Q$.grey(Y):void 0;if(U)if(_=Y.length>0?Q$.inverse(Y[0])+Q$.grey(Y.slice(1)):Q$.inverse(" "),$.length===0)H=Q$.inverse(" ");else{H="";for(let z=0;z<$.length;z++)if(z===Q&&Q<$.length)H+=Q$.inverse($[z]);else H+=$[z];if(Q>=$.length)H+=Q$.inverse(" ")}return Rq(Nq,{children:Y?$.length>0?H:_:H},void 0,!1,void 0,this)}import{jsxDEV as v8}from"react/jsx-dev-runtime";var e3=Dq.memo(({input:$,cursorPosition:Y,onChange:Z,onChangeCursorPosition:X})=>{let J=i0()==="main-input",q=t3((K)=>{let W=K.split(`
|
|
1503
|
+
`).length,O=K.length,U=500,H=10;if(O>500||W>10){let _=K.slice(0,30).replace(/\n/g," ");return{prompt:`[Pasted: ${O} chars, ${W} lines] ${_}...`}}return{}}),G=t3(async(K,W,O)=>{try{return{prompt:`[Image saved to ${c3(K,W,O).filePath}. Note: Image attachments not yet supported by @ mentions] `}}catch(U){return console.error("[Image Paste] Failed to process image:",U),{prompt:`[Image paste failed: ${U instanceof Error?U.message:"Unknown error"}] `}}});return v8(bq,{flexDirection:"row",paddingX:2,paddingY:0,borderStyle:"round",borderColor:"gray",children:[v8(Vq,{color:"blue",bold:!0,children:"> "},void 0,!1,void 0,this),v8(s3,{value:$,cursorPosition:Y,onChange:Z,onChangeCursorPosition:X,onPaste:q,onImagePaste:G,placeholder:" 输入命令...",focus:J,disabledKeys:["upArrow","downArrow","tab","return","escape"]},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{Box as _6,Text as W1}from"ink";import yq,{useEffect as Eq,useState as jq}from"react";import{useEffect as Mq,useState as XY}from"react";import{useEffect as Iq,useState as kq}from"react";var vq=15000,$Y=["炼化代码灵气...","参悟 AST 道法...","推演算法天机...","重铸代码根基...","破解逻辑封印...","凝练类型真元...","铸就函数金丹...","渡劫编译雷劫...","打通模块任督二脉...","修炼 Tree-shaking 神功...","压缩代码乾坤...","布下 Source Map 阵法...","推演 Token 灵数...","炼制 Prompt 仙丹...","调息温度参数...","参透困惑度玄机...","驱动 LLM 灵力...","施展向量搜索术...","构筑 RAG 法阵...","凝聚 Embedding 道果...","勾连向量宝库...","破译函数咒语...","验证 Schema 真意...","封印工具参数...","注入系统道韵...","串联历史因果...","炼化抽象语法树...","破境重构神功...","感悟类型天道...","筑基模块根基...","施展词法轻功...","破解语法阵法...","参悟语义心法...","凝练中间内力...","修炼优化神功...","调息寄存器真气...","运转指令招式...","消除死码杂念...","折叠常量真元...","内联函数身法...","逃逸分析密探...","垃圾回收扫地僧...","标记清除掌法...","分代回收心诀...","增量收功法门...","JIT 即时顿悟...","解读字节码暗器...","V8 引擎神功...","召唤 WASM 傀儡...","开辟虚拟洞府...","丹田分配内存...","掌控栈帧乾坤...","捕获异常剑气...","尾调优化身法...","动态链接飞剑...","建立 TCP 金桥...","三次握手结契...","传送 HTTP 飞书...","破译响应符文...","TLS 秘境握手...","验证 SSL 信物...","WebSocket 通灵...","流式传功大法...","gRPC 御剑飞行...","Protobuf 封印术...","GraphQL 问道...","DNS 测算域名...","负载均衡五行阵...","CDN 边缘瞬移...","HTTP/2 分身术...","QUIC 闪现神通...","gzip 缩地成寸...","Brotli 玄冰压缩...","断点续传接续术...","分片上传合璧功...","参研 SQL 真经...","推演查询路径...","索引扫描神识...","全表扫描暴力突破...","执行 JOIN 双修大法...","聚合数据炼丹...","事务提交天地誓...","ACID 四象护法...","乐观锁道心无畏...","悲观锁剑阵守护...","分布式锁万里封禁...","Redis 炼药鼎缓存...","LRU 新陈代谢...","WAL 预写因果簿...","B+ 树平衡阴阳...","LSM 树合璧压缩...","向量宝库搜寻...","余弦相似度测算...","KNN 近邻追踪...","倒排索引翻阅秘籍...","快速排序剑法...","归并排序双刀...","堆排优化内功...","二分查找闪现...","深度优先潜行...","广度优先横扫...","Dijkstra 寻路神算...","A* 天机推演...","动态规划填棋盘...","回溯剑法剪枝...","贪心策略奇谋...","分治递归化身术...","哈希表扩容开天...","红黑树旋转太极...","AVL 树平衡阴阳...","跳表纵身轻功...","Trie 树千头万绪...","布隆过滤天罗地网...","一致性哈希环定乾坤...","最小生成树扎根...","Docker 镜像炼制...","Kubernetes 调兵遣将...","容器结界布阵...","卷挂载空间挪移...","Helm 符箓展开...","CI/CD 流水线作业...","GitHub 门派行动...","代码品鉴术...","漏洞探查密探...","依赖追溯寻根...","蓝绿部署换防...","金丝雀试探...","回滚时光倒流...","健康探查望闻问切...","日志归档藏经阁...","监控预警千里眼...","告警通知飞鸽传书...","性能调优筋骨重塑...","扩容缩容易筋经...","灰度发布声东击西...","React 虚影对决...","组件树调和大法...","Hooks 勾魂术...","useEffect 副作用因果...","Redux 中枢天宫...","Zustand 灵台藏识...","CSS-in-JS 画地为牢...","Tailwind 疾风步...","Webpack 热更换血重生...","Vite 按需凝形...","ESBuild 极速神行...","SWC 闪电炼形...","SSR 天地初开...","Hydration 魂归肉身...","Ink 终端墨宝...","虚拟 DOM 镜花水月...","事件冒泡顺流而上...","状态提升登峰造极...","懒加载厚积薄发...","代码分割庖丁解牛...","SHA-256 炼心咒...","AES-256 玄冰封印...","RSA 阴阳双钥...","JWT 信物令牌...","OAuth 门派授权...","CSRF 防御结界...","XSS 祛邪过滤...","SQL 注入克星...","PBKDF2 淬炼秘钥...","零知识誓言验证...","HTTPS 金钟罩...","签名验证印玺鉴定...","盐值加密炼丹配方...","双因素认证双重认证...","权限控制天条律令...","拜见图灵祖师爷...","冯·诺依曼传道...","Linus 大侠坐镇...","参悟 Rust 生命轮回...","逃离回调地狱轮回...","await 静待天时...","捕获野生 Bug 妖兽...","喂养橡皮鸭灵兽 \uD83E\uDD86...","炼丹调参秘术...","0xDEADBEEF 死亡凝视...","递归无限轮回...","闭包封印记忆...","Promise 未来契约...","async 异步神功...","Generator 分身术...","Proxy 替身傀儡...","Reflect 返照镜...","Symbol 独一无二印记...","WeakMap 过眼云烟...","Iterator 周而复始...","GitHub 武林大会...","Star 点赞声望...","Fork 拜师学艺...","Pull Request 挑战切磋...","Code Review 武功点评...","Issue 悬赏令...","Merge 收徒入门...","Commit 闭关修炼记录...","Branch 分支独辟蹊径...","Tag 里程碑界碑...","Release 出关发布...","License 门规戒律...","README 入门心法...","Documentation 武学秘籍...","Open Source 广纳贤才..."],YY=["Esc - 立即停止当前任务","Shift+Tab - 切换权限模式 (default/auto_edit/plan)","Tab - 智能补全斜杠命令","↑↓ - 浏览输入历史记录","双击 Esc - 快速清空输入框","Ctrl+C - 强制终止程序","Ctrl+D - 优雅退出 Blade","Ctrl+L - 清屏(保留历史)","Ctrl+R - 反向搜索历史","Ctrl+U - 清空当前行","/help - 查看完整帮助文档","/init - 生成 BLADE.md 项目配置","/resume - 恢复历史会话","/compact - 手动压缩上下文(节省 token)","/theme - 打开主题选择器","/config - 打开配置面板","/model - 管理与切换模型配置","/permissions - 管理工具权限规则","/mcp - 查看 MCP 服务器状态","/agents - 管理 Subagent 配置","/version - 显示版本信息","/clear - 清除屏幕内容","/status - 显示当前项目配置状态","/context - 可视化当前上下文使用情况","/cost - 显示会话成本统计","/exit - 退出 REPL","@ 文件路径 - 附加文件到上下文","@dir/ - 附加整个目录","@file.ts:10-20 - 附加指定行范围","Plan 模式 - 先规划后编码(/plan)","Auto Edit 模式 - 自动批准工具调用","MCP 协议 - 扩展外部工具集成","Subagents - 并行执行子任务","Hooks 系统 - 自定义工具执行流程","Context 压缩 - 自动总结历史对话","Loop 检测 - 防止无限循环","提示:使用 /init 让 AI 理解你的项目结构","提示:Plan 模式适合复杂多步骤任务","提示:Auto Edit 可加速重复性操作","提示:@ 引用可提供更精准的上下文","提示:定期 /compact 节省 token 成本","提示:使用 /permissions 控制工具权限","提示:Shift+Tab 快速切换模式","提示:Esc 可随时中断长时间任务","提示:/resume 继续未完成的对话","提示:/export 保存重要对话记录"];function ZY($,Y){let[Z,X]=kq("");return Iq(()=>{if(Y){X("等待用户确认...");return}if(!$){X("");return}let Q=()=>{if(Math.random()<0.16666666666666666){let K=Math.floor(Math.random()*YY.length);return YY[K]}let G=Math.floor(Math.random()*$Y.length);return $Y[G]};X(Q());let J=setInterval(()=>{X(Q())},vq);return()=>{clearInterval(J)}},[$,Y]),Z}function QY($,Y=!1){let[Z,X]=XY(0),[Q,J]=XY(null),q=ZY($,Y);return Mq(()=>{if(!$){X(0),J(null);return}if(Q===null)J(Date.now());let G=setInterval(()=>{if(Q!==null){let K=Math.floor((Date.now()-Q)/1000);X(K)}},1000);return()=>{clearInterval(G)}},[$,Q]),{currentPhrase:q,elapsedTime:Z}}import{jsxDEV as M0,Fragment as Sq}from"react/jsx-dev-runtime";var M8=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],Pq=80;function JY($){if($<60)return`${$}s`;let Y=Math.floor($/60),Z=$%60;return`${Y}m ${Z}s`}var qY=yq.memo(({message:$})=>{let Y=f1(),Z=o2(),X=Y||!Z,[Q,J]=jq(0),q=$0.getTheme(),K=P$()>=Pq,{currentPhrase:W,elapsedTime:O}=QY(X,!1);if(Eq(()=>{if(!X){J(0);return}let H=setInterval(()=>{J((_)=>(_+1)%M8.length)},80);return()=>clearInterval(H)},[X]),!X)return null;let U=W||$||"正在思考中...";if(K)return M0(_6,{paddingX:2,paddingBottom:1,flexDirection:"row",gap:1,children:[M0(W1,{color:q.colors.warning,bold:!0,children:M8[Q]},void 0,!1,void 0,this),M0(W1,{color:q.colors.text.primary,children:U},void 0,!1,void 0,this),O>0&&M0(Sq,{children:[M0(W1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:q.colors.info,children:["已用时: ",JY(O)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),M0(W1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:q.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return M0(_6,{paddingX:2,paddingBottom:1,flexDirection:"column",children:[M0(_6,{flexDirection:"row",gap:1,children:[M0(W1,{color:q.colors.warning,bold:!0,children:M8[Q]},void 0,!1,void 0,this),M0(W1,{color:q.colors.text.primary,children:U},void 0,!1,void 0,this)]},void 0,!0,void 0,this),O>0&&M0(_6,{marginLeft:2,flexDirection:"row",gap:1,children:[M0(W1,{color:q.colors.info,children:["已用时: ",JY(O)]},void 0,!0,void 0,this),M0(W1,{color:q.colors.muted,children:"|"},void 0,!1,void 0,this),M0(W1,{color:q.colors.secondary,children:"Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as O2,Static as pq}from"ink";import gq,{useMemo as E8}from"react";import{Box as W2,Text as U2}from"ink";import Tq from"ink-big-text";import Cq from"ink-gradient";import fq from"react";import{jsxDEV as t0}from"react/jsx-dev-runtime";var GY=fq.memo(()=>{return t0(W2,{flexDirection:"column",paddingX:2,paddingTop:1,paddingBottom:1,children:[t0(W2,{flexDirection:"column",children:t0(Cq,{name:"pastel",children:t0(Tq,{text:"BLADE",font:"block"},void 0,!1,void 0,this)},void 0,!1,void 0,this)},void 0,!1,void 0,this),t0(W2,{marginBottom:1,children:t0(U2,{color:"white",dimColor:!0,children:x8()},void 0,!1,void 0,this)},void 0,!1,void 0,this),t0(W2,{flexDirection:"column",marginBottom:1,children:[t0(W2,{marginBottom:1,children:t0(U2,{color:"white",bold:!0,children:"使用指南:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),t0(U2,{color:"white",children:"1. 输入问题、编辑文件或运行命令"},void 0,!1,void 0,this),t0(U2,{color:"white",children:"2. 使用 /init 创建项目配置文件"},void 0,!1,void 0,this),t0(U2,{color:"white",children:"3. 输入 /help 查看所有 slash 命令"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)});import{Box as F6,Text as y8}from"ink";import{useState as KY}from"react";function hq(){let[$,Y]=KY($0.getTheme()),[Z,X]=KY($0.getCurrentThemeName()),Q=(K)=>{try{$0.setTheme(K),Y($0.getTheme()),X(K)}catch(W){console.error("Failed to change theme:",W)}},J=$0.getAvailableThemes();return{theme:$,themeName:Z,changeTheme:Q,availableThemes:J,hasTheme:(K)=>$0.hasTheme(K),getThemeByName:(K)=>$0.getThemeByName(K),colors:$.colors,spacing:$.spacing,typography:$.typography}}function WY(){let{colors:$}=hq();return $}import{jsxDEV as p1}from"react/jsx-dev-runtime";var UY=({todos:$,visible:Y=!0,compact:Z=!1})=>{let X=WY();if(!Y||$.length===0)return null;let Q={total:$.length,completed:$.filter((J)=>J.status==="completed").length,inProgress:$.filter((J)=>J.status==="in_progress").length};return p1(F6,{flexDirection:"column",borderStyle:"single",borderColor:X.border.light,paddingX:1,paddingY:Z?0:1,marginBottom:1,children:[p1(F6,{marginBottom:Z?0:1,children:[p1(y8,{dimColor:!0,children:"Tasks "},void 0,!1,void 0,this),p1(y8,{color:X.text.muted,children:[Q.completed,"/",Q.total]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),p1(F6,{flexDirection:"column",children:$.map((J,q)=>p1(xq,{todo:J,compact:Z},J.id||q,!1,void 0,this))},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},xq=({todo:$,compact:Y})=>{let Z,X=!1,Q;switch($.status){case"completed":Z="✓",X=!0,Q=$.content;break;case"in_progress":Z="▶",X=!1,Q=$.activeForm;break;case"pending":default:Z="○",X=!0,Q=$.content;break}return p1(F6,{paddingY:Y?0:0,children:p1(y8,{dimColor:X,children:[Z," ",Q]},void 0,!0,void 0,this)},void 0,!1,void 0,this)};import{jsxDEV as w1}from"react/jsx-dev-runtime";var OY=gq.memo(()=>{let $=a2(),Y=f1(),Z=b5(),X=k5(),Q=S5(),J=P$(),{completedMessages:q,streamingMessage:G}=E8(()=>{if(Y&&$.length>0)return{completedMessages:$.slice(0,-1),streamingMessage:$[$.length-1]};return{completedMessages:$,streamingMessage:null}},[$,Y]),K=E8(()=>{return Z.some((U)=>U.status==="pending"||U.status==="in_progress")},[Z]),W=(U,H,_=!1)=>w1(O2,{flexDirection:"column",children:w1(K2,{content:U.content,role:U.role,terminalWidth:J,metadata:U.metadata,isPending:_},void 0,!1,void 0,this)},U.id,!1,void 0,this),O=E8(()=>{let U=[];return U.push(w1(GY,{},"header",!1,void 0,this)),q.forEach((H,_)=>{U.push(W(H,_))}),U},[q,J]);return w1(O2,{flexDirection:"column",flexGrow:1,paddingX:2,children:w1(O2,{flexDirection:"column",flexGrow:1,children:[w1(pq,{items:O,children:(U)=>U},void 0,!1,void 0,this),G&&W(G,q.length,!0),X&&K&&w1(O2,{marginTop:1,children:w1(UY,{todos:Z,visible:!0,compact:!1},void 0,!1,void 0,this)},void 0,!1,void 0,this),Q.map((U,H)=>w1(O2,{flexDirection:"column",children:w1(K2,{content:U,role:"user",terminalWidth:J},void 0,!1,void 0,this)},`pending-${H}`,!1,void 0,this))]},void 0,!0,void 0,this)},void 0,!1,void 0,this)});import{Box as l,Text as h,useFocus as HY,useFocusManager as mq,useInput as B6}from"ink";import uq from"ink-select-input";import dq from"ink-text-input";import{useEffect as cq,useState as H2}from"react";import{jsxDEV as I,Fragment as N6}from"react/jsx-dev-runtime";var lq=({isSelected:$})=>I(l,{marginRight:1,children:I(h,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),iq=({isSelected:$,label:Y})=>I(h,{bold:$,color:$?"yellow":void 0,children:Y},void 0,!1,void 0,this),rq=({onSelect:$,onCancel:Y,initialProvider:Z})=>{let{isFocused:X}=HY({id:"provider-step"});B6((q,G)=>{if(G.escape)Y()},{isActive:X});let Q=[{label:"⚡ OpenAI Compatible - 兼容 OpenAI API 的服务 (千问/豆包/DeepSeek等)",value:"openai-compatible"},{label:"\uD83E\uDD16 Anthropic Claude API - Claude 官方 API",value:"anthropic"}],J=Z?Math.max(0,Q.findIndex((q)=>q.value===Z)):0;return I(l,{flexDirection:"column",marginBottom:1,children:[I(l,{marginBottom:1,children:I(h,{bold:!0,color:"blue",children:"\uD83D\uDCE1 Step 2: 选择 API 提供商"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:"根据您使用的 LLM 服务选择对应的 API 类型"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(uq,{items:Q,onSelect:(q)=>$(q.value),indicatorComponent:lq,itemComponent:iq,initialIndex:J},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},z6=({stepNumber:$,icon:Y,title:Z,description:X,hint:Q,examples:J,value:q,placeholder:G,mask:K,previousValue:W,onChange:O,onSubmit:U,onCancel:H})=>{return B6((_,z)=>{if(z.escape)H()},{isActive:!0}),I(l,{flexDirection:"column",marginBottom:1,children:[I(l,{marginBottom:1,children:I(h,{bold:!0,color:"blue",children:[Y," Step ",$,": ",Z]},void 0,!0,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:X},void 0,!1,void 0,this)},void 0,!1,void 0,this),W&&I(l,{marginBottom:1,children:I(h,{color:"green",children:["✓ ",W]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Q&&I(l,{marginBottom:1,children:I(h,{dimColor:!0,children:Q},void 0,!1,void 0,this)},void 0,!1,void 0,this),J&&J.length>0&&I(N6,{children:[I(l,{marginBottom:1,children:I(h,{dimColor:!0,children:"常见示例:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,paddingLeft:2,children:I(h,{dimColor:!0,children:J.join(`
|
|
1504
|
+
`)},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I(l,{children:[I(h,{bold:!0,color:"cyan",children:["▶"," "]},void 0,!0,void 0,this),I(dq,{value:q,onChange:O,onSubmit:U,placeholder:G,mask:K},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},aq=({mode:$,config:Y,isSaving:Z,onConfirm:X,onBack:Q,onCancel:J})=>{let{isFocused:q}=HY({id:"confirm-step"});return B6((G,K)=>{if(Z)return;if(G==="y"||G==="Y")X();else if(G==="n"||G==="N")Q();else if(K.escape)J()},{isActive:q&&!Z}),I(l,{flexDirection:"column",marginBottom:1,children:[I(l,{marginBottom:1,children:I(h,{bold:!0,color:$==="edit"?"yellow":"blue",children:$==="edit"?"\uD83D\uDCBE 确认修改":"✅ Step 6: 确认配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:$==="edit"?"请确认修改内容,保存后将立即生效。":"请确认以下配置信息:"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{flexDirection:"column",marginBottom:1,paddingLeft:2,children:[I(l,{marginBottom:1,children:[I(h,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),I(h,{bold:!0,color:"cyan",children:Y.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I(l,{marginBottom:1,children:[I(h,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),I(h,{bold:!0,color:"cyan",children:Y.provider==="openai-compatible"?"⚡ OpenAI Compatible":"\uD83E\uDD16 Anthropic"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I(l,{marginBottom:1,children:[I(h,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),I(h,{bold:!0,color:"blue",children:Y.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),I(l,{marginBottom:1,children:[I(h,{dimColor:!0,children:"API Key: "},void 0,!1,void 0,this),I(h,{bold:!0,color:"yellow",children:[Y.apiKey?.slice(0,8),"*".repeat(Math.min(32,(Y.apiKey?.length||0)-8))]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),I(l,{children:[I(h,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),I(h,{bold:!0,color:"cyan",children:Y.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),!Z&&I(l,{marginTop:1,children:I(h,{children:[$==="edit"?"保存修改? ":"确认保存配置? ","[",I(h,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this),"/",I(h,{bold:!0,color:"red",children:"n"},void 0,!1,void 0,this),"]"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),Z&&I(l,{children:I(h,{color:"yellow",children:"⏳ 正在保存配置到 ~/.blade/config.json..."},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},j8=({mode:$,initialConfig:Y,modelId:Z,onComplete:X,onCancel:Q})=>{let J=$==="edit",[q,G]=H2("name"),[K,W]=H2(()=>J&&Y?{...Y}:{}),[O,U]=H2(J&&Y?Y.name:""),[H,_]=H2(!1),[z,F]=H2(null),w=b0(!1);B6((M,i)=>{if(i.ctrl&&M==="c"||i.meta&&M==="c")if($==="setup")w();else Q()},{isActive:!0});let{focus:L}=mq();cq(()=>{if(q==="provider")L("provider-step");else if(q==="confirm")L("confirm-step")},[q,L]);let N=()=>{if(!O.trim()){F("配置名称不能为空");return}W({...K,name:O}),U(""),F(null),G("provider")},A=(M)=>{W({...K,provider:M});let i=J?K.baseUrl??Y?.baseUrl??"":"";U(i),G("baseUrl")},V=()=>{if(!O.trim()){F("Base URL 不能为空");return}try{new URL(O)}catch{F("请输入有效的 URL (例如: https://api.openai.com/v1)");return}W({...K,baseUrl:O});let M=J?K.apiKey??Y?.apiKey??"":"";U(M),F(null),G("apiKey")},E=()=>{if(!O.trim()){F("API Key 不能为空");return}W({...K,apiKey:O});let M=J?K.model??Y?.model??"":"";U(M),F(null),G("model")},R=()=>{if(!O.trim()){F("Model 不能为空");return}W({...K,model:O}),U(""),F(null),G("confirm")},B=async()=>{_(!0),F(null);try{let M={name:K.name,provider:K.provider,baseUrl:K.baseUrl,apiKey:K.apiKey,model:K.model};if($==="setup")X(M);else if($==="add")await e().addModel(M),X(M);else{if(!Z)throw Error("未提供模型 ID,无法编辑");await e().updateModel(Z,M),X(M)}}catch(M){F(M instanceof Error?M.message:"配置失败"),_(!1)}},D=()=>{switch(F(null),U(""),q){case"provider":U(K.name||""),G("name");break;case"baseUrl":G("provider");break;case"apiKey":U(K.baseUrl||""),G("baseUrl");break;case"model":G("apiKey");break;case"confirm":U(K.model||""),G("model");break}},C=q==="name"?1:q==="provider"?2:q==="baseUrl"?3:q==="apiKey"?4:q==="model"?5:6,p=Math.floor((C-1)/5*40);return I(l,{...$==="setup"?{flexDirection:"column",padding:1}:$==="add"?{flexDirection:"column",borderStyle:"round",borderColor:"blue",padding:1}:{flexDirection:"column",borderStyle:"round",borderColor:"yellow",padding:1},children:[$==="setup"?I(N6,{children:[I(l,{marginBottom:1,children:I(h,{bold:!0,color:"blue",children:"\uD83D\uDE80 欢迎使用 Blade Code"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:"AI 驱动的代码助手 - 让我们开始配置您的助手"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:[I(h,{bold:!0,color:"blue",children:"█".repeat(p)},void 0,!1,void 0,this),I(h,{dimColor:!0,children:"░".repeat(40-p)},void 0,!1,void 0,this),I(h,{children:" "},void 0,!1,void 0,this),I(h,{bold:!0,color:"cyan",children:[C,"/6"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),I(l,{marginBottom:1,children:I(h,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):$==="add"?I(N6,{children:[I(l,{justifyContent:"center",marginBottom:1,children:I(h,{bold:!0,color:"blue",children:"添加新模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:["步骤: ",C,"/6"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this):I(N6,{children:[I(l,{justifyContent:"center",marginBottom:1,children:I(h,{bold:!0,color:"yellow",children:"编辑模型配置"},void 0,!1,void 0,this)},void 0,!1,void 0,this),I(l,{marginBottom:1,children:I(h,{children:["步骤: ",C,"/6"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q==="name"&&I(z6,{stepNumber:1,icon:"\uD83D\uDCDD",title:"配置名称",description:"给这个模型配置起一个易于识别的名称",value:O,placeholder:"例如: 千问工作账号",onChange:U,onSubmit:N,onCancel:Q},void 0,!1,void 0,this),q==="provider"&&I(rq,{onSelect:A,onCancel:Q,initialProvider:K.provider},void 0,!1,void 0,this),q==="baseUrl"&&I(z6,{stepNumber:3,icon:"\uD83C\uDF10",title:"配置 Base URL",description:"输入您的 API 端点地址(完整的 URL 包含协议)",examples:["• OpenAI: https://api.openai.com/v1","• 千问: https://dashscope.aliyuncs.com/compatible-mode/v1","• 豆包: https://ark.cn-beijing.volces.com/api/v3","• DeepSeek: https://api.deepseek.com/v1"],value:O,placeholder:"https://api.example.com/v1",onChange:U,onSubmit:V,onCancel:Q},void 0,!1,void 0,this),q==="apiKey"&&I(z6,{stepNumber:4,icon:"\uD83D\uDD11",title:"输入 API Key",description:"您的 API 密钥将被安全存储在 ~/.blade/config.json (权限 600)",hint:"\uD83D\uDCA1 提示: 输入时字符会被隐藏,支持粘贴 (Ctrl+V / Cmd+V)",previousValue:K.baseUrl?`✓ 当前 Base URL: ${K.baseUrl}`:void 0,value:O,placeholder:"sk-...",mask:"*",onChange:U,onSubmit:E,onCancel:Q},void 0,!1,void 0,this),q==="model"&&I(z6,{stepNumber:5,icon:"\uD83E\uDD16",title:"选择模型",description:"输入您想使用的模型名称(请参考您的 API 提供商文档)",examples:["• OpenAI: gpt-5, gpt-5-mini, gpt-5-nano","• Claude: claude-sonnet-4.5, claude-opus-4.1","• 千问: qwen3-max, qwen3-235b, qwen3-32b","• DeepSeek: deepseek-v3.1, deepseek-r1-0528","• 豆包: doubao-seed-1.6, doubao-seed-1.6-flash"],value:O,placeholder:"例如: gpt-5",onChange:U,onSubmit:R,onCancel:Q},void 0,!1,void 0,this),q==="confirm"&&I(aq,{mode:$,config:K,isSaving:H,onConfirm:B,onBack:D,onCancel:Q},void 0,!1,void 0,this),z&&I(l,{marginTop:1,borderStyle:"round",borderColor:"red",paddingX:1,children:I(h,{color:"red",children:["❌ ",z]},void 0,!0,void 0,this)},void 0,!1,void 0,this),I(l,{marginTop:1,children:I(h,{dimColor:!0,children:"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"},void 0,!1,void 0,this)},void 0,!1,void 0,this),!H&&q==="provider"&&I(l,{marginTop:1,children:I(h,{dimColor:!0,children:["\uD83D\uDCA1 使用 ",I(h,{bold:!0,children:"↑/↓"},void 0,!1,void 0,this)," 键选择,",I(h,{bold:!0,children:"Enter"},void 0,!1,void 0,this)," 确认,",I(h,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!H&&q!=="confirm"&&q!=="provider"&&I(l,{marginTop:1,children:I(h,{dimColor:!0,children:["\uD83D\uDCA1 输入完成后按 ",I(h,{bold:!0,children:"Enter"},void 0,!1,void 0,this),",",I(h,{bold:!0,children:"Ctrl+C"},void 0,!1,void 0,this)," 退出"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),!H&&q==="confirm"&&I(l,{marginTop:1,children:I(h,{dimColor:!0,children:["\uD83D\uDCA1 按"," ",I(h,{bold:!0,color:"green",children:"Y"},void 0,!1,void 0,this)," ","保存,",I(h,{bold:!0,color:"red",children:"N"},void 0,!1,void 0,this)," ","返回修改,",I(h,{bold:!0,children:"Esc"},void 0,!1,void 0,this)," 取消"]},void 0,!0,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as L6,useMount as nq}from"ahooks";import{Box as e0,Text as X0,useFocus as oq,useFocusManager as sq,useInput as tq}from"ink";import eq from"ink-select-input";import{memo as $G,useMemo as YG,useState as w6}from"react";import{jsxDEV as u}from"react/jsx-dev-runtime";var ZG=({isSelected:$})=>u(e0,{marginRight:1,children:u(X0,{color:$?"yellow":"gray",children:$?"▶":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),XG=({isSelected:$,label:Y})=>u(X0,{bold:$,color:$?"yellow":void 0,children:Y},void 0,!1,void 0,this),_Y=$G(({onClose:$,onEdit:Y})=>{let Z=v5(),X=y5()??"",{isFocused:Q}=oq({id:"model-selector"}),J=sq(),[q,G]=w6(""),[K,W]=w6(!1),[O,U]=w6(null),H=b0(!1),[_]=w6(()=>{let R=process.stdout?.columns||80;return Math.max(20,R-8)});nq(()=>{if(J?.focus("model-selector"),Z.length>0)G(Z[0].id)}),tq((R,B)=>{if(K)return;if(B.ctrl&&R==="c"||B.meta&&R==="c"){H();return}if(B.escape){$();return}if(!Q)return;if(R==="d"||R==="D"){F();return}if((R==="e"||R==="E")&&Y)w()},{isActive:!0});let z=L6(async(R)=>{if(K)return;let B=R.value;if(B===X){$();return}W(!0),U(null);try{await e().setCurrentModel(B),$()}catch(D){U(D.message),W(!1)}}),F=L6(async()=>{if(K||q===X)return;W(!0),U(null);try{if(await e().removeModel(q),Z.length<=1)$()}catch(R){U(R.message)}finally{W(!1)}}),w=L6(()=>{if(K||!Y)return;let R=Z.find((B)=>B.id===q);if(!R)return;Y(R)}),L=L6((R)=>{G(R.value)}),N=YG(()=>{return Z.find((R)=>R.id===q)},[Z,q]),A=Z.map((R)=>({label:R.name+(R.id===X?" (当前)":""),value:R.id})),V=q===X;return u(e0,{flexDirection:"column",borderStyle:"round",borderColor:"gray",padding:1,width:"100%",children:[u(e0,{flexDirection:"row",justifyContent:"space-between",marginBottom:1,children:[u(X0,{bold:!0,color:"cyan",children:"模型管理"},void 0,!1,void 0,this),u(X0,{dimColor:!0,children:[K?"⏳ 处理中...":V?"Enter=关闭 • E=编辑 • Esc=取消":"Enter=切换 • D=删除 • E=编辑 • Esc=取消"," • Ctrl+C=退出"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),u(e0,{flexDirection:"row",children:[u(e0,{flexDirection:"column",flexGrow:2,marginRight:2,borderStyle:"single",borderColor:"gray",padding:1,children:[u(X0,{dimColor:!0,children:["已配置模型 (",Z.length,")"]},void 0,!0,void 0,this),u(e0,{marginTop:1,children:u(eq,{items:A,onSelect:z,onHighlight:L,indicatorComponent:ZG,itemComponent:XG},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u(e0,{flexDirection:"column",flexGrow:3,borderStyle:"single",borderColor:"gray",padding:1,children:[u(X0,{dimColor:!0,children:"模型详情"},void 0,!1,void 0,this),u(e0,{marginY:1,children:u(X0,{color:V?"green":"yellow",children:V?"● 当前使用":"● 可切换"},void 0,!1,void 0,this)},void 0,!1,void 0,this),N?u(e0,{flexDirection:"column",children:[u(X0,{children:[u(X0,{dimColor:!0,children:"名称: "},void 0,!1,void 0,this),u(X0,{bold:!0,color:"cyan",children:N.name},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u(X0,{children:[u(X0,{dimColor:!0,children:"Provider: "},void 0,!1,void 0,this),u(X0,{bold:!0,children:N.provider},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u(X0,{children:[u(X0,{dimColor:!0,children:"Model: "},void 0,!1,void 0,this),u(X0,{bold:!0,children:N.model},void 0,!1,void 0,this)]},void 0,!0,void 0,this),u(X0,{children:[u(X0,{dimColor:!0,children:"Base URL: "},void 0,!1,void 0,this),u(X0,{color:"blueBright",children:N.baseUrl},void 0,!1,void 0,this)]},void 0,!0,void 0,this),N.temperature!==void 0&&u(X0,{children:[u(X0,{dimColor:!0,children:"Temperature: "},void 0,!1,void 0,this),u(X0,{children:N.temperature},void 0,!1,void 0,this)]},void 0,!0,void 0,this),N.maxContextTokens!==void 0&&u(X0,{children:[u(X0,{dimColor:!0,children:"Context Window: "},void 0,!1,void 0,this),u(X0,{children:N.maxContextTokens},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this):u(X0,{dimColor:!0,children:"请选择一个模型查看详情"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),O&&u(e0,{marginTop:1,children:u(X0,{color:"red",children:["❌ ",O]},void 0,!0,void 0,this)},void 0,!1,void 0,this),u(e0,{justifyContent:"center",marginTop:1,children:u(X0,{dimColor:!0,children:"─".repeat(_)},void 0,!1,void 0,this)},void 0,!1,void 0,this),u(e0,{justifyContent:"center",children:u(X0,{dimColor:!0,children:"提示:D=删除 • E=编辑 • ↑↓=移动 • Enter/ESC=确认"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)});import{useMemoizedFn as _2}from"ahooks";import{promises as BY}from"fs";import{Box as x0,Text as U0,useInput as QG}from"ink";import FY from"ink-select-input";import JG from"ink-text-input";import qG from"os";import A6 from"path";import{useEffect as GG,useMemo as R6,useRef as KG,useState as g1}from"react";import{jsxDEV as d}from"react/jsx-dev-runtime";var F2=[{key:"allow",label:"Allow"},{key:"ask",label:"Ask"},{key:"deny",label:"Deny"},{key:"info",label:"Info"}],WG={allow:"Add a new rule...",ask:"Add a new rule...",deny:"Add a new rule..."},UG={allow:"Allow permission rules",ask:"Ask permission rules",deny:"Deny permission rules"},zY={project:"[项目共享配置]",global:"[用户全局配置]",local:"[本地配置]"},OG=["project","global","local"],HG={allow:[],ask:[],deny:[]},_G={localExists:!1,projectExists:!1,globalExists:!1},NY={allow:[],ask:[],deny:[]};function FG($){let Y=(X)=>Array.isArray(X)?X.filter((Q)=>typeof Q==="string"):[],Z=$?.permissions??{};return{allow:Y(Z?.allow),ask:Y(Z?.ask),deny:Y(Z?.deny)}}async function zG($){try{let Y=await BY.readFile($,"utf-8"),Z=JSON.parse(Y);return{exists:!0,raw:Z,permissions:FG(Z)}}catch(Y){if(Y.code==="ENOENT")return{exists:!1,raw:{},permissions:{...NY}};return console.warn(`[PermissionsManager] Failed to read ${$}:`,Y),{exists:!0,raw:{},permissions:{...NY}}}}function NG($,Y){let Z=$.padEnd(32," "),X=Y==="local"?`${zY[Y]} ← 可删除`:zY[Y];return`${Z} ${X}`}var LY=({onClose:$})=>{let Z=i0()==="permissions-manager",X=b0(!1),[Q,J]=g1(0),q=F2[Q].key,[G,K]=g1(HG),[W,O]=g1(_G),[U,H]=g1(!0),[_,z]=g1("list"),[F,w]=g1(""),[L,N]=g1(null),[A,V]=g1(null),E=KG(!1),R=R6(()=>A6.join(process.cwd(),".blade","settings.local.json"),[]),B=R6(()=>A6.join(process.cwd(),".blade","settings.json"),[]),D=R6(()=>A6.join(qG.homedir(),".blade","settings.json"),[]),C=_2(async()=>{H(!0);let c=[{source:"local",path:R},{source:"project",path:B},{source:"global",path:D}],Z0=await Promise.all(c.map(async({source:w0,path:R1})=>{let u0=await zG(R1);return{source:w0,path:R1,...u0}})),a={localExists:Z0.find((w0)=>w0.source==="local")?.exists??!1,projectExists:Z0.find((w0)=>w0.source==="project")?.exists??!1,globalExists:Z0.find((w0)=>w0.source==="global")?.exists??!1};O(a);let h0={allow:[],ask:[],deny:[]},d1=Object.fromEntries(Z0.map((w0)=>[w0.source,w0]));["allow","ask","deny"].forEach((w0)=>{OG.forEach((R1)=>{(d1[R1]?.permissions[w0]??[]).forEach(($1,c1)=>{let k6={key:`${R1}:${c1}:${$1}`,rule:$1,source:R1};h0[w0].push(k6)})})}),K(h0),H(!1)});GG(()=>{C()},[C]);let p=_2(async(c,Z0)=>{try{let a=A6.join(process.cwd(),".blade","settings.local.json"),h0={allow:[],ask:[],deny:[]};try{let w0=await BY.readFile(a,"utf-8"),u0=JSON.parse(w0).permissions||{};h0={allow:Array.isArray(u0.allow)?u0.allow:[],ask:Array.isArray(u0.ask)?u0.ask:[],deny:Array.isArray(u0.deny)?u0.deny:[]}}catch(w0){}let d1=Z0(h0);await e().updateConfig({permissions:d1},{scope:"local",immediate:!0}),await C()}catch(a){throw console.error("[PermissionsManager] 修改权限规则失败:",a),a}});QG((c,Z0)=>{if(Z0.ctrl&&c==="c"||Z0.meta&&c==="c"){X();return}if(_==="locked"){if(E.current){E.current=!1;return}z("list"),N(null),V(null);return}if(Z0.escape){if(_==="list"||q==="info")$();else z("list"),w(""),N(null),V(null);return}if(_==="list"){if(Z0.tab&&Z0.shift)J((a)=>(a-1+F2.length)%F2.length);else if(Z0.tab)J((a)=>(a+1)%F2.length);else if(c?.toLowerCase()==="q")$()}},{isActive:Z});let y=_2((c)=>{let Z0=c.value;if(q==="info")return;if(Z0.type==="add"){z("add"),w(""),V(null);return}if(Z0.entry.source!=="local"){z("locked"),E.current=!0,N({tab:q,entry:Z0.entry}),V({type:"error",text:Z0.entry.source==="project"?"此规则定义在项目共享配置中,无法在此删除。":"此规则来自用户全局配置,无法在此删除。"});return}z("confirm-delete"),N({tab:q,entry:Z0.entry}),V(null)}),M=_2(async()=>{if(q==="info")return;let c=F.trim();if(!c){V({type:"error",text:"Permission rule 不能为空"});return}if(G[q].map((a)=>a.rule).includes(c)){V({type:"error",text:"该规则已存在"});return}try{await p(q,(a)=>{let h0={allow:[...a.allow],ask:[...a.ask],deny:[...a.deny]};return h0[q]=[...new Set([...a[q],c])],h0}),z("list"),w(""),V({type:"success",text:"已添加本地权限规则"})}catch(a){V({type:"error",text:`保存失败: ${a instanceof Error?a.message:"未知错误"}`})}}),i=_2(async()=>{if(!L)return;let{tab:c,entry:Z0}=L;try{await p(c,(a)=>{let h0={allow:[...a.allow],ask:[...a.ask],deny:[...a.deny]};return h0[c]=a[c].filter((d1)=>d1!==Z0.rule),h0}),z("list"),N(null),V({type:"success",text:"已删除本地权限规则"})}catch(a){V({type:"error",text:`删除失败: ${a instanceof Error?a.message:"未知错误"}`})}}),S=R6(()=>{if(q==="info")return[];let c=q;return[{label:`› ${WG[c]}`,value:{type:"add"}},...G[c].map((a)=>({label:NG(a.rule,a.source),value:{type:"rule",entry:a}}))]},[q,G]),U1=()=>d(x0,{marginBottom:1,children:F2.map((c,Z0)=>d(x0,{marginRight:2,children:d(U0,{color:Z0===Q?"yellow":"gray",children:["[",c.label,"]"]},void 0,!0,void 0,this)},c.key,!1,void 0,this))},void 0,!1,void 0,this),Q0=()=>d(x0,{flexDirection:"column",gap:1,children:[d(U0,{children:"配置文件优先级(从高到低):"},void 0,!1,void 0,this),d(x0,{flexDirection:"column",marginLeft:2,children:[d(U0,{children:["1. .blade/settings.local.json (本地配置,不提交 Git)"," ",W.localExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),d(U0,{children:["2. .blade/settings.json (项目配置,提交 Git)"," ",W.projectExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this),d(U0,{children:["3. ~/.blade/settings.json (用户全局配置)"," ",W.globalExists?"✓ 存在":"✗ 不存在"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),d(U0,{children:"说明:"},void 0,!1,void 0,this),d(x0,{flexDirection:"column",marginLeft:2,children:[d(U0,{children:"- /permissions 命令只管理本地配置 (.blade/settings.local.json)"},void 0,!1,void 0,this),d(U0,{children:"- 修改全局或项目配置请直接编辑对应文件"},void 0,!1,void 0,this),d(U0,{children:"- 本地配置不会提交到 Git"},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),_0=(c)=>d(x0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:UG[c]},void 0,!1,void 0,this),d(U0,{children:"Permission rules are a tool name, optionally followed by a specifier in parentheses."},void 0,!1,void 0,this),d(U0,{color:"gray",children:"例如: WebFetch 或 Bash(ls:*)"},void 0,!1,void 0,this),d(x0,{marginTop:1,children:d(JG,{value:F,onChange:w,onSubmit:M},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(U0,{color:"gray",children:"Enter 提交 · Esc 取消"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M1=(c,Z0)=>d(x0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:["Delete ",c," permission rule?"]},void 0,!0,void 0,this),d(U0,{children:Z0.rule},void 0,!1,void 0,this),d(U0,{color:"gray",children:"From project local settings"},void 0,!1,void 0,this),d(U0,{children:"Are you sure you want to delete this permission rule?"},void 0,!1,void 0,this),d(FY,{items:[{label:"Yes",value:"yes"},{label:"No",value:"no"}],onSelect:(a)=>{if(a.value==="yes")i();else z("list"),N(null)}},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q$=(c)=>d(x0,{flexDirection:"column",gap:1,children:[d(U0,{bold:!0,children:"Cannot delete this rule"},void 0,!1,void 0,this),d(U0,{children:c.rule},void 0,!1,void 0,this),d(U0,{color:"gray",children:c.source==="project"?"This rule is defined in .blade/settings.json. 请手动编辑该文件以移除规则。":"This rule is defined in ~/.blade/settings.json. 请手动编辑该文件以移除规则。"},void 0,!1,void 0,this),d(U0,{color:"gray",children:"按任意键继续"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),C$=(c)=>d(FY,{items:S,isFocused:_==="list",onSelect:y},void 0,!1,void 0,this),I6=()=>{if(U)return d(U0,{children:"加载中..."},void 0,!1,void 0,this);if(q==="info")return Q0();if(_==="add")return _0(q);if(_==="confirm-delete"&&L)return M1(L.tab,L.entry);if(_==="locked"&&L)return q$(L.entry);return C$(q)};return d(x0,{flexDirection:"column",borderStyle:"round",borderColor:Z?"cyan":"gray",padding:1,width:80,children:[d(U0,{color:"cyan",bold:!0,children:"⚙️ 权限管理器"},void 0,!1,void 0,this),U1(),d(x0,{flexDirection:"column",gap:1,children:I6()},void 0,!1,void 0,this),A&&d(x0,{marginTop:1,children:d(U0,{color:A.type==="success"?"green":"red",children:A.text},void 0,!1,void 0,this)},void 0,!1,void 0,this),d(x0,{marginTop:1,children:d(U0,{color:"gray",children:"Tab 切换视图 · Esc 关闭 · Q 退出"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{Box as b6,Text as m1,useInput as BG}from"ink";import LG from"ink-select-input";import{useEffect as wG,useMemo as AG,useState as wY}from"react";import{jsxDEV as p0}from"react/jsx-dev-runtime";function RG($){let Y=new Date($),X=new Date().getTime()-Y.getTime(),Q=Math.floor(X/86400000);if(Q===0)return`今天 ${Y.getHours().toString().padStart(2,"0")}:${Y.getMinutes().toString().padStart(2,"0")}`;if(Q===1)return"昨天";if(Q<7)return`${Q}天前`;return`${Y.getMonth()+1}/${Y.getDate()}`}function bG($){let Y=$.split("/");return Y[Y.length-1]||$}var VG=({isSelected:$})=>p0(b6,{marginRight:1,children:p0(m1,{color:$?"cyan":"gray",children:$?"❯":" "},void 0,!1,void 0,this)},void 0,!1,void 0,this),DG=({isSelected:$,label:Y})=>p0(m1,{color:$?"cyan":"white",bold:$,children:Y},void 0,!1,void 0,this),AY=({sessions:$,onSelect:Y,onCancel:Z})=>{let[X,Q]=wY([]),[J,q]=wY(!1),K=i0()==="session-selector",W=b0(!1);BG((_,z)=>{if(z.ctrl&&_==="c"||z.meta&&_==="c"){W();return}if(z.escape&&Z)Z()},{isActive:K}),wG(()=>{if($){Q($);return}(async()=>{q(!0);try{let z=await z1.listSessions();Q(z)}catch(z){console.error("[SessionSelector] Failed to load sessions:",z),Q([])}finally{q(!1)}})()},[$]);let O=$||X,U=AG(()=>{return O.map((_)=>{let z=bG(_.projectPath),F=RG(_.lastMessageTime),w=_.gitBranch?` (${_.gitBranch})`:"",L=_.hasErrors?" ⚠️":"";return{label:`\uD83D\uDCC5 ${F} | ${z}${w} | ${_.messageCount} 条消息${L}`,value:_.sessionId}})},[O]),H=(_)=>{Y(_.value)};if(J)return p0(b6,{flexDirection:"column",paddingX:2,paddingY:1,children:p0(m1,{children:"⏳ 正在加载会话列表..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);if(O.length===0)return p0(b6,{flexDirection:"column",paddingX:2,paddingY:1,children:[p0(m1,{color:"yellow",children:"⚠️ 没有找到历史会话"},void 0,!1,void 0,this),p0(m1,{dimColor:!0,children:[`
|
|
1505
|
+
`,"提示: 开始一次对话后,会话历史将保存到 ~/.blade/projects/"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this);return p0(b6,{flexDirection:"column",paddingX:2,paddingY:1,children:[p0(m1,{bold:!0,color:"cyan",children:"\uD83D\uDCC2 选择要恢复的会话:"},void 0,!1,void 0,this),p0(m1,{dimColor:!0,children:[`
|
|
1506
1506
|
`,"(↑↓ 选择 | Enter 确认 | Esc 取消 | Ctrl+C 退出)",`
|
|
1507
|
-
`]},void 0,!0,void 0,this),
|
|
1508
|
-
`,"共 ",O.length," 个历史会话"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as Aq}from"ahooks";import{Box as A1,Text as S,useInput as Rq}from"ink";import bq from"ink-select-input";import{useState as BY}from"react";import{jsxDEV as M}from"react/jsx-dev-runtime";var NY=N1.map(($)=>({label:$.label,value:$.id})),Vq=({theme:$})=>{let{colors:Y}=$;return M(A1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[M(S,{bold:!0,color:Y.text.primary,children:"代码预览"},void 0,!1,void 0,this),M(S,{children:" "},void 0,!1,void 0,this),M(S,{color:Y.syntax.comment,children:"# function"},void 0,!1,void 0,this),M(S,{children:[M(S,{color:Y.syntax.keyword,children:"def"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.function,children:"fibonacci"},void 0,!1,void 0,this),M(S,{color:Y.text.primary,children:"("},void 0,!1,void 0,this),M(S,{color:Y.syntax.variable,children:"n"},void 0,!1,void 0,this),M(S,{color:Y.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[" ",M(S,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this),M(S,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.operator,children:"="},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.number,children:"0"},void 0,!1,void 0,this),M(S,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.number,children:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[" ",M(S,{color:Y.syntax.keyword,children:"for"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"_"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.keyword,children:"in"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.function,children:"range"},void 0,!1,void 0,this),M(S,{color:Y.text.primary,children:"("},void 0,!1,void 0,this),M(S,{color:Y.syntax.variable,children:"n"},void 0,!1,void 0,this),M(S,{color:Y.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[" ",M(S,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this),M(S,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.operator,children:"="},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this),M(S,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.operator,children:"+"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[" ",M(S,{color:Y.syntax.keyword,children:"return"},void 0,!1,void 0,this)," ",M(S,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:" "},void 0,!1,void 0,this),M(S,{color:Y.error,children:["- print(",M(S,{color:Y.syntax.string,children:'"Hello, "'},void 0,!1,void 0,this)," + name)"]},void 0,!0,void 0,this),M(S,{color:Y.success,children:["+ print(",M(S,{color:Y.syntax.string,children:['f"Hello, ',"{","name","}",'"']},void 0,!0,void 0,this),")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},Iq=({theme:$})=>{let{colors:Y}=$;return M(A1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[M(S,{children:" "},void 0,!1,void 0,this),M(S,{bold:!0,color:Y.text.primary,children:"颜色配置"},void 0,!1,void 0,this),M(S,{children:" "},void 0,!1,void 0,this),M(S,{children:[M(S,{color:Y.text.muted,children:"Primary: "},void 0,!1,void 0,this),M(S,{color:Y.primary,children:Y.primary},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[M(S,{color:Y.text.muted,children:"Success: "},void 0,!1,void 0,this),M(S,{color:Y.success,children:Y.success},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[M(S,{color:Y.text.muted,children:"Error: "},void 0,!1,void 0,this),M(S,{color:Y.error,children:Y.error},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[M(S,{color:Y.text.muted,children:"Warning: "},void 0,!1,void 0,this),M(S,{color:Y.warning,children:Y.warning},void 0,!1,void 0,this)]},void 0,!0,void 0,this),M(S,{children:[M(S,{color:Y.text.muted,children:"Info: "},void 0,!1,void 0,this),M(S,{color:Y.info,children:Y.info},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},wY=()=>{let $=b$(),Y=$0.getCurrentThemeName(),Z=N1.findIndex((z)=>z.label===Y),X=Z>=0?N1[Z].theme:N1[0].theme,[Q,J]=BY(X),[G,q]=BY(!1),K=Aq(async(z)=>{if(G)return;q(!0);try{$0.setTheme(z.value),await e().setTheme(z.value),$.closeModal()}catch(F){console.error("❌ 主题切换失败:",F instanceof Error?F.message:F)}finally{q(!1)}}),W=(z)=>{let F=N1.find((L)=>L.id===z.value);if(F)J(F.theme)},U=l0()==="theme-selector",H=b0(!1);Rq((z,F)=>{if(F.ctrl&&z==="c"||F.meta&&z==="c"){H();return}if(F.escape&&!G)$.closeModal()},{isActive:U});let _=(z)=>{let{isSelected:F,label:L}=z,B=L===Y?"✓":" ";return M(S,{color:F?Q.colors.primary:Q.colors.text.primary,children:[B," ",L]},void 0,!0,void 0,this)};return M(A1,{flexDirection:"column",height:"100%",children:[M(A1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:M(S,{bold:!0,color:Q.colors.primary,children:"\uD83C\uDFA8 主题选择器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),M(A1,{flexDirection:"row",flexGrow:1,children:[M(A1,{width:"40%",borderStyle:"single",borderColor:Q.colors.border.light,paddingX:1,children:M(A1,{flexDirection:"column",children:[M(A1,{paddingTop:1,paddingBottom:1,children:M(S,{bold:!0,color:Q.colors.text.primary,children:["可用主题 (",NY.length,")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M(bq,{items:NY,initialIndex:Z>=0?Z:0,onSelect:K,onHighlight:W,itemComponent:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),M(A1,{width:"60%",flexDirection:"column",borderStyle:"single",borderColor:Q.colors.border.light,children:[M(Vq,{theme:Q},void 0,!1,void 0,this),M(Iq,{theme:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),M(A1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:M(S,{color:Q.colors.text.muted,children:G?"正在保存...":"Enter: 选择主题 | Esc: 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as N0,Fragment as kq}from"react/jsx-dev-runtime";var g0=Q0("UI"),LY=({debug:$,...Y})=>{if($)g0.debug("[Debug] BladeInterface props:",{permissionMode:Y.permissionMode,yolo:Y.yolo});let Z=A6(!1),X=A6(!1),Q=A6(!1),J=A6(null),G=z5(),q=B5(),K=i2(),W=L5(),O=w5(),U=b$(),H=R$(),_=D5(),z=V$(),F=C1(),{exit:L}=Dq(),w=G==="ready",B=G==="needsSetup",A=G==="idle",{confirmationState:V,confirmationHandler:E,handleResponse:R}=U3(),{executeCommand:N,handleAbort:I}=G3(Y.systemPrompt,Y.appendSystemPrompt,E,Y.maxTurns),{getPreviousCommand:C,getNextCommand:p,addToHistory:y}=K3(),v=O3("",0),i=p0(async()=>{let r=z,G0;if(r==="default")G0="autoEdit";else if(r==="autoEdit")G0="plan";else G0="default";try{await e().setPermissionMode(G0)}catch($1){g0.error("❌ 权限模式切换失败:",$1 instanceof Error?$1.message:$1)}}),P=p0(async(r)=>{try{await e().addModel({name:r.name,provider:r.provider,apiKey:r.apiKey,baseUrl:r.baseUrl,model:r.model}),U.setInitializationStatus("ready")}catch(G0){g0.error("❌ 初始化配置保存失败:",G0 instanceof Error?G0.message:G0),U.setInitializationStatus("ready")}}),U1=p0(()=>{if(K==="shortcuts")U.closeModal();else U.setActiveModal("shortcuts")}),{showSuggestions:X0,suggestions:_0,selectedSuggestionIndex:M1}=A3(v,N,C,p,y,I,F,i,U1,K==="shortcuts");Q$(()=>{if(v.value&&K==="shortcuts")U.closeModal()},[v.value,K,U]);let J$=p0(async()=>{try{if(typeof Y.resume==="string"&&Y.resume!=="true"){let G0=await z1.loadSession(Y.resume),$1=G0.map((b1,T$)=>({id:`restored-${Date.now()}-${T$}`,role:b1.role,content:typeof b1.content==="string"?b1.content:JSON.stringify(b1.content),timestamp:Date.now()-(G0.length-T$)*1000}));H.restoreSession(Y.resume,$1);return}let r=await z1.listSessions();if(r.length===0)g0.error("没有找到历史会话"),process.exit(1);U.showSessionSelector(r)}catch(r){g0.error("[BladeInterface] 加载会话失败:",r),process.exit(1)}});Q$(()=>{if(Z.current)return;if(!Y.resume)return;Z.current=!0,J$()},[Y.resume,J$]);let P$=p0(async(r)=>{let G0=V.details?.type;if(G0==="enterPlanMode"&&r.approved)try{await e().setPermissionMode("plan"),g0.debug("[BladeInterface] Entered Plan mode")}catch($1){g0.error("[BladeInterface] Failed to enter Plan mode:",$1)}if(G0==="exitPlanMode"&&r.approved)g0.debug("[BladeInterface] ExitPlanMode approved, Store auto-synced");R(r)}),b6=p0(()=>{H.addAssistantMessage("❌ 设置已取消"),H.addAssistantMessage("Blade 需要 API 配置才能正常工作。"),H.addAssistantMessage("您可以稍后运行 Blade 重新进入设置向导。"),process.exit(0)}),c=p0(()=>{U.closeModal()}),Y0=p0(async(r)=>{try{let G0=await z1.loadSession(r),$1=G0.map((b1,T$)=>({id:`restored-${Date.now()}-${T$}`,role:b1.role,content:typeof b1.content==="string"?b1.content:JSON.stringify(b1.content),timestamp:Date.now()-(G0.length-T$)*1000}));H.restoreSession(r,$1),U.closeModal()}catch(G0){g0.error("[BladeInterface] Failed to restore session:",G0),U.closeModal()}}),n=p0(()=>{if(Y.resume)L();else U.closeModal()}),C0=p0((r)=>{U.showModelEditWizard(r)}),m1=p0((r)=>{H.addAssistantMessage(`✅ 已更新模型配置: ${r.name}`),c()});Q$(()=>{if(B){_.setFocus("model-config-wizard");return}if(V.isVisible)_.setFocus("confirmation-prompt");else if(K==="sessionSelector")_.setFocus("session-selector");else if(K==="themeSelector")_.setFocus("theme-selector");else if(K==="modelSelector")_.setFocus("model-selector");else if(K==="modelAddWizard"||K==="modelEditWizard")_.setFocus("model-config-wizard");else if(K==="permissionsManager")_.setFocus("permissions-manager");else if(K==="agentsManager")_.setFocus("agents-manager");else if(K==="agentCreationWizard")_.setFocus("agent-creation-wizard");else if(K==="shortcuts")_.setFocus("main-input");else _.setFocus("main-input")},[B,V.isVisible,K,_.setFocus]),Q$(()=>{if(!w||Q.current)return;Q.current=!0,H.addAssistantMessage("请输入您的问题,我将为您提供帮助。")},[w,H.addAssistantMessage]),Q$(()=>{if(!q)return;if(J.current===q)return;if(J.current=q,G==="error")H.addAssistantMessage(`❌ 初始化失败: ${q}`);else H.addAssistantMessage(`❌ ${q}`),H.addAssistantMessage("请重新尝试设置,或检查文件权限")},[q,G,H.addAssistantMessage]);let L0=p0(async(r)=>{try{await N(r)}catch(G0){let $1=G0 instanceof Error?G0.message:"无法发送初始消息";H.addAssistantMessage(`❌ 初始消息发送失败:${$1}`)}});Q$(()=>{let r=Y.initialMessage?.trim();if(!r||X.current||!w||B)return;X.current=!0,y(r),L0(r)},[Y.initialMessage,w,B,N,y]);let R1=p0(async(r)=>{try{await e().setPermissionMode(r)}catch(G0){g0.error("❌ 权限模式初始化失败:",G0 instanceof Error?G0.message:G0)}});if(Q$(()=>{let r=Y.permissionMode;if($)g0.debug("[Debug] permissionMode from CLI:",r),g0.debug("[Debug] current permissionMode:",z);if(!r||r===z)return;R1(r)},[Y.permissionMode,z]),A)return null;if(B)return N0(v8,{mode:"setup",onComplete:P,onCancel:b6},void 0,!1,void 0,this);if($)g0.debug("[Debug] 渲染主界面,条件检查:",{confirmationVisible:V.isVisible,activeModal:K});let u0=K==="modelSelector",e0=O,d1=K==="modelAddWizard"?"add":K==="modelEditWizard"&&e0?"edit":null,V6=u0||Boolean(d1),kY=K==="agentsManager",MY=K==="agentCreationWizard",vY=e0?{name:e0.name,provider:e0.provider,baseUrl:e0.baseUrl,apiKey:e0.apiKey,model:e0.model}:void 0,yY=V.isVisible&&V.details?N0(x3,{details:V.details,onResponse:P$},void 0,!1,void 0,this):K==="themeSelector"?N0(wY,{},void 0,!1,void 0,this):K==="permissionsManager"?N0(_Y,{onClose:c},void 0,!1,void 0,this):K==="sessionSelector"?N0(zY,{sessions:W,onSelect:Y0,onCancel:n},void 0,!1,void 0,this):null;return N0(_2,{flexDirection:"column",width:"100%",height:"100%",children:yY??N0(kq,{children:[N0(GY,{},void 0,!1,void 0,this),N0(YY,{},void 0,!1,void 0,this),N0(n3,{input:v.value,cursorPosition:v.cursorPosition,onChange:v.setValue,onChangeCursorPosition:v.setCursorPosition},void 0,!1,void 0,this),u0&&N0(_2,{marginTop:1,paddingX:2,children:N0(KY,{onClose:c,onEdit:C0},void 0,!1,void 0,this)},void 0,!1,void 0,this),d1&&N0(_2,{marginTop:1,paddingX:2,children:N0(v8,{mode:d1,modelId:e0?.id,initialConfig:d1==="edit"?vY:void 0,onComplete:d1==="edit"?m1:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),kY&&N0(_2,{marginTop:1,paddingX:2,children:N0(I3,{onComplete:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),MY&&N0(_2,{marginTop:1,paddingX:2,children:N0(Q2,{onComplete:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),N0(v3,{suggestions:_0,selectedIndex:M1,visible:X0&&!V6},void 0,!1,void 0,this),N0(M3,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)};import{Box as Mq,Text as u1}from"ink";import vq from"react";import{jsxDEV as k1}from"react/jsx-dev-runtime";class y8 extends vq.Component{constructor($){super($);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError($){return{hasError:!0,error:$,errorInfo:null}}componentDidCatch($,Y){this.setState({error:$,errorInfo:Y}),console.error("未捕获的错误:",$,Y)}render(){if(this.state.hasError)return k1(Mq,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"red",children:[k1(u1,{color:"red",children:"\uD83D\uDCA5 应用发生错误"},void 0,!1,void 0,this),k1(u1,{children:" "},void 0,!1,void 0,this),k1(u1,{color:"red",children:this.state.error?.message},void 0,!1,void 0,this),k1(u1,{children:" "},void 0,!1,void 0,this),k1(u1,{color:"gray",children:"错误详情:"},void 0,!1,void 0,this),k1(u1,{color:"gray",children:this.state.error?.stack},void 0,!1,void 0,this),k1(u1,{children:" "},void 0,!1,void 0,this),k1(u1,{color:"yellow",children:"请重启应用或联系开发者"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return this.props.children}}function R6($){return($ instanceof Error?$.message:String($)).replace(/sk-[a-zA-Z0-9]{32,}/g,"sk-***").replace(/apiKey['":\s]+[a-zA-Z0-9-_]+/gi,"apiKey: ***").replace(/API_KEY['":\s=]+[a-zA-Z0-9-_]+/gi,"API_KEY=***")}import{jsxDEV as RY}from"react/jsx-dev-runtime";function AY($){if(s().config.actions.setConfig($),!$.models||$.models.length===0){if($.debug)console.log("[Debug] 未检测到模型配置,进入设置向导");Y1().setInitializationStatus("needsSetup");return}if($.debug)console.log("[Debug] 模型配置检查通过,准备就绪");Y1().setInitializationStatus("ready")}var bY=($)=>{let[Y,Z]=jq(!1),X=yq(async()=>{try{let J=await V0.getInstance().initialize(),G=B2(J,$);if(AY(G),G.debug)S0.setGlobalDebug(G.debug),console.error("[Debug] 全局 Logger 已启用 debug 模式"),console.error("[Debug] 运行时配置:",G);let q=G.theme;if(q&&$0.hasTheme(q)){if($0.setTheme(q),$.debug)console.log(`✓ 已加载主题: ${q}`)}try{let K=B0.loadFromStandardLocations();if($.debug&&K>0)console.log(`✓ 已加载 ${K} 个 subagents: ${B0.getAllNames().join(", ")}`)}catch(K){if($.debug)console.warn("⚠️ Subagents 加载失败:",R6(K))}try{if(Q1.getInstance().loadConfig(G.hooks||{}),$.debug&&G.hooks?.enabled)console.log("✓ Hooks 系统已启用")}catch(K){if($.debug)console.warn("⚠️ Hooks 初始化失败:",R6(K))}K5().then((K)=>{if(K)console.log(""),console.log(K),console.log("")}),Z(!0)}catch(Q){if($.debug)console.warn("⚠️ 配置初始化失败,使用默认配置:",R6(Q));let J=B2(G$,$);if(AY(J),J.debug)S0.setGlobalDebug(J.debug),console.error("[Debug] 全局 Logger 已启用 debug 模式(fallback)");Z(!0)}});if(Eq(()=>{X()},[]),!Y)return null;return RY(y8,{children:RY(LY,{...$},void 0,!1,void 0,this)},void 0,!1,void 0,this)};var DY=IY(process.argv),VY=DY.indexOf("--debug");if(VY!==-1){let $=DY[VY+1],Y=$&&!$.startsWith("-")?$:!0;S0.setGlobalDebug(Y)}async function Cq(){if(await Q5())return;let $=Tq(IY(process.argv)).scriptName(c1.scriptName).usage(c1.usage).version(c1.version).locale(c1.locale).showHelpOnFail(c1.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(c1.strict).parserConfiguration({"populate--":!0}).options(f8).middleware([r8,n8,a8]).command(Q9).command(o8).command(W5).command(s8).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((Y,Z,X)=>{if(Z)console.error("\uD83D\uDCA5 An error occurred:"),console.error(Z.message),console.error(`
|
|
1507
|
+
`]},void 0,!0,void 0,this),p0(LG,{items:U,onSelect:H,indicatorComponent:VG,itemComponent:DG},void 0,!1,void 0,this),p0(m1,{dimColor:!0,children:[`
|
|
1508
|
+
`,"共 ",O.length," 个历史会话"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)};import{useMemoizedFn as IG}from"ahooks";import{Box as A1,Text as P,useInput as kG}from"ink";import vG from"ink-select-input";import{useState as RY}from"react";import{jsxDEV as v}from"react/jsx-dev-runtime";var bY=B1.map(($)=>({label:$.label,value:$.id})),MG=({theme:$})=>{let{colors:Y}=$;return v(A1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[v(P,{bold:!0,color:Y.text.primary,children:"代码预览"},void 0,!1,void 0,this),v(P,{children:" "},void 0,!1,void 0,this),v(P,{color:Y.syntax.comment,children:"# function"},void 0,!1,void 0,this),v(P,{children:[v(P,{color:Y.syntax.keyword,children:"def"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.function,children:"fibonacci"},void 0,!1,void 0,this),v(P,{color:Y.text.primary,children:"("},void 0,!1,void 0,this),v(P,{color:Y.syntax.variable,children:"n"},void 0,!1,void 0,this),v(P,{color:Y.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[" ",v(P,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this),v(P,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.operator,children:"="},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.number,children:"0"},void 0,!1,void 0,this),v(P,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.number,children:"1"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[" ",v(P,{color:Y.syntax.keyword,children:"for"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"_"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.keyword,children:"in"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.function,children:"range"},void 0,!1,void 0,this),v(P,{color:Y.text.primary,children:"("},void 0,!1,void 0,this),v(P,{color:Y.syntax.variable,children:"n"},void 0,!1,void 0,this),v(P,{color:Y.text.primary,children:"):"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[" ",v(P,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this),v(P,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.operator,children:"="},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this),v(P,{color:Y.syntax.operator,children:","},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.operator,children:"+"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"b"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[" ",v(P,{color:Y.syntax.keyword,children:"return"},void 0,!1,void 0,this)," ",v(P,{color:Y.syntax.variable,children:"a"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:" "},void 0,!1,void 0,this),v(P,{color:Y.error,children:["- print(",v(P,{color:Y.syntax.string,children:'"Hello, "'},void 0,!1,void 0,this)," + name)"]},void 0,!0,void 0,this),v(P,{color:Y.success,children:["+ print(",v(P,{color:Y.syntax.string,children:['f"Hello, ',"{","name","}",'"']},void 0,!0,void 0,this),")"]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},yG=({theme:$})=>{let{colors:Y}=$;return v(A1,{flexDirection:"column",paddingLeft:1,paddingTop:1,children:[v(P,{children:" "},void 0,!1,void 0,this),v(P,{bold:!0,color:Y.text.primary,children:"颜色配置"},void 0,!1,void 0,this),v(P,{children:" "},void 0,!1,void 0,this),v(P,{children:[v(P,{color:Y.text.muted,children:"Primary: "},void 0,!1,void 0,this),v(P,{color:Y.primary,children:Y.primary},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[v(P,{color:Y.text.muted,children:"Success: "},void 0,!1,void 0,this),v(P,{color:Y.success,children:Y.success},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[v(P,{color:Y.text.muted,children:"Error: "},void 0,!1,void 0,this),v(P,{color:Y.error,children:Y.error},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[v(P,{color:Y.text.muted,children:"Warning: "},void 0,!1,void 0,this),v(P,{color:Y.warning,children:Y.warning},void 0,!1,void 0,this)]},void 0,!0,void 0,this),v(P,{children:[v(P,{color:Y.text.muted,children:"Info: "},void 0,!1,void 0,this),v(P,{color:Y.info,children:Y.info},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this)},VY=()=>{let $=D$(),Y=$0.getCurrentThemeName(),Z=B1.findIndex((z)=>z.label===Y),X=Z>=0?B1[Z].theme:B1[0].theme,[Q,J]=RY(X),[q,G]=RY(!1),K=IG(async(z)=>{if(q)return;G(!0);try{$0.setTheme(z.value),await e().setTheme(z.value),$.closeModal()}catch(F){console.error("❌ 主题切换失败:",F instanceof Error?F.message:F)}finally{G(!1)}}),W=(z)=>{let F=B1.find((w)=>w.id===z.value);if(F)J(F.theme)},U=i0()==="theme-selector",H=b0(!1);kG((z,F)=>{if(F.ctrl&&z==="c"||F.meta&&z==="c"){H();return}if(F.escape&&!q)$.closeModal()},{isActive:U});let _=(z)=>{let{isSelected:F,label:w}=z,N=w===Y?"✓":" ";return v(P,{color:F?Q.colors.primary:Q.colors.text.primary,children:[N," ",w]},void 0,!0,void 0,this)};return v(A1,{flexDirection:"column",height:"100%",children:[v(A1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:v(P,{bold:!0,color:Q.colors.primary,children:"\uD83C\uDFA8 主题选择器"},void 0,!1,void 0,this)},void 0,!1,void 0,this),v(A1,{flexDirection:"row",flexGrow:1,children:[v(A1,{width:"40%",borderStyle:"single",borderColor:Q.colors.border.light,paddingX:1,children:v(A1,{flexDirection:"column",children:[v(A1,{paddingTop:1,paddingBottom:1,children:v(P,{bold:!0,color:Q.colors.text.primary,children:["可用主题 (",bY.length,")"]},void 0,!0,void 0,this)},void 0,!1,void 0,this),v(vG,{items:bY,initialIndex:Z>=0?Z:0,onSelect:K,onHighlight:W,itemComponent:_},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this),v(A1,{width:"60%",flexDirection:"column",borderStyle:"single",borderColor:Q.colors.border.light,children:[v(MG,{theme:Q},void 0,!1,void 0,this),v(yG,{theme:Q},void 0,!1,void 0,this)]},void 0,!0,void 0,this)]},void 0,!0,void 0,this),v(A1,{paddingX:2,paddingY:1,borderStyle:"single",borderColor:Q.colors.border.light,children:v(P,{color:Q.colors.text.muted,children:q?"正在保存...":"Enter: 选择主题 | Esc: 取消"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)};import{jsxDEV as B0,Fragment as jG}from"react/jsx-dev-runtime";var m0=Y0("UI"),DY=({debug:$,...Y})=>{if($)m0.debug("[Debug] BladeInterface props:",{permissionMode:Y.permissionMode,yolo:Y.yolo});let Z=V6(!1),X=V6(!1),Q=V6(!1),J=V6(null),q=A5(),G=R5(),K=n2(),W=D5(),O=V5(),U=D$(),H=V$(),_=E5(),z=I$(),F=f1(),{exit:w}=EG(),L=q==="ready",N=q==="needsSetup",A=q==="idle",{confirmationState:V,confirmationHandler:E,handleResponse:R}=z3(),{executeCommand:B,handleAbort:D}=O3(Y.systemPrompt,Y.appendSystemPrompt,E,Y.maxTurns),{getPreviousCommand:C,getNextCommand:p,addToHistory:y}=_3(),M=N3("",0),i=g0(async()=>{let r=z,q0;if(r==="default")q0="autoEdit";else if(r==="autoEdit")q0="plan";else q0="default";try{await e().setPermissionMode(q0)}catch(Y1){m0.error("❌ 权限模式切换失败:",Y1 instanceof Error?Y1.message:Y1)}}),S=g0(async(r)=>{try{await e().addModel({name:r.name,provider:r.provider,apiKey:r.apiKey,baseUrl:r.baseUrl,model:r.model}),U.setInitializationStatus("ready")}catch(q0){m0.error("❌ 初始化配置保存失败:",q0 instanceof Error?q0.message:q0),U.setInitializationStatus("ready")}}),U1=g0(()=>{if(K==="shortcuts")U.closeModal();else U.setActiveModal("shortcuts")}),{showSuggestions:Q0,suggestions:_0,selectedSuggestionIndex:M1}=I3(M,B,C,p,y,D,F,i,U1,K==="shortcuts");J$(()=>{if(M.value&&K==="shortcuts")U.closeModal()},[M.value,K,U]);let q$=g0(async()=>{try{if(typeof Y.resume==="string"&&Y.resume!=="true"){let q0=await z1.loadSession(Y.resume),Y1=q0.map((b1,f$)=>({id:`restored-${Date.now()}-${f$}`,role:b1.role,content:typeof b1.content==="string"?b1.content:JSON.stringify(b1.content),timestamp:Date.now()-(q0.length-f$)*1000}));H.restoreSession(Y.resume,Y1);return}let r=await z1.listSessions();if(r.length===0)m0.error("没有找到历史会话"),process.exit(1);U.showSessionSelector(r)}catch(r){m0.error("[BladeInterface] 加载会话失败:",r),process.exit(1)}});J$(()=>{if(Z.current)return;if(!Y.resume)return;Z.current=!0,q$()},[Y.resume,q$]);let C$=g0(async(r)=>{let q0=V.details?.type;if(q0==="enterPlanMode"&&r.approved)try{await e().setPermissionMode("plan"),m0.debug("[BladeInterface] Entered Plan mode")}catch(Y1){m0.error("[BladeInterface] Failed to enter Plan mode:",Y1)}if(q0==="exitPlanMode"&&r.approved)m0.debug("[BladeInterface] ExitPlanMode approved, Store auto-synced");R(r)}),I6=g0(()=>{H.addAssistantMessage("❌ 设置已取消"),H.addAssistantMessage("Blade 需要 API 配置才能正常工作。"),H.addAssistantMessage("您可以稍后运行 Blade 重新进入设置向导。"),process.exit(0)}),c=g0(()=>{U.closeModal()}),Z0=g0(async(r)=>{try{let q0=await z1.loadSession(r),Y1=q0.map((b1,f$)=>({id:`restored-${Date.now()}-${f$}`,role:b1.role,content:typeof b1.content==="string"?b1.content:JSON.stringify(b1.content),timestamp:Date.now()-(q0.length-f$)*1000}));H.restoreSession(r,Y1),U.closeModal()}catch(q0){m0.error("[BladeInterface] Failed to restore session:",q0),U.closeModal()}}),a=g0(()=>{if(Y.resume)w();else U.closeModal()}),h0=g0((r)=>{U.showModelEditWizard(r)}),d1=g0((r)=>{H.addAssistantMessage(`✅ 已更新模型配置: ${r.name}`),c()});J$(()=>{if(N){_.setFocus("model-config-wizard");return}if(V.isVisible)_.setFocus("confirmation-prompt");else if(K==="sessionSelector")_.setFocus("session-selector");else if(K==="themeSelector")_.setFocus("theme-selector");else if(K==="modelSelector")_.setFocus("model-selector");else if(K==="modelAddWizard"||K==="modelEditWizard")_.setFocus("model-config-wizard");else if(K==="permissionsManager")_.setFocus("permissions-manager");else if(K==="agentsManager")_.setFocus("agents-manager");else if(K==="agentCreationWizard")_.setFocus("agent-creation-wizard");else if(K==="shortcuts")_.setFocus("main-input");else _.setFocus("main-input")},[N,V.isVisible,K,_.setFocus]),J$(()=>{if(!L||Q.current)return;Q.current=!0,H.addAssistantMessage("请输入您的问题,我将为您提供帮助。")},[L,H.addAssistantMessage]),J$(()=>{if(!G)return;if(J.current===G)return;if(J.current=G,q==="error")H.addAssistantMessage(`❌ 初始化失败: ${G}`);else H.addAssistantMessage(`❌ ${G}`),H.addAssistantMessage("请重新尝试设置,或检查文件权限")},[G,q,H.addAssistantMessage]);let w0=g0(async(r)=>{try{await B(r)}catch(q0){let Y1=q0 instanceof Error?q0.message:"无法发送初始消息";H.addAssistantMessage(`❌ 初始消息发送失败:${Y1}`)}});J$(()=>{let r=Y.initialMessage?.trim();if(!r||X.current||!L||N)return;X.current=!0,y(r),w0(r)},[Y.initialMessage,L,N,B,y]);let R1=g0(async(r)=>{try{await e().setPermissionMode(r)}catch(q0){m0.error("❌ 权限模式初始化失败:",q0 instanceof Error?q0.message:q0)}});if(J$(()=>{let r=Y.permissionMode;if($)m0.debug("[Debug] permissionMode from CLI:",r),m0.debug("[Debug] current permissionMode:",z);if(!r||r===z)return;R1(r)},[Y.permissionMode,z]),A)return null;if(N)return B0(j8,{mode:"setup",onComplete:S,onCancel:I6},void 0,!1,void 0,this);if($)m0.debug("[Debug] 渲染主界面,条件检查:",{confirmationVisible:V.isVisible,activeModal:K});let u0=K==="modelSelector",$1=O,c1=K==="modelAddWizard"?"add":K==="modelEditWizard"&&$1?"edit":null,k6=u0||Boolean(c1),jY=K==="agentsManager",PY=K==="agentCreationWizard",SY=$1?{name:$1.name,provider:$1.provider,baseUrl:$1.baseUrl,apiKey:$1.apiKey,model:$1.model}:void 0,TY=V.isVisible&&V.details?B0(d3,{details:V.details,onResponse:C$},void 0,!1,void 0,this):K==="themeSelector"?B0(VY,{},void 0,!1,void 0,this):K==="permissionsManager"?B0(LY,{onClose:c},void 0,!1,void 0,this):K==="sessionSelector"?B0(AY,{sessions:W,onSelect:Z0,onCancel:a},void 0,!1,void 0,this):null;return B0(z2,{flexDirection:"column",width:"100%",height:"100%",children:TY??B0(jG,{children:[B0(OY,{},void 0,!1,void 0,this),B0(qY,{},void 0,!1,void 0,this),B0(e3,{input:M.value,cursorPosition:M.cursorPosition,onChange:M.setValue,onChangeCursorPosition:M.setCursorPosition},void 0,!1,void 0,this),u0&&B0(z2,{marginTop:1,paddingX:2,children:B0(_Y,{onClose:c,onEdit:h0},void 0,!1,void 0,this)},void 0,!1,void 0,this),c1&&B0(z2,{marginTop:1,paddingX:2,children:B0(j8,{mode:c1,modelId:$1?.id,initialConfig:c1==="edit"?SY:void 0,onComplete:c1==="edit"?d1:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),jY&&B0(z2,{marginTop:1,paddingX:2,children:B0(y3,{onComplete:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),PY&&B0(z2,{marginTop:1,paddingX:2,children:B0(q2,{onComplete:c,onCancel:c},void 0,!1,void 0,this)},void 0,!1,void 0,this),B0(S3,{suggestions:_0,selectedIndex:M1,visible:Q0&&!k6},void 0,!1,void 0,this),B0(P3,{},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},void 0,!1,void 0,this)};import{Box as PG,Text as u1}from"ink";import SG from"react";import{jsxDEV as v1}from"react/jsx-dev-runtime";class P8 extends SG.Component{constructor($){super($);this.state={hasError:!1,error:null,errorInfo:null}}static getDerivedStateFromError($){return{hasError:!0,error:$,errorInfo:null}}componentDidCatch($,Y){this.setState({error:$,errorInfo:Y}),console.error("未捕获的错误:",$,Y)}render(){if(this.state.hasError)return v1(PG,{flexDirection:"column",padding:1,borderStyle:"round",borderColor:"red",children:[v1(u1,{color:"red",children:"\uD83D\uDCA5 应用发生错误"},void 0,!1,void 0,this),v1(u1,{children:" "},void 0,!1,void 0,this),v1(u1,{color:"red",children:this.state.error?.message},void 0,!1,void 0,this),v1(u1,{children:" "},void 0,!1,void 0,this),v1(u1,{color:"gray",children:"错误详情:"},void 0,!1,void 0,this),v1(u1,{color:"gray",children:this.state.error?.stack},void 0,!1,void 0,this),v1(u1,{children:" "},void 0,!1,void 0,this),v1(u1,{color:"yellow",children:"请重启应用或联系开发者"},void 0,!1,void 0,this)]},void 0,!0,void 0,this);return this.props.children}}function D6($){return($ instanceof Error?$.message:String($)).replace(/sk-[a-zA-Z0-9]{32,}/g,"sk-***").replace(/apiKey['":\s]+[a-zA-Z0-9-_]+/gi,"apiKey: ***").replace(/API_KEY['":\s=]+[a-zA-Z0-9-_]+/gi,"API_KEY=***")}import{jsxDEV as kY}from"react/jsx-dev-runtime";function IY($){if(s().config.actions.setConfig($),!$.models||$.models.length===0){if($.debug)console.log("[Debug] 未检测到模型配置,进入设置向导");Z1().setInitializationStatus("needsSetup");return}if($.debug)console.log("[Debug] 模型配置检查通过,准备就绪");Z1().setInitializationStatus("ready")}var vY=($)=>{let[Y,Z]=fG(!1),X=TG(async()=>{try{let J=await V0.getInstance().initialize(),q=L2(J,$);if(IY(q),q.debug)P0.setGlobalDebug(q.debug),console.error("[Debug] 全局 Logger 已启用 debug 模式"),console.error("[Debug] 运行时配置:",q);let G=q.theme;if(G&&$0.hasTheme(G)){if($0.setTheme(G),$.debug)console.log(`✓ 已加载主题: ${G}`)}try{let K=N0.loadFromStandardLocations();if($.debug&&K>0)console.log(`✓ 已加载 ${K} 个 subagents: ${N0.getAllNames().join(", ")}`)}catch(K){if($.debug)console.warn("⚠️ Subagents 加载失败:",D6(K))}try{if(l0.getInstance().loadConfig(q.hooks||{}),$.debug&&q.hooks?.enabled)console.log("✓ Hooks 系统已启用")}catch(K){if($.debug)console.warn("⚠️ Hooks 初始化失败:",D6(K))}O5().then((K)=>{if(K)console.log(""),console.log(K),console.log("")}),_5(async()=>{C0.getInstance().killAll(),await I0.getInstance().disconnectAll(),l0.getInstance().cleanup()}),Z(!0)}catch(Q){if($.debug)console.warn("⚠️ 配置初始化失败,使用默认配置:",D6(Q));let J=L2(G$,$);if(IY(J),J.debug)P0.setGlobalDebug(J.debug),console.error("[Debug] 全局 Logger 已启用 debug 模式(fallback)");Z(!0)}});if(CG(()=>{X()},[]),!Y)return null;return kY(P8,{children:kY(DY,{...$},void 0,!1,void 0,this)},void 0,!1,void 0,this)};var EY=yY(process.argv),MY=EY.indexOf("--debug");if(MY!==-1){let $=EY[MY+1],Y=$&&!$.startsWith("-")?$:!0;P0.setGlobalDebug(Y)}async function gG(){if(F5(),await G5())return;let $=pG(yY(process.argv)).scriptName(l1.scriptName).usage(l1.usage).version(l1.version).locale(l1.locale).showHelpOnFail(l1.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(l1.strict).parserConfiguration({"populate--":!0}).options(p8).middleware([o8,s8,t8]).command(G9).command(e8).command(H5).command($9).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((Y,Z,X)=>{if(Z)console.error("\uD83D\uDCA5 An error occurred:"),console.error(Z.message),console.error(`
|
|
1509
1509
|
Stack trace:`),console.error(Z.stack),process.exit(1);if(Y)console.error("❌ Invalid arguments:"),console.error(Y),console.error(`
|
|
1510
|
-
\uD83D\uDCA1 Did you mean:`),X.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(Y)=>{let Z=Y._.slice(1),X=Z.length>0?Z.join(" "):void 0,Q={...Y,initialMessage:X,debug:Y.debug,print:Boolean(Y.print)};delete Q._,delete Q.$0,delete Q.message,
|
|
1510
|
+
\uD83D\uDCA1 Did you mean:`),X.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(Y)=>{let Z=Y._.slice(1),X=Z.length>0?Z.join(" "):void 0,Q={...Y,initialMessage:X,debug:Y.debug,print:Boolean(Y.print)};delete Q._,delete Q.$0,delete Q.message,hG(xG.createElement(vY,Q),{patchConsole:!0,exitOnCtrlC:!1})});try{await $.parse()}catch(Y){console.error("❌ Parse error:",Y),process.exit(1)}}if(A0.main==A0.module)gG().catch(console.error);export{gG as main};
|