mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 22:28:10 +09:00
chore: publish v2.7.6 with correct build artifacts for stdio fix
This commit is contained in:
1 parent
7d5d999c13
commit
b02036744a
17 files changed
+878
-10803
No files matched your search
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"startTime": 1761341307662,
|
||||
"sessionId": "session-1761341307662",
|
||||
"lastActivity": 1761341307662,
|
||||
"startTime": 1761343100657,
|
||||
"sessionId": "session-1761343100657",
|
||||
"lastActivity": 1761343100657,
|
||||
"sessionDuration": 0,
|
||||
"totalTasks": 1,
|
||||
"successfulTasks": 1,
|
||||
|
||||
+401
-10421
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,10 @@
|
||||
[
|
||||
{
|
||||
"id": "cmd-hooks-1761341307760",
|
||||
"id": "cmd-hooks-1761343100758",
|
||||
"type": "hooks",
|
||||
"success": true,
|
||||
"duration": 12.237257999999997,
|
||||
"timestamp": 1761341307773,
|
||||
"duration": 8.819323999999995,
|
||||
"timestamp": 1761343100767,
|
||||
"metadata": {}
|
||||
}
|
||||
]
|
||||
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2.7.6] - 2025-10-24
|
||||
|
||||
> **🐛 Critical Bug Fix**: MCP Server Stdio Mode - Fixed stdout corruption in stdio mode (build artifacts)
|
||||
|
||||
### Changes
|
||||
- Republish with correct build artifacts for stdio mode fix
|
||||
|
||||
## [2.7.5] - 2025-10-24
|
||||
|
||||
> **🐛 Critical Bug Fix**: MCP Server Stdio Mode - Fixed stdout corruption in stdio mode
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
|
||||
|
||||
VERSION="2.7.4"
|
||||
VERSION="2.7.6"
|
||||
|
||||
# Determine the correct path based on how the script is invoked
|
||||
if [ -L "$0" ]; then
|
||||
|
||||
+173
-79
@@ -1,18 +1,47 @@
|
||||
#!/usr/bin/env -S deno run --allow-all
|
||||
import { promises as fs } from 'node:fs';
|
||||
#!/usr/bin/env node
|
||||
import { executeCommand, hasCommand, showCommandHelp, listCommands } from './command-registry.js';
|
||||
import { parseFlags } from './utils.js';
|
||||
import { args, cwd, isMainModule, exit, readTextFile, writeTextFile, mkdirAsync, errors } from './node-compat.js';
|
||||
import { spawn } from 'child_process';
|
||||
import process from 'process';
|
||||
import readline from 'readline';
|
||||
import { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';
|
||||
import { VERSION } from '../core/version.js';
|
||||
function printHelp() {
|
||||
const LEGACY_AGENT_MAPPING = {
|
||||
analyst: 'code-analyzer',
|
||||
coordinator: 'task-orchestrator',
|
||||
optimizer: 'perf-analyzer',
|
||||
documenter: 'api-docs',
|
||||
monitor: 'performance-benchmarker',
|
||||
specialist: 'system-architect',
|
||||
architect: 'system-architect'
|
||||
};
|
||||
function resolveLegacyAgentType(legacyType) {
|
||||
return LEGACY_AGENT_MAPPING[legacyType] || legacyType;
|
||||
}
|
||||
function printHelp(plain = false) {
|
||||
console.log(getMainHelp(plain));
|
||||
}
|
||||
function printCommandHelp(command) {
|
||||
const standardCommands = [
|
||||
'agent',
|
||||
'sparc',
|
||||
'memory'
|
||||
];
|
||||
if (standardCommands.includes(command)) {
|
||||
const help = getStandardizedCommandHelp(command);
|
||||
console.log(help);
|
||||
} else {
|
||||
const help = getCommandHelp(command);
|
||||
console.log(help);
|
||||
}
|
||||
}
|
||||
function printLegacyHelp() {
|
||||
console.log(`
|
||||
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
|
||||
|
||||
🎯 NEW IN v2.6.0: Multi-Provider Execution Engine with Agentic-Flow Integration
|
||||
• 66+ specialized agents with multi-provider support (Anthropic, OpenRouter, ONNX, Gemini)
|
||||
• 99% cost savings with OpenRouter, 352x faster local edits with Agent Booster
|
||||
• Complete backwards compatibility with existing features
|
||||
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure
|
||||
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure
|
||||
⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines
|
||||
|
||||
USAGE:
|
||||
claude-flow <command> [options]
|
||||
@@ -48,10 +77,9 @@ USAGE:
|
||||
init [--sparc] # Initialize with enterprise environment + ruv-swarm
|
||||
start [--ui] [--swarm] # Start orchestration with swarm intelligence
|
||||
spawn <type> [--name] # Create AI agent with swarm coordination
|
||||
agent <subcommand> # 🆕 Multi-provider agent execution + management
|
||||
agent <subcommand> # Advanced agent management with neural patterns
|
||||
sparc <subcommand> # 17 SPARC modes with neural enhancement
|
||||
memory <subcommand> # Cross-session persistent memory with neural learning
|
||||
config <subcommand> # 🆕 Provider configuration management
|
||||
status # Comprehensive system status with performance metrics
|
||||
|
||||
🤖 NEURAL AGENT TYPES (ruv-swarm Integration):
|
||||
@@ -66,25 +94,20 @@ USAGE:
|
||||
|
||||
🎮 ENTERPRISE QUICK START:
|
||||
# Initialize enterprise environment
|
||||
npx claude-flow@2.6.0-alpha.1 init --sparc
|
||||
|
||||
# 🆕 Execute agents with multi-provider support
|
||||
./claude-flow agent run coder "Build REST API with auth" --provider anthropic
|
||||
./claude-flow agent run researcher "Research React 19" --provider openrouter # 99% cost savings
|
||||
./claude-flow agent agents # List all 66+ available agents
|
||||
|
||||
npx claude-flow@2.0.0 init --sparc
|
||||
|
||||
# Start enterprise orchestration with swarm intelligence
|
||||
./claude-flow start --ui --swarm
|
||||
|
||||
|
||||
# Deploy intelligent multi-agent development workflow
|
||||
./claude-flow swarm "build enterprise API" --strategy development --parallel --monitor
|
||||
|
||||
|
||||
# GitHub workflow automation
|
||||
./claude-flow github pr-manager "coordinate release with automated testing"
|
||||
|
||||
|
||||
# Neural memory management
|
||||
./claude-flow memory store "architecture" "microservices with API gateway pattern"
|
||||
|
||||
|
||||
# Real-time system monitoring
|
||||
./claude-flow status --verbose
|
||||
|
||||
@@ -152,8 +175,8 @@ function printSuccess(message) {
|
||||
function printWarning(message) {
|
||||
console.warn(`⚠️ Warning: ${message}`);
|
||||
}
|
||||
function showHelpWithCommands() {
|
||||
printHelp();
|
||||
function showHelpWithCommands(plain = false) {
|
||||
printHelp(plain);
|
||||
console.log('\nRegistered Commands:');
|
||||
const commands = listCommands();
|
||||
for (const command of commands){
|
||||
@@ -162,14 +185,58 @@ function showHelpWithCommands() {
|
||||
console.log('\nUse "claude-flow help <command>" for detailed usage information');
|
||||
}
|
||||
async function main() {
|
||||
const args = Deno.args;
|
||||
if (args.length === 0) {
|
||||
printHelp();
|
||||
printHelp(usePlainHelp);
|
||||
return;
|
||||
}
|
||||
const command = args[0];
|
||||
const { flags, args: parsedArgs } = parseFlags(args.slice(1));
|
||||
const usePlainHelp = args.includes('--plain');
|
||||
let enhancedFlags = flags;
|
||||
try {
|
||||
const { detectExecutionEnvironment, applySmartDefaults } = await import('./utils/environment-detector.js');
|
||||
enhancedFlags = applySmartDefaults(flags);
|
||||
enhancedFlags._environment = detectExecutionEnvironment({
|
||||
skipWarnings: true
|
||||
});
|
||||
} catch (e) {
|
||||
enhancedFlags = flags;
|
||||
}
|
||||
if (command !== 'help' && command !== '--help' && command !== '-h' && (enhancedFlags.help || enhancedFlags.h)) {
|
||||
const detailedHelp = getCommandHelp(command);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(command);
|
||||
} else if (hasCommand(command)) {
|
||||
showCommandHelp(command);
|
||||
} else {
|
||||
printError(`Unknown command: ${command}`);
|
||||
console.log('\nRun "claude-flow --help" to see available commands.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
switch(command){
|
||||
case 'env-check':
|
||||
case 'environment':
|
||||
if (enhancedFlags._environment) {
|
||||
const env = enhancedFlags._environment;
|
||||
console.log(`\n🖥️ Environment Detection Results:`);
|
||||
console.log(` Terminal: ${env.terminalType}`);
|
||||
console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);
|
||||
console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);
|
||||
console.log(` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`);
|
||||
if (env.recommendedFlags.length > 0) {
|
||||
console.log(`\n💡 Recommended flags:`);
|
||||
console.log(` ${env.recommendedFlags.join(' ')}`);
|
||||
}
|
||||
if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {
|
||||
console.log(`\n✅ Auto-applied:`);
|
||||
console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);
|
||||
}
|
||||
console.log();
|
||||
} else {
|
||||
console.log('Environment detection not available');
|
||||
}
|
||||
return;
|
||||
case 'version':
|
||||
case '--version':
|
||||
case '-v':
|
||||
@@ -179,9 +246,14 @@ async function main() {
|
||||
case '--help':
|
||||
case '-h':
|
||||
if (parsedArgs.length > 0) {
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
const detailedHelp = getCommandHelp(parsedArgs[0]);
|
||||
if (detailedHelp && !detailedHelp.includes('Help not available')) {
|
||||
printCommandHelp(parsedArgs[0]);
|
||||
} else {
|
||||
showCommandHelp(parsedArgs[0]);
|
||||
}
|
||||
} else {
|
||||
showHelpWithCommands();
|
||||
printHelp(usePlainHelp);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -191,6 +263,7 @@ async function main() {
|
||||
return;
|
||||
} catch (err) {
|
||||
printError(err.message);
|
||||
console.log(`\nRun "claude-flow ${command} --help" for usage information.`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -210,11 +283,12 @@ async function main() {
|
||||
console.log('📊 Real-time monitoring would display here');
|
||||
break;
|
||||
case 'spawn':
|
||||
const spawnType = subArgs[0] || 'general';
|
||||
const rawSpawnType = subArgs[0] || 'general';
|
||||
const spawnType = resolveLegacyAgentType(rawSpawnType);
|
||||
const spawnName = flags.name || `agent-${Date.now()}`;
|
||||
printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);
|
||||
console.log('🤖 Agent would be created with the following configuration:');
|
||||
console.log(` Type: ${spawnType}`);
|
||||
console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);
|
||||
console.log(` Name: ${spawnName}`);
|
||||
console.log(' Capabilities: Research, Analysis, Code Generation');
|
||||
console.log(' Status: Ready');
|
||||
@@ -239,7 +313,7 @@ async function main() {
|
||||
console.log(' • Max Pool Size: 10');
|
||||
console.log(' • Idle Timeout: 5 minutes');
|
||||
console.log(' • Shell: /bin/bash');
|
||||
console.log(' • Working Directory: ' + process.cwd());
|
||||
console.log(' • Working Directory: ' + cwd());
|
||||
console.log(' Performance:');
|
||||
console.log(' • Average Response Time: N/A');
|
||||
console.log(' • Terminal Creation Time: N/A');
|
||||
@@ -288,7 +362,7 @@ async function main() {
|
||||
const terminalConfig = {
|
||||
name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),
|
||||
shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),
|
||||
workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),
|
||||
env: envIndex >= 0 ? subArgs[envIndex + 1] : '',
|
||||
persistent: persistentIndex >= 0
|
||||
};
|
||||
@@ -1245,10 +1319,9 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('Debug - Executing command:');
|
||||
console.log(`claude ${claudeArgs.map((arg)=>arg.includes(' ') || arg.includes('\n') ? `"${arg}"` : arg).join(' ')}`);
|
||||
}
|
||||
const command = new Deno.Command('claude', {
|
||||
args: claudeArgs,
|
||||
const child = spawn('claude', claudeArgs, {
|
||||
env: {
|
||||
...Deno.env.toObject(),
|
||||
...process.env,
|
||||
CLAUDE_INSTANCE_ID: instanceId,
|
||||
CLAUDE_FLOW_MODE: flags1.mode || 'full',
|
||||
CLAUDE_FLOW_COVERAGE: (flags1.coverage || 80).toString(),
|
||||
@@ -1258,17 +1331,18 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
CLAUDE_FLOW_COORDINATION_ENABLED: flags1.parallel ? 'true' : 'false',
|
||||
CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm'
|
||||
},
|
||||
stdin: 'inherit',
|
||||
stdout: 'inherit',
|
||||
stderr: 'inherit'
|
||||
stdio: 'inherit'
|
||||
});
|
||||
await new Promise((resolve)=>{
|
||||
child.on('exit', (code)=>{
|
||||
if (code === 0) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${code}`);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const child = command.spawn();
|
||||
const status = await child.status;
|
||||
if (status.success) {
|
||||
printSuccess(`Claude instance ${instanceId} completed successfully`);
|
||||
} else {
|
||||
printError(`Claude instance ${instanceId} exited with code ${status.code}`);
|
||||
}
|
||||
} catch (err) {
|
||||
printError(`Failed to spawn Claude: ${err.message}`);
|
||||
console.log('Make sure you have the Claude CLI installed.');
|
||||
@@ -1821,7 +1895,7 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
|
||||
console.log('\nDid you mean:');
|
||||
suggestions.forEach((cmd)=>console.log(` claude-flow ${cmd}`));
|
||||
}
|
||||
process.exit(1);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
async function startRepl() {
|
||||
@@ -1899,7 +1973,7 @@ Shortcuts:
|
||||
},
|
||||
config: async (key)=>{
|
||||
try {
|
||||
const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));
|
||||
const config = JSON.parse(await readTextFile('claude-flow.config.json'));
|
||||
if (key) {
|
||||
const keys = key.split('.');
|
||||
let value = config;
|
||||
@@ -1927,21 +2001,25 @@ Shortcuts:
|
||||
if (trimmed.startsWith('!')) {
|
||||
const shellCmd = trimmed.substring(1);
|
||||
try {
|
||||
const command = new Deno.Command('sh', {
|
||||
args: [
|
||||
await new Promise((resolve)=>{
|
||||
const proc = spawn('sh', [
|
||||
'-c',
|
||||
shellCmd
|
||||
],
|
||||
stdout: 'piped',
|
||||
stderr: 'piped'
|
||||
], {
|
||||
stdio: [
|
||||
'inherit',
|
||||
'pipe',
|
||||
'pipe'
|
||||
]
|
||||
});
|
||||
proc.stdout.on('data', (data)=>{
|
||||
console.log(data.toString());
|
||||
});
|
||||
proc.stderr.on('data', (data)=>{
|
||||
console.error(data.toString());
|
||||
});
|
||||
proc.on('exit', resolve);
|
||||
});
|
||||
const { stdout, stderr } = await command.output();
|
||||
if (stdout.length > 0) {
|
||||
console.log(new TextDecoder().decode(stdout));
|
||||
}
|
||||
if (stderr.length > 0) {
|
||||
console.error(new TextDecoder().decode(stderr));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Shell error: ${err.message}`);
|
||||
}
|
||||
@@ -1961,7 +2039,7 @@ Shortcuts:
|
||||
const parts = trimmed.split(' ');
|
||||
const command = parts[0];
|
||||
const args = parts.slice(1);
|
||||
if (command in replCommands) {
|
||||
if (replCommands[command]) {
|
||||
await replCommands[command](...args);
|
||||
return true;
|
||||
}
|
||||
@@ -1982,7 +2060,8 @@ Shortcuts:
|
||||
const subCmd = args[0];
|
||||
switch(subCmd){
|
||||
case 'spawn':
|
||||
const type = args[1] || 'researcher';
|
||||
const rawType = args[1] || 'researcher';
|
||||
const type = resolveLegacyAgentType(rawType);
|
||||
const name = args[2] || `agent-${Date.now()}`;
|
||||
const agent = {
|
||||
id: `agent-${Date.now()}`,
|
||||
@@ -2187,18 +2266,33 @@ Shortcuts:
|
||||
console.log('Terminal commands: create, list, exec, attach, detach');
|
||||
}
|
||||
}
|
||||
const decoder = new TextDecoder();
|
||||
const encoder = new TextEncoder();
|
||||
while(true){
|
||||
const prompt = replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ';
|
||||
await Deno.stdout.write(encoder.encode(prompt));
|
||||
const buf = new Uint8Array(1024);
|
||||
const n = await Deno.stdin.read(buf);
|
||||
if (n === null) break;
|
||||
const input = decoder.decode(buf.subarray(0, n)).trim();
|
||||
const shouldContinue = await processReplCommand(input);
|
||||
if (!shouldContinue) break;
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout
|
||||
});
|
||||
function updatePrompt() {
|
||||
rl.setPrompt(replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ');
|
||||
}
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
rl.on('line', async (input)=>{
|
||||
input = input.trim();
|
||||
const shouldContinue = await processReplCommand(input);
|
||||
if (!shouldContinue) {
|
||||
rl.close();
|
||||
} else {
|
||||
updatePrompt();
|
||||
rl.prompt();
|
||||
}
|
||||
});
|
||||
rl.on('SIGINT', ()=>{
|
||||
console.log('\nExiting Claude-Flow...');
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
});
|
||||
return new Promise((resolve)=>{
|
||||
rl.on('close', resolve);
|
||||
});
|
||||
}
|
||||
function createMinimalClaudeMd() {
|
||||
return `# Claude Code Integration
|
||||
@@ -2515,30 +2609,30 @@ async function createSparcStructureManually() {
|
||||
];
|
||||
for (const dir of rooDirectories){
|
||||
try {
|
||||
await Deno.mkdir(dir, {
|
||||
await mkdirAsync(dir, {
|
||||
recursive: true
|
||||
});
|
||||
console.log(` ✓ Created ${dir}/`);
|
||||
} catch (err) {
|
||||
if (!(err instanceof Deno.errors.AlreadyExists)) {
|
||||
if (!(err instanceof errors.AlreadyExists)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
let roomodesContent;
|
||||
try {
|
||||
roomodesContent = await fs.readFile('.roomodes');
|
||||
roomodesContent = await readTextFile('.roomodes');
|
||||
console.log(' ✓ Using existing .roomodes configuration');
|
||||
} catch {
|
||||
roomodesContent = createBasicRoomodesConfig();
|
||||
await fs.writeFile('.roomodes', roomodesContent);
|
||||
await writeTextFile('.roomodes', roomodesContent);
|
||||
console.log(' ✓ Created .roomodes configuration');
|
||||
}
|
||||
const basicWorkflow = createBasicSparcWorkflow();
|
||||
await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);
|
||||
console.log(' ✓ Created .roo/workflows/basic-tdd.json');
|
||||
const rooReadme = createRooReadme();
|
||||
await fs.writeFile('.roo/README.md', rooReadme);
|
||||
await writeTextFile('.roo/README.md', rooReadme);
|
||||
console.log(' ✓ Created .roo/README.md');
|
||||
console.log(' ✅ Basic SPARC structure created successfully');
|
||||
} catch (err) {
|
||||
@@ -2969,7 +3063,7 @@ This SPARC-enabled project follows a systematic development approach:
|
||||
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
|
||||
`;
|
||||
}
|
||||
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||
if (isMainModule(import.meta.url)) {
|
||||
await main();
|
||||
}
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.ts"],"sourcesContent":["#!/usr/bin/env -S deno run --allow-all\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport { promises as fs } from 'node:fs';\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport { VERSION } from '../core/version.js';\n\nfunction printHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 NEW IN v2.6.0: Multi-Provider Execution Engine with Agentic-Flow Integration\n • 66+ specialized agents with multi-provider support (Anthropic, OpenRouter, ONNX, Gemini)\n • 99% cost savings with OpenRouter, 352x faster local edits with Agent Booster\n • Complete backwards compatibility with existing features\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # 🆕 Multi-provider agent execution + management\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n config <subcommand> # 🆕 Provider configuration management\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.6.0-alpha.1 init --sparc\n\n # 🆕 Execute agents with multi-provider support\n ./claude-flow agent run coder \"Build REST API with auth\" --provider anthropic\n ./claude-flow agent run researcher \"Research React 19\" --provider openrouter # 99% cost savings\n ./claude-flow agent agents # List all 66+ available agents\n\n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n\n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n\n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n\n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n\n # Real-time system monitoring\n ./claude-flow status --verbose\n\n🏢 ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n DevelLine truncated
|
||||
{"version":3,"sources":["../../../src/cli/simple-cli.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport {\n args,\n cwd,\n isMainModule,\n exit,\n readTextFile,\n writeTextFile,\n mkdirAsync,\n errors,\n} from './node-compat.js';\nimport { spawn } from 'child_process';\nimport process from 'process';\nimport readline from 'readline';\nimport { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';\nimport { VERSION } from '../core/version.js';\n\n// Legacy agent type mapping for backward compatibility\nconst LEGACY_AGENT_MAPPING = {\n analyst: 'code-analyzer',\n coordinator: 'task-orchestrator', \n optimizer: 'perf-analyzer',\n documenter: 'api-docs',\n monitor: 'performance-benchmarker',\n specialist: 'system-architect',\n architect: 'system-architect',\n};\n\n// Resolve legacy agent types to current equivalents\nfunction resolveLegacyAgentType(legacyType) {\n return LEGACY_AGENT_MAPPING[legacyType] || legacyType;\n}\n\nfunction printHelp(plain = false) {\n console.log(getMainHelp(plain));\n}\n\nfunction printCommandHelp(command) {\n // Try standardized help first\n const standardCommands = ['agent', 'sparc', 'memory'];\n if (standardCommands.includes(command)) {\n const help = getStandardizedCommandHelp(command);\n console.log(help);\n } else {\n const help = getCommandHelp(command);\n console.log(help);\n }\n}\n\n// Legacy help function for backward compatibility\nfunction printLegacyHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure\n⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx claude-flow@2.0.0 init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx claude-flow@2.0.0 init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start Line truncated
|
||||
@@ -1,4 +1,9 @@
|
||||
import { printSuccess } from '../utils.js';
|
||||
import { printSuccess, printError, printWarning } from '../utils.js';
|
||||
let isStdioMode = false;
|
||||
const log = (...args)=>isStdioMode ? console.error(...args) : console.log(...args);
|
||||
const success = (msg)=>isStdioMode ? console.error(`✅ ${msg}`) : printSuccess(msg);
|
||||
const error = (msg)=>isStdioMode ? console.error(`❌ ${msg}`) : printError(msg);
|
||||
const warning = (msg)=>isStdioMode ? console.error(`⚠️ ${msg}`) : printWarning(msg);
|
||||
export async function mcpCommand(subArgs, flags) {
|
||||
const mcpCmd = subArgs[0];
|
||||
switch(mcpCmd){
|
||||
@@ -25,25 +30,26 @@ export async function mcpCommand(subArgs, flags) {
|
||||
}
|
||||
}
|
||||
async function showMcpStatus(subArgs, flags) {
|
||||
printSuccess('MCP Server Status:');
|
||||
console.log('🌐 Status: Stopped (orchestrator not running)');
|
||||
console.log('🔧 Configuration: Default settings');
|
||||
console.log('🔌 Connections: 0 active');
|
||||
console.log('📡 Tools: Ready to load');
|
||||
console.log('🔐 Authentication: Not configured');
|
||||
success('MCP Server Status:');
|
||||
log('🌐 Status: Stopped (orchestrator not running)');
|
||||
log('🔧 Configuration: Default settings');
|
||||
log('🔌 Connections: 0 active');
|
||||
log('📡 Tools: Ready to load');
|
||||
log('🔐 Authentication: Not configured');
|
||||
}
|
||||
async function startMcpServer(subArgs, flags) {
|
||||
const autoOrchestrator = subArgs.includes('--auto-orchestrator') || flags.autoOrchestrator;
|
||||
const daemon = subArgs.includes('--daemon') || flags.daemon;
|
||||
const stdio = subArgs.includes('--stdio') || flags.stdio || true;
|
||||
isStdioMode = stdio;
|
||||
if (stdio) {
|
||||
printSuccess('Starting Claude Flow MCP server in stdio mode...');
|
||||
success('Starting Claude Flow MCP server in stdio mode...');
|
||||
if (autoOrchestrator) {
|
||||
console.log('🚀 Auto-starting orchestrator...');
|
||||
console.log('🧠 Neural network capabilities: ENABLED');
|
||||
console.log('🔧 WASM SIMD optimization: ACTIVE');
|
||||
console.log('📊 Performance monitoring: ENABLED');
|
||||
console.log('🐝 Swarm coordination: READY');
|
||||
log('🚀 Auto-starting orchestrator...');
|
||||
log('🧠 Neural network capabilities: ENABLED');
|
||||
log('🔧 WASM SIMD optimization: ACTIVE');
|
||||
log('📊 Performance monitoring: ENABLED');
|
||||
log('🐝 Swarm coordination: READY');
|
||||
}
|
||||
try {
|
||||
const { fileURLToPath } = await import('url');
|
||||
@@ -54,9 +60,9 @@ async function startMcpServer(subArgs, flags) {
|
||||
const mcpServerPath = path.join(__dirname, '../../mcp/mcp-server.js');
|
||||
const fs = await import('fs');
|
||||
if (!fs.existsSync(mcpServerPath)) {
|
||||
console.error(`MCP server file not found at: ${mcpServerPath}`);
|
||||
console.error(`Current directory: ${process.cwd()}`);
|
||||
console.error(`Script directory: ${__dirname}`);
|
||||
error(`MCP server file not found at: ${mcpServerPath}`);
|
||||
error(`Current directory: ${process.cwd()}`);
|
||||
error(`Script directory: ${__dirname}`);
|
||||
throw new Error(`MCP server file not found: ${mcpServerPath}`);
|
||||
}
|
||||
const serverProcess = spawn('node', [
|
||||
@@ -72,288 +78,288 @@ async function startMcpServer(subArgs, flags) {
|
||||
});
|
||||
serverProcess.on('exit', (code)=>{
|
||||
if (code !== 0) {
|
||||
console.error(`MCP server exited with code ${code}`);
|
||||
error(`MCP server exited with code ${code}`);
|
||||
}
|
||||
});
|
||||
await new Promise(()=>{});
|
||||
} catch (error) {
|
||||
console.error('Failed to start MCP server:', error.message);
|
||||
console.log('🚀 MCP server would start with:');
|
||||
console.log(' Protocol: stdio');
|
||||
console.log(' Tools: 87 Claude-Flow integration tools');
|
||||
console.log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));
|
||||
console.log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));
|
||||
} catch (err) {
|
||||
error('Failed to start MCP server: ' + err.message);
|
||||
log('🚀 MCP server would start with:');
|
||||
log(' Protocol: stdio');
|
||||
log(' Tools: 87 Claude-Flow integration tools');
|
||||
log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));
|
||||
log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));
|
||||
}
|
||||
} else {
|
||||
const port = getFlag(subArgs, '--port') || flags.port || 3000;
|
||||
const host = getFlag(subArgs, '--host') || flags.host || 'localhost';
|
||||
printSuccess(`Starting Claude Flow MCP server on ${host}:${port}...`);
|
||||
console.log('🚀 HTTP mode not yet implemented, use --stdio for full functionality');
|
||||
success(`Starting Claude Flow MCP server on ${host}:${port}...`);
|
||||
log('🚀 HTTP mode not yet implemented, use --stdio for full functionality');
|
||||
}
|
||||
}
|
||||
async function stopMcpServer(subArgs, flags) {
|
||||
printSuccess('Stopping MCP server...');
|
||||
console.log('🛑 Server would be gracefully shut down');
|
||||
console.log('📝 Active connections would be closed');
|
||||
console.log('💾 State would be persisted');
|
||||
success('Stopping MCP server...');
|
||||
log('🛑 Server would be gracefully shut down');
|
||||
log('📝 Active connections would be closed');
|
||||
log('💾 State would be persisted');
|
||||
}
|
||||
async function listMcpTools(subArgs, flags) {
|
||||
const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;
|
||||
const category = getFlag(subArgs, '--category') || flags.category;
|
||||
printSuccess('Claude-Flow MCP Tools & Resources (87 total):');
|
||||
success('Claude-Flow MCP Tools & Resources (87 total):');
|
||||
if (!category || category === 'swarm') {
|
||||
console.log('\n🐝 SWARM COORDINATION (12 tools):');
|
||||
console.log(' • swarm_init Initialize swarm with topology');
|
||||
console.log(' • agent_spawn Create specialized AI agents');
|
||||
console.log(' • task_orchestrate Orchestrate complex workflows');
|
||||
console.log(' • swarm_status Monitor swarm health/performance');
|
||||
console.log(' • agent_list List active agents & capabilities');
|
||||
console.log(' • agent_metrics Agent performance metrics');
|
||||
console.log(' • swarm_monitor Real-time swarm monitoring');
|
||||
console.log(' • topology_optimize Auto-optimize swarm topology');
|
||||
console.log(' • load_balance Distribute tasks efficiently');
|
||||
console.log(' • coordination_sync Sync agent coordination');
|
||||
console.log(' • swarm_scale Auto-scale agent count');
|
||||
console.log(' • swarm_destroy Gracefully shutdown swarm');
|
||||
log('\n🐝 SWARM COORDINATION (12 tools):');
|
||||
log(' • swarm_init Initialize swarm with topology');
|
||||
log(' • agent_spawn Create specialized AI agents');
|
||||
log(' • task_orchestrate Orchestrate complex workflows');
|
||||
log(' • swarm_status Monitor swarm health/performance');
|
||||
log(' • agent_list List active agents & capabilities');
|
||||
log(' • agent_metrics Agent performance metrics');
|
||||
log(' • swarm_monitor Real-time swarm monitoring');
|
||||
log(' • topology_optimize Auto-optimize swarm topology');
|
||||
log(' • load_balance Distribute tasks efficiently');
|
||||
log(' • coordination_sync Sync agent coordination');
|
||||
log(' • swarm_scale Auto-scale agent count');
|
||||
log(' • swarm_destroy Gracefully shutdown swarm');
|
||||
}
|
||||
if (!category || category === 'neural') {
|
||||
console.log('\n🧠 NEURAL NETWORKS & AI (15 tools):');
|
||||
console.log(' • neural_status Check neural network status');
|
||||
console.log(' • neural_train Train neural patterns');
|
||||
console.log(' • neural_patterns Analyze cognitive patterns');
|
||||
console.log(' • neural_predict Make AI predictions');
|
||||
console.log(' • model_load Load pre-trained models');
|
||||
console.log(' • model_save Save trained models');
|
||||
console.log(' • wasm_optimize WASM SIMD optimization');
|
||||
console.log(' • inference_run Run neural inference');
|
||||
console.log(' • pattern_recognize Pattern recognition');
|
||||
console.log(' • cognitive_analyze Cognitive behavior analysis');
|
||||
console.log(' • learning_adapt Adaptive learning');
|
||||
console.log(' • neural_compress Compress neural models');
|
||||
console.log(' • ensemble_create Create model ensembles');
|
||||
console.log(' • transfer_learn Transfer learning');
|
||||
console.log(' • neural_explain AI explainability');
|
||||
log('\n🧠 NEURAL NETWORKS & AI (15 tools):');
|
||||
log(' • neural_status Check neural network status');
|
||||
log(' • neural_train Train neural patterns');
|
||||
log(' • neural_patterns Analyze cognitive patterns');
|
||||
log(' • neural_predict Make AI predictions');
|
||||
log(' • model_load Load pre-trained models');
|
||||
log(' • model_save Save trained models');
|
||||
log(' • wasm_optimize WASM SIMD optimization');
|
||||
log(' • inference_run Run neural inference');
|
||||
log(' • pattern_recognize Pattern recognition');
|
||||
log(' • cognitive_analyze Cognitive behavior analysis');
|
||||
log(' • learning_adapt Adaptive learning');
|
||||
log(' • neural_compress Compress neural models');
|
||||
log(' • ensemble_create Create model ensembles');
|
||||
log(' • transfer_learn Transfer learning');
|
||||
log(' • neural_explain AI explainability');
|
||||
}
|
||||
if (!category || category === 'memory') {
|
||||
console.log('\n💾 MEMORY & PERSISTENCE (12 tools):');
|
||||
console.log(' • memory_usage Store/retrieve persistent data');
|
||||
console.log(' • memory_search Search memory with patterns');
|
||||
console.log(' • memory_persist Cross-session persistence');
|
||||
console.log(' • memory_namespace Namespace management');
|
||||
console.log(' • memory_backup Backup memory stores');
|
||||
console.log(' • memory_restore Restore from backups');
|
||||
console.log(' • memory_compress Compress memory data');
|
||||
console.log(' • memory_sync Sync across instances');
|
||||
console.log(' • cache_manage Manage coordination cache');
|
||||
console.log(' • state_snapshot Create state snapshots');
|
||||
console.log(' • context_restore Restore execution context');
|
||||
console.log(' • memory_analytics Analyze memory usage');
|
||||
log('\n💾 MEMORY & PERSISTENCE (12 tools):');
|
||||
log(' • memory_usage Store/retrieve persistent data');
|
||||
log(' • memory_search Search memory with patterns');
|
||||
log(' • memory_persist Cross-session persistence');
|
||||
log(' • memory_namespace Namespace management');
|
||||
log(' • memory_backup Backup memory stores');
|
||||
log(' • memory_restore Restore from backups');
|
||||
log(' • memory_compress Compress memory data');
|
||||
log(' • memory_sync Sync across instances');
|
||||
log(' • cache_manage Manage coordination cache');
|
||||
log(' • state_snapshot Create state snapshots');
|
||||
log(' • context_restore Restore execution context');
|
||||
log(' • memory_analytics Analyze memory usage');
|
||||
}
|
||||
if (!category || category === 'analysis') {
|
||||
console.log('\n📊 ANALYSIS & MONITORING (13 tools):');
|
||||
console.log(' • task_status Check task execution status');
|
||||
console.log(' • task_results Get task completion results');
|
||||
console.log(' • benchmark_run Performance benchmarks');
|
||||
console.log(' • bottleneck_analyze Identify bottlenecks');
|
||||
console.log(' • performance_report Generate performance reports');
|
||||
console.log(' • token_usage Analyze token consumption');
|
||||
console.log(' • metrics_collect Collect system metrics');
|
||||
console.log(' • trend_analysis Analyze performance trends');
|
||||
console.log(' • cost_analysis Cost and resource analysis');
|
||||
console.log(' • quality_assess Quality assessment');
|
||||
console.log(' • error_analysis Error pattern analysis');
|
||||
console.log(' • usage_stats Usage statistics');
|
||||
console.log(' • health_check System health monitoring');
|
||||
log('\n📊 ANALYSIS & MONITORING (13 tools):');
|
||||
log(' • task_status Check task execution status');
|
||||
log(' • task_results Get task completion results');
|
||||
log(' • benchmark_run Performance benchmarks');
|
||||
log(' • bottleneck_analyze Identify bottlenecks');
|
||||
log(' • performance_report Generate performance reports');
|
||||
log(' • token_usage Analyze token consumption');
|
||||
log(' • metrics_collect Collect system metrics');
|
||||
log(' • trend_analysis Analyze performance trends');
|
||||
log(' • cost_analysis Cost and resource analysis');
|
||||
log(' • quality_assess Quality assessment');
|
||||
log(' • error_analysis Error pattern analysis');
|
||||
log(' • usage_stats Usage statistics');
|
||||
log(' • health_check System health monitoring');
|
||||
}
|
||||
if (!category || category === 'workflow') {
|
||||
console.log('\n🔧 WORKFLOW & AUTOMATION (11 tools):');
|
||||
console.log(' • workflow_create Create custom workflows');
|
||||
console.log(' • workflow_execute Execute predefined workflows');
|
||||
console.log(' • workflow_export Export workflow definitions');
|
||||
console.log(' • sparc_mode Run SPARC development modes');
|
||||
console.log(' • automation_setup Setup automation rules');
|
||||
console.log(' • pipeline_create Create CI/CD pipelines');
|
||||
console.log(' • scheduler_manage Manage task scheduling');
|
||||
console.log(' • trigger_setup Setup event triggers');
|
||||
console.log(' • workflow_template Manage workflow templates');
|
||||
console.log(' • batch_process Batch processing');
|
||||
console.log(' • parallel_execute Execute tasks in parallel');
|
||||
log('\n🔧 WORKFLOW & AUTOMATION (11 tools):');
|
||||
log(' • workflow_create Create custom workflows');
|
||||
log(' • workflow_execute Execute predefined workflows');
|
||||
log(' • workflow_export Export workflow definitions');
|
||||
log(' • sparc_mode Run SPARC development modes');
|
||||
log(' • automation_setup Setup automation rules');
|
||||
log(' • pipeline_create Create CI/CD pipelines');
|
||||
log(' • scheduler_manage Manage task scheduling');
|
||||
log(' • trigger_setup Setup event triggers');
|
||||
log(' • workflow_template Manage workflow templates');
|
||||
log(' • batch_process Batch processing');
|
||||
log(' • parallel_execute Execute tasks in parallel');
|
||||
}
|
||||
if (!category || category === 'github') {
|
||||
console.log('\n🐙 GITHUB INTEGRATION (8 tools):');
|
||||
console.log(' • github_repo_analyze Repository analysis');
|
||||
console.log(' • github_pr_manage Pull request management');
|
||||
console.log(' • github_issue_track Issue tracking & triage');
|
||||
console.log(' • github_release_coord Release coordination');
|
||||
console.log(' • github_workflow_auto Workflow automation');
|
||||
console.log(' • github_code_review Automated code review');
|
||||
console.log(' • github_sync_coord Multi-repo sync coordination');
|
||||
console.log(' • github_metrics Repository metrics');
|
||||
log('\n🐙 GITHUB INTEGRATION (8 tools):');
|
||||
log(' • github_repo_analyze Repository analysis');
|
||||
log(' • github_pr_manage Pull request management');
|
||||
log(' • github_issue_track Issue tracking & triage');
|
||||
log(' • github_release_coord Release coordination');
|
||||
log(' • github_workflow_auto Workflow automation');
|
||||
log(' • github_code_review Automated code review');
|
||||
log(' • github_sync_coord Multi-repo sync coordination');
|
||||
log(' • github_metrics Repository metrics');
|
||||
}
|
||||
if (!category || category === 'daa') {
|
||||
console.log('\n🤖 DAA (Dynamic Agent Architecture) (8 tools):');
|
||||
console.log(' • daa_agent_create Create dynamic agents');
|
||||
console.log(' • daa_capability_match Match capabilities to tasks');
|
||||
console.log(' • daa_resource_alloc Resource allocation');
|
||||
console.log(' • daa_lifecycle_manage Agent lifecycle management');
|
||||
console.log(' • daa_communication Inter-agent communication');
|
||||
console.log(' • daa_consensus Consensus mechanisms');
|
||||
console.log(' • daa_fault_tolerance Fault tolerance & recovery');
|
||||
console.log(' • daa_optimization Performance optimization');
|
||||
log('\n🤖 DAA (Dynamic Agent Architecture) (8 tools):');
|
||||
log(' • daa_agent_create Create dynamic agents');
|
||||
log(' • daa_capability_match Match capabilities to tasks');
|
||||
log(' • daa_resource_alloc Resource allocation');
|
||||
log(' • daa_lifecycle_manage Agent lifecycle management');
|
||||
log(' • daa_communication Inter-agent communication');
|
||||
log(' • daa_consensus Consensus mechanisms');
|
||||
log(' • daa_fault_tolerance Fault tolerance & recovery');
|
||||
log(' • daa_optimization Performance optimization');
|
||||
}
|
||||
if (!category || category === 'system') {
|
||||
console.log('\n⚙️ SYSTEM & UTILITIES (8 tools):');
|
||||
console.log(' • terminal_execute Execute terminal commands');
|
||||
console.log(' • config_manage Configuration management');
|
||||
console.log(' • features_detect Feature detection');
|
||||
console.log(' • security_scan Security scanning');
|
||||
console.log(' • backup_create Create system backups');
|
||||
console.log(' • restore_system System restoration');
|
||||
console.log(' • log_analysis Log analysis & insights');
|
||||
console.log(' • diagnostic_run System diagnostics');
|
||||
log('\n⚙️ SYSTEM & UTILITIES (8 tools):');
|
||||
log(' • terminal_execute Execute terminal commands');
|
||||
log(' • config_manage Configuration management');
|
||||
log(' • features_detect Feature detection');
|
||||
log(' • security_scan Security scanning');
|
||||
log(' • backup_create Create system backups');
|
||||
log(' • restore_system System restoration');
|
||||
log(' • log_analysis Log analysis & insights');
|
||||
log(' • diagnostic_run System diagnostics');
|
||||
}
|
||||
if (verbose) {
|
||||
console.log('\n📋 DETAILED TOOL INFORMATION:');
|
||||
console.log(' 🔥 HIGH-PRIORITY TOOLS:');
|
||||
console.log(' swarm_init: Initialize coordination with 4 topologies (hierarchical, mesh, ring, star)');
|
||||
console.log(' agent_spawn: 8 agent types (researcher, coder, analyst, architect, tester, coordinator, reviewer, optimizer)');
|
||||
console.log(' neural_train: Train 27 neural models with WASM SIMD acceleration');
|
||||
console.log(' memory_usage: 5 operations (store, retrieve, list, delete, search) with TTL & namespacing');
|
||||
console.log(' performance_report: Real-time metrics with 24h/7d/30d timeframes');
|
||||
console.log('\n ⚡ PERFORMANCE FEATURES:');
|
||||
console.log(' • 2.8-4.4x speed improvement with parallel execution');
|
||||
console.log(' • 32.3% token reduction through optimization');
|
||||
console.log(' • 84.8% SWE-Bench solve rate with swarm coordination');
|
||||
console.log(' • WASM neural processing with SIMD optimization');
|
||||
console.log(' • Cross-session memory persistence');
|
||||
console.log('\n 🔗 INTEGRATION CAPABILITIES:');
|
||||
console.log(' • Full ruv-swarm feature parity (rebranded)');
|
||||
console.log(' • Claude Code native tool integration');
|
||||
console.log(' • GitHub Actions workflow automation');
|
||||
console.log(' • SPARC methodology with 17 modes');
|
||||
console.log(' • MCP protocol compatibility');
|
||||
log('\n📋 DETAILED TOOL INFORMATION:');
|
||||
log(' 🔥 HIGH-PRIORITY TOOLS:');
|
||||
log(' swarm_init: Initialize coordination with 4 topologies (hierarchical, mesh, ring, star)');
|
||||
log(' agent_spawn: 8 agent types (researcher, coder, analyst, architect, tester, coordinator, reviewer, optimizer)');
|
||||
log(' neural_train: Train 27 neural models with WASM SIMD acceleration');
|
||||
log(' memory_usage: 5 operations (store, retrieve, list, delete, search) with TTL & namespacing');
|
||||
log(' performance_report: Real-time metrics with 24h/7d/30d timeframes');
|
||||
log('\n ⚡ PERFORMANCE FEATURES:');
|
||||
log(' • 2.8-4.4x speed improvement with parallel execution');
|
||||
log(' • 32.3% token reduction through optimization');
|
||||
log(' • 84.8% SWE-Bench solve rate with swarm coordination');
|
||||
log(' • WASM neural processing with SIMD optimization');
|
||||
log(' • Cross-session memory persistence');
|
||||
log('\n 🔗 INTEGRATION CAPABILITIES:');
|
||||
log(' • Full ruv-swarm feature parity (rebranded)');
|
||||
log(' • Claude Code native tool integration');
|
||||
log(' • GitHub Actions workflow automation');
|
||||
log(' • SPARC methodology with 17 modes');
|
||||
log(' • MCP protocol compatibility');
|
||||
}
|
||||
console.log('\n📡 Status: 87 tools & resources available when server is running');
|
||||
console.log('🎯 Categories: swarm, neural, memory, analysis, workflow, github, daa, system');
|
||||
console.log('🔗 Compatibility: ruv-swarm + DAA + Claude-Flow unified platform');
|
||||
console.log('\n💡 Usage: claude-flow mcp tools --category=<category> --verbose');
|
||||
log('\n📡 Status: 87 tools & resources available when server is running');
|
||||
log('🎯 Categories: swarm, neural, memory, analysis, workflow, github, daa, system');
|
||||
log('🔗 Compatibility: ruv-swarm + DAA + Claude-Flow unified platform');
|
||||
log('\n💡 Usage: claude-flow mcp tools --category=<category> --verbose');
|
||||
}
|
||||
async function manageMcpAuth(subArgs, flags) {
|
||||
const authCmd = subArgs[1];
|
||||
switch(authCmd){
|
||||
case 'setup':
|
||||
printSuccess('Setting up MCP authentication...');
|
||||
console.log('🔐 Authentication configuration:');
|
||||
console.log(' Type: API Key based');
|
||||
console.log(' Scope: Claude-Flow tools');
|
||||
console.log(' Security: TLS encrypted');
|
||||
success('Setting up MCP authentication...');
|
||||
log('🔐 Authentication configuration:');
|
||||
log(' Type: API Key based');
|
||||
log(' Scope: Claude-Flow tools');
|
||||
log(' Security: TLS encrypted');
|
||||
break;
|
||||
case 'status':
|
||||
printSuccess('MCP Authentication Status:');
|
||||
console.log('🔐 Status: Not configured');
|
||||
console.log('🔑 API Keys: 0 active');
|
||||
console.log('🛡️ Security: Default settings');
|
||||
success('MCP Authentication Status:');
|
||||
log('🔐 Status: Not configured');
|
||||
log('🔑 API Keys: 0 active');
|
||||
log('🛡️ Security: Default settings');
|
||||
break;
|
||||
case 'rotate':
|
||||
printSuccess('Rotating MCP authentication keys...');
|
||||
console.log('🔄 New API keys would be generated');
|
||||
console.log('♻️ Old keys would be deprecated gracefully');
|
||||
success('Rotating MCP authentication keys...');
|
||||
log('🔄 New API keys would be generated');
|
||||
log('♻️ Old keys would be deprecated gracefully');
|
||||
break;
|
||||
default:
|
||||
console.log('Auth commands: setup, status, rotate');
|
||||
console.log('Examples:');
|
||||
console.log(' claude-flow mcp auth setup');
|
||||
console.log(' claude-flow mcp auth status');
|
||||
log('Auth commands: setup, status, rotate');
|
||||
log('Examples:');
|
||||
log(' claude-flow mcp auth setup');
|
||||
log(' claude-flow mcp auth status');
|
||||
}
|
||||
}
|
||||
async function showMcpConfig(subArgs, flags) {
|
||||
printSuccess('Claude-Flow MCP Server Configuration:');
|
||||
console.log('\n📋 Server Settings:');
|
||||
console.log(' Host: localhost');
|
||||
console.log(' Port: 3000');
|
||||
console.log(' Protocol: HTTP/STDIO');
|
||||
console.log(' Timeout: 30000ms');
|
||||
console.log(' Auto-Orchestrator: Enabled');
|
||||
console.log('\n🔧 Tool Configuration:');
|
||||
console.log(' Available Tools: 87 total');
|
||||
console.log(' Categories: 8 (swarm, neural, memory, analysis, workflow, github, daa, system)');
|
||||
console.log(' Authentication: API Key + OAuth');
|
||||
console.log(' Rate Limiting: 1000 req/min');
|
||||
console.log(' WASM Support: Enabled with SIMD');
|
||||
console.log('\n🧠 Neural Network Settings:');
|
||||
console.log(' Models: 27 pre-trained models available');
|
||||
console.log(' Training: Real-time adaptive learning');
|
||||
console.log(' Inference: WASM optimized');
|
||||
console.log(' Pattern Recognition: Enabled');
|
||||
console.log('\n🐝 Swarm Configuration:');
|
||||
console.log(' Max Agents: 10 per swarm');
|
||||
console.log(' Topologies: hierarchical, mesh, ring, star');
|
||||
console.log(' Coordination: Real-time with hooks');
|
||||
console.log(' Memory: Cross-session persistence');
|
||||
console.log('\n🔐 Security Settings:');
|
||||
console.log(' TLS: Enabled in production');
|
||||
console.log(' CORS: Configured for Claude Code');
|
||||
console.log(' API Key Rotation: 30 days');
|
||||
console.log(' Audit Logging: Enabled');
|
||||
console.log('\n🔗 Integration Settings:');
|
||||
console.log(' ruv-swarm Compatibility: 100%');
|
||||
console.log(' DAA Integration: Enabled');
|
||||
console.log(' GitHub Actions: Connected');
|
||||
console.log(' SPARC Modes: 17 available');
|
||||
console.log('\n📁 Configuration Files:');
|
||||
console.log(' Main Config: ./mcp_config/claude-flow.json');
|
||||
console.log(' Neural Models: ./models/');
|
||||
console.log(' Memory Store: ./memory/');
|
||||
console.log(' Logs: ./logs/mcp/');
|
||||
success('Claude-Flow MCP Server Configuration:');
|
||||
log('\n📋 Server Settings:');
|
||||
log(' Host: localhost');
|
||||
log(' Port: 3000');
|
||||
log(' Protocol: HTTP/STDIO');
|
||||
log(' Timeout: 30000ms');
|
||||
log(' Auto-Orchestrator: Enabled');
|
||||
log('\n🔧 Tool Configuration:');
|
||||
log(' Available Tools: 87 total');
|
||||
log(' Categories: 8 (swarm, neural, memory, analysis, workflow, github, daa, system)');
|
||||
log(' Authentication: API Key + OAuth');
|
||||
log(' Rate Limiting: 1000 req/min');
|
||||
log(' WASM Support: Enabled with SIMD');
|
||||
log('\n🧠 Neural Network Settings:');
|
||||
log(' Models: 27 pre-trained models available');
|
||||
log(' Training: Real-time adaptive learning');
|
||||
log(' Inference: WASM optimized');
|
||||
log(' Pattern Recognition: Enabled');
|
||||
log('\n🐝 Swarm Configuration:');
|
||||
log(' Max Agents: 10 per swarm');
|
||||
log(' Topologies: hierarchical, mesh, ring, star');
|
||||
log(' Coordination: Real-time with hooks');
|
||||
log(' Memory: Cross-session persistence');
|
||||
log('\n🔐 Security Settings:');
|
||||
log(' TLS: Enabled in production');
|
||||
log(' CORS: Configured for Claude Code');
|
||||
log(' API Key Rotation: 30 days');
|
||||
log(' Audit Logging: Enabled');
|
||||
log('\n🔗 Integration Settings:');
|
||||
log(' ruv-swarm Compatibility: 100%');
|
||||
log(' DAA Integration: Enabled');
|
||||
log(' GitHub Actions: Connected');
|
||||
log(' SPARC Modes: 17 available');
|
||||
log('\n📁 Configuration Files:');
|
||||
log(' Main Config: ./mcp_config/claude-flow.json');
|
||||
log(' Neural Models: ./models/');
|
||||
log(' Memory Store: ./memory/');
|
||||
log(' Logs: ./logs/mcp/');
|
||||
}
|
||||
function getFlag(args, flagName) {
|
||||
const index = args.indexOf(flagName);
|
||||
return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
|
||||
}
|
||||
function showMcpHelp() {
|
||||
console.log('🔧 Claude-Flow MCP Server Commands:');
|
||||
console.log();
|
||||
console.log('COMMANDS:');
|
||||
console.log(' status Show MCP server status');
|
||||
console.log(' start [options] Start MCP server with orchestrator');
|
||||
console.log(' stop Stop MCP server gracefully');
|
||||
console.log(' tools [options] List available tools & resources');
|
||||
console.log(' auth <setup|status|rotate> Manage authentication');
|
||||
console.log(' config Show comprehensive configuration');
|
||||
console.log();
|
||||
console.log('START OPTIONS:');
|
||||
console.log(' --port <port> Server port (default: 3000)');
|
||||
console.log(' --host <host> Server host (default: localhost)');
|
||||
console.log(' --auto-orchestrator Auto-start orchestrator with neural/WASM');
|
||||
console.log(' --daemon Run in background daemon mode');
|
||||
console.log(' --enable-neural Enable neural network features');
|
||||
console.log(' --enable-wasm Enable WASM SIMD optimization');
|
||||
console.log();
|
||||
console.log('TOOLS OPTIONS:');
|
||||
console.log(' --category <cat> Filter by category (swarm, neural, memory, etc.)');
|
||||
console.log(' --verbose, -v Show detailed tool information');
|
||||
console.log(' --examples Show usage examples');
|
||||
console.log();
|
||||
console.log('CATEGORIES:');
|
||||
console.log(' swarm 🐝 Swarm coordination (12 tools)');
|
||||
console.log(' neural 🧠 Neural networks & AI (15 tools)');
|
||||
console.log(' memory 💾 Memory & persistence (12 tools)');
|
||||
console.log(' analysis 📊 Analysis & monitoring (13 tools)');
|
||||
console.log(' workflow 🔧 Workflow & automation (11 tools)');
|
||||
console.log(' github 🐙 GitHub integration (8 tools)');
|
||||
console.log(' daa 🤖 Dynamic Agent Architecture (8 tools)');
|
||||
console.log(' system ⚙️ System & utilities (8 tools)');
|
||||
console.log();
|
||||
console.log('EXAMPLES:');
|
||||
console.log(' claude-flow mcp status');
|
||||
console.log(' claude-flow mcp start --auto-orchestrator --daemon');
|
||||
console.log(' claude-flow mcp tools --category=neural --verbose');
|
||||
console.log(' claude-flow mcp tools --category=swarm');
|
||||
console.log(' claude-flow mcp config');
|
||||
console.log(' claude-flow mcp auth setup');
|
||||
console.log();
|
||||
console.log('🎯 Total: 87 tools & resources available');
|
||||
console.log('🔗 Full ruv-swarm + DAA + Claude-Flow integration');
|
||||
log('🔧 Claude-Flow MCP Server Commands:');
|
||||
log();
|
||||
log('COMMANDS:');
|
||||
log(' status Show MCP server status');
|
||||
log(' start [options] Start MCP server with orchestrator');
|
||||
log(' stop Stop MCP server gracefully');
|
||||
log(' tools [options] List available tools & resources');
|
||||
log(' auth <setup|status|rotate> Manage authentication');
|
||||
log(' config Show comprehensive configuration');
|
||||
log();
|
||||
log('START OPTIONS:');
|
||||
log(' --port <port> Server port (default: 3000)');
|
||||
log(' --host <host> Server host (default: localhost)');
|
||||
log(' --auto-orchestrator Auto-start orchestrator with neural/WASM');
|
||||
log(' --daemon Run in background daemon mode');
|
||||
log(' --enable-neural Enable neural network features');
|
||||
log(' --enable-wasm Enable WASM SIMD optimization');
|
||||
log();
|
||||
log('TOOLS OPTIONS:');
|
||||
log(' --category <cat> Filter by category (swarm, neural, memory, etc.)');
|
||||
log(' --verbose, -v Show detailed tool information');
|
||||
log(' --examples Show usage examples');
|
||||
log();
|
||||
log('CATEGORIES:');
|
||||
log(' swarm 🐝 Swarm coordination (12 tools)');
|
||||
log(' neural 🧠 Neural networks & AI (15 tools)');
|
||||
log(' memory 💾 Memory & persistence (12 tools)');
|
||||
log(' analysis 📊 Analysis & monitoring (13 tools)');
|
||||
log(' workflow 🔧 Workflow & automation (11 tools)');
|
||||
log(' github 🐙 GitHub integration (8 tools)');
|
||||
log(' daa 🤖 Dynamic Agent Architecture (8 tools)');
|
||||
log(' system ⚙️ System & utilities (8 tools)');
|
||||
log();
|
||||
log('EXAMPLES:');
|
||||
log(' claude-flow mcp status');
|
||||
log(' claude-flow mcp start --auto-orchestrator --daemon');
|
||||
log(' claude-flow mcp tools --category=neural --verbose');
|
||||
log(' claude-flow mcp tools --category=swarm');
|
||||
log(' claude-flow mcp config');
|
||||
log(' claude-flow mcp auth setup');
|
||||
log();
|
||||
log('🎯 Total: 87 tools & resources available');
|
||||
log('🔗 Full ruv-swarm + DAA + Claude-Flow integration');
|
||||
}
|
||||
|
||||
//# sourceMappingURL=mcp.js.map
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/mcp.js"],"sourcesContent":["// mcp.js - MCP server management commands\nimport { printSuccess, printError, printWarning } from '../utils.js';\n\nexport async function mcpCommand(subArgs, flags) {\n const mcpCmd = subArgs[0];\n\n switch (mcpCmd) {\n case 'status':\n await showMcpStatus(subArgs, flags);\n break;\n\n case 'start':\n await startMcpServer(subArgs, flags);\n break;\n\n case 'stop':\n await stopMcpServer(subArgs, flags);\n break;\n\n case 'tools':\n await listMcpTools(subArgs, flags);\n break;\n\n case 'auth':\n await manageMcpAuth(subArgs, flags);\n break;\n\n case 'config':\n await showMcpConfig(subArgs, flags);\n break;\n\n default:\n showMcpHelp();\n }\n}\n\nasync function showMcpStatus(subArgs, flags) {\n printSuccess('MCP Server Status:');\n console.log('🌐 Status: Stopped (orchestrator not running)');\n console.log('🔧 Configuration: Default settings');\n console.log('🔌 Connections: 0 active');\n console.log('📡 Tools: Ready to load');\n console.log('🔐 Authentication: Not configured');\n}\n\nasync function startMcpServer(subArgs, flags) {\n const autoOrchestrator = subArgs.includes('--auto-orchestrator') || flags.autoOrchestrator;\n const daemon = subArgs.includes('--daemon') || flags.daemon;\n const stdio = subArgs.includes('--stdio') || flags.stdio || true; // Default to stdio mode\n\n if (stdio) {\n // Start MCP server in stdio mode (like ruv-swarm)\n printSuccess('Starting Claude Flow MCP server in stdio mode...');\n\n if (autoOrchestrator) {\n console.log('🚀 Auto-starting orchestrator...');\n console.log('🧠 Neural network capabilities: ENABLED');\n console.log('🔧 WASM SIMD optimization: ACTIVE');\n console.log('📊 Performance monitoring: ENABLED');\n console.log('🐝 Swarm coordination: READY');\n }\n\n // Import and start the MCP server\n try {\n const { fileURLToPath } = await import('url');\n const path = await import('path');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n // TODO: Switch to new TypeScript server (server-standalone.js) after fixing import resolution\n // For now, using old mcp-server.js for local testing\n // Phase 4 tools will be available after NPM publish\n const mcpServerPath = path.join(__dirname, '../../mcp/mcp-server.js');\n\n // Check if the file exists, and log the path for debugging\n const fs = await import('fs');\n if (!fs.existsSync(mcpServerPath)) {\n console.error(`MCP server file not found at: ${mcpServerPath}`);\n console.error(`Current directory: ${process.cwd()}`);\n console.error(`Script directory: ${__dirname}`);\n throw new Error(`MCP server file not found: ${mcpServerPath}`);\n }\n\n // Start the MCP server process\n const serverProcess = spawn('node', [mcpServerPath], {\n stdio: 'inherit',\n env: {\n ...process.env,\n CLAUDE_FLOW_AUTO_ORCHESTRATOR: autoOrchestrator ? 'true' : 'false',\n CLAUDE_FLOW_NEURAL_ENABLED: 'true',\n CLAUDE_FLOW_WASM_ENABLED: 'true',\n },\n });\n\n serverProcess.on('exit', (code) => {\n if (code !== 0) {\n console.error(`MCP server exited with code ${code}`);\n }\n });\n\n // Keep the process alive\n await new Promise(() => {}); // Never resolves, keeps server running\n } catch (error) {\n console.error('Failed to start MCP server:', error.message);\n\n // Fallback to status display\n console.log('🚀 MCP server would start with:');\n console.log(' Protocol: stdio');\n console.log(' Tools: 87 Claude-Flow integration tools');\n console.log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));\n console.log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));\n }\n } else {\n // HTTP mode (for future implementation)\n const port = getFlag(subArgs, '--port') || flags.port || 3000;\n const host = getFlag(subArgs, '--host') || flags.host || 'localhost';\n\n printSuccess(`Starting Claude Flow MCP server on ${host}:${port}...`);\n console.log('🚀 HTTP mode not yet implemented, use --stdio for full functionality');\n }\n}\n\nasync function stopMcpServer(subArgs, flags) {\n printSuccess('Stopping MCP server...');\n console.log('🛑 Server would be gracefully shut down');\n console.log('📝 Active connections would be closed');\n console.log('💾 State would be persisted');\n}\n\nasync function listMcpTools(subArgs, flags) {\n const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;\n const category = getFlag(subArgs, '--category') || flags.category;\n\n printSuccess('ClaudeLine truncated
|
||||
{"version":3,"sources":["../../../../src/cli/simple-commands/mcp.js"],"sourcesContent":["// mcp.js - MCP server management commands\nimport { printSuccess, printError, printWarning } from '../utils.js';\n\n// Module-level state to track stdio mode\nlet isStdioMode = false;\n\n// Smart logging helpers that respect stdio mode\n// In stdio mode: route to stderr to keep stdout clean for JSON-RPC\n// In HTTP mode: route to stdout for normal behavior\nconst log = (...args) => (isStdioMode ? console.error(...args) : console.log(...args));\nconst success = (msg) => (isStdioMode ? console.error(`✅ ${msg}`) : printSuccess(msg));\nconst error = (msg) => (isStdioMode ? console.error(`❌ ${msg}`) : printError(msg));\nconst warning = (msg) => (isStdioMode ? console.error(`⚠️ ${msg}`) : printWarning(msg));\n\nexport async function mcpCommand(subArgs, flags) {\n const mcpCmd = subArgs[0];\n\n switch (mcpCmd) {\n case 'status':\n await showMcpStatus(subArgs, flags);\n break;\n\n case 'start':\n await startMcpServer(subArgs, flags);\n break;\n\n case 'stop':\n await stopMcpServer(subArgs, flags);\n break;\n\n case 'tools':\n await listMcpTools(subArgs, flags);\n break;\n\n case 'auth':\n await manageMcpAuth(subArgs, flags);\n break;\n\n case 'config':\n await showMcpConfig(subArgs, flags);\n break;\n\n default:\n showMcpHelp();\n }\n}\n\nasync function showMcpStatus(subArgs, flags) {\n success('MCP Server Status:');\n log('🌐 Status: Stopped (orchestrator not running)');\n log('🔧 Configuration: Default settings');\n log('🔌 Connections: 0 active');\n log('📡 Tools: Ready to load');\n log('🔐 Authentication: Not configured');\n}\n\nasync function startMcpServer(subArgs, flags) {\n const autoOrchestrator = subArgs.includes('--auto-orchestrator') || flags.autoOrchestrator;\n const daemon = subArgs.includes('--daemon') || flags.daemon;\n const stdio = subArgs.includes('--stdio') || flags.stdio || true; // Default to stdio mode\n\n // Set module-level stdio flag for all helper functions\n isStdioMode = stdio;\n\n if (stdio) {\n // Start MCP server in stdio mode (like ruv-swarm)\n success('Starting Claude Flow MCP server in stdio mode...');\n\n if (autoOrchestrator) {\n log('🚀 Auto-starting orchestrator...');\n log('🧠 Neural network capabilities: ENABLED');\n log('🔧 WASM SIMD optimization: ACTIVE');\n log('📊 Performance monitoring: ENABLED');\n log('🐝 Swarm coordination: READY');\n }\n\n // Import and start the MCP server\n try {\n const { fileURLToPath } = await import('url');\n const path = await import('path');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n // TODO: Switch to new TypeScript server (server-standalone.js) after fixing import resolution\n // For now, using old mcp-server.js for local testing\n // Phase 4 tools will be available after NPM publish\n const mcpServerPath = path.join(__dirname, '../../mcp/mcp-server.js');\n\n // Check if the file exists, and log the path for debugging\n const fs = await import('fs');\n if (!fs.existsSync(mcpServerPath)) {\n error(`MCP server file not found at: ${mcpServerPath}`);\n error(`Current directory: ${process.cwd()}`);\n error(`Script directory: ${__dirname}`);\n throw new Error(`MCP server file not found: ${mcpServerPath}`);\n }\n\n // Start the MCP server process\n const serverProcess = spawn('node', [mcpServerPath], {\n stdio: 'inherit',\n env: {\n ...process.env,\n CLAUDE_FLOW_AUTO_ORCHESTRATOR: autoOrchestrator ? 'true' : 'false',\n CLAUDE_FLOW_NEURAL_ENABLED: 'true',\n CLAUDE_FLOW_WASM_ENABLED: 'true',\n },\n });\n\n serverProcess.on('exit', (code) => {\n if (code !== 0) {\n error(`MCP server exited with code ${code}`);\n }\n });\n\n // Keep the process alive\n await new Promise(() => {}); // Never resolves, keeps server running\n } catch (err) {\n error('Failed to start MCP server: ' + err.message);\n\n // Fallback to status display\n log('🚀 MCP server would start with:');\n log(' Protocol: stdio');\n log(' Tools: 87 Claude-Flow integration tools');\n log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));\n log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));\n }\n } else {\n // HTTP mode (for future implementation)\n const port = getFlag(subArgs, '--port') || flags.port || 3000;\n const host = getFlag(subArgs, '--host') || flags.host || 'localhost';\n\n success(`Starting Claude Flow MCP server on ${host}:${port}...`);\n log('🚀 HTTP mode not yet implemented, use --stdio for full functionality');\n Line truncated
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/cli/validation-helper.js"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(value, paramName, validOptions, commandPath) {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(value, paramName, min, max, commandPath) {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value, paramName, commandPath) {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(path, paramName, commandPath) {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value, paramName, commandPath) {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aAAaC,KAAK,EAAEC,SAAS,EAAEC,YAAY,EAAEC,WAAW,EAAE;QAC/D,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eAAeV,KAAK,EAAEC,SAAS,EAAEU,GAAG,EAAEC,GAAG,EAAET,WAAW,EAAE;QAC7D,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACrD,IAAI,CAACH,SAAU,OAAOA,UAAU,YAAYA,MAAMmB,IAAI,OAAO,IAAK;YAChEd,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,4BAA4B,EAAEf,WAAW,EAC1CE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,aAAaW,iBAAiBC,IAAI,EAAEpB,SAAS,EAAEE,WAAW,EAAE;QAC1D,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACpD,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;Line truncated
|
||||
{"version":3,"sources":["../../../src/cli/validation-helper.ts"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(\n value: string,\n paramName: string,\n validOptions: string[],\n commandPath: string,\n ): void {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(\n value: string,\n paramName: string,\n min?: number,\n max?: number,\n commandPath?: string,\n ): number {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value: any, paramName: string, commandPath?: string): void {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(\n path: string,\n paramName: string,\n commandPath?: string,\n ): Promise<void> {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value: string, paramName: string, commandPath?: string): boolean {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aACLC,KAAa,EACbC,SAAiB,EACjBC,YAAsB,EACtBC,WAAmB,EACb;QACN,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eACLV,KAAa,EACbC,SAAiB,EACjBU,GAAY,EACZC,GAAY,EACZT,WAAoB,EACZ;QACR,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAU,EAAEC,SAAiB,EAAEE,WAAoB,EAAQ;QACjF,IAAI,CAACH,SAAU,OAAOA,UAAU,YAAYA,MAAMmB,IAAI,OAAO,IAAK;YAChEd,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,4BAA4B,EAAEf,WAAW,EAC1CE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,aAAaW,iBACXC,IAAY,EACZpB,SAAiB,EACjBE,WAAoB,EACL;QACf,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAa,EAAELine truncated
|
||||
@@ -12,7 +12,7 @@ try {
|
||||
BUILD_DATE = new Date().toISOString().split('T')[0];
|
||||
} catch (error) {
|
||||
console.warn('Warning: Could not read version from package.json, using fallback');
|
||||
VERSION = '2.0.0-alpha.101';
|
||||
VERSION = '2.0.0-alpha.91';
|
||||
BUILD_DATE = new Date().toISOString().split('T')[0];
|
||||
}
|
||||
export { VERSION, BUILD_DATE };
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/core/version.js"],"sourcesContent":["/**\n * Centralized version management (JavaScript version)\n * Reads version from package.json to ensure consistency\n */\n\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Get the directory of this module\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read version from package.json\nlet VERSION;\nlet BUILD_DATE;\n\ntry {\n // Navigate to project root and read package.json\n const packageJsonPath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n VERSION = packageJson.version;\n BUILD_DATE = new Date().toISOString().split('T')[0];\n} catch (error) {\n // Fallback version if package.json can't be read\n console.warn('Warning: Could not read version from package.json, using fallback');\n VERSION = '2.0.0-alpha.101';\n BUILD_DATE = new Date().toISOString().split('T')[0];\n}\n\nexport { VERSION, BUILD_DATE };\n\n// Helper function to get formatted version string\nexport function getVersionString(includeV = true) {\n return includeV ? `v${VERSION}` : VERSION;\n}\n\n// Helper function for version display in CLI\nexport function displayVersion() {\n console.log(getVersionString());\n}"],"names":["readFileSync","join","dirname","fileURLToPath","__filename","url","__dirname","VERSION","BUILD_DATE","packageJsonPath","packageJson","JSON","parse","version","Date","toISOString","split","error","console","warn","getVersionString","includeV","displayVersion","log"],"mappings":"AAKA,SAASA,YAAY,QAAQ,KAAK;AAClC,SAASC,IAAI,EAAEC,OAAO,QAAQ,OAAO;AACrC,SAASC,aAAa,QAAQ,MAAM;AAGpC,MAAMC,aAAaD,cAAc,YAAYE,GAAG;AAChD,MAAMC,YAAYJ,QAAQE;AAG1B,IAAIG;AACJ,IAAIC;AAEJ,IAAI;IAEF,MAAMC,kBAAkBR,KAAKK,WAAW;IACxC,MAAMI,cAAcC,KAAKC,KAAK,CAACZ,aAAaS,iBAAiB;IAC7DF,UAAUG,YAAYG,OAAO;IAC7BL,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD,EAAE,OAAOC,OAAO;IAEdC,QAAQC,IAAI,CAAC;IACbZ,UAAU;IACVC,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD;AAEA,SAAST,OAAO,EAAEC,UAAU,GAAG;AAG/B,OAAO,SAASY,iBAAiBC,WAAW,IAAI;IAC9C,OAAOA,WAAW,CAAC,CAAC,EAAEd,SAAS,GAAGA;AACpC;AAGA,OAAO,SAASe;IACdJ,QAAQK,GAAG,CAACH;AACd"}H;AACd"}
|
||||
{"version":3,"sources":["../../../src/core/version.ts"],"sourcesContent":["/**\n * Centralized version management\n * Reads version from package.json to ensure consistency\n */\n\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Get the directory of this module\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read version from package.json\nlet VERSION: string;\nlet BUILD_DATE: string;\n\ntry {\n // Navigate to project root and read package.json\n const packageJsonPath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n VERSION = packageJson.version;\n BUILD_DATE = new Date().toISOString().split('T')[0];\n} catch (error) {\n // Fallback version if package.json can't be read\n console.warn('Warning: Could not read version from package.json, using fallback');\n VERSION = '2.0.0-alpha.91';\n BUILD_DATE = new Date().toISOString().split('T')[0];\n}\n\nexport { VERSION, BUILD_DATE };\n\n// Helper function to get formatted version string\nexport function getVersionString(includeV = true): string {\n return includeV ? `v${VERSION}` : VERSION;\n}\n\n// Helper function for version display in CLI\nexport function displayVersion(): void {\n console.log(getVersionString());\n}"],"names":["readFileSync","join","dirname","fileURLToPath","__filename","url","__dirname","VERSION","BUILD_DATE","packageJsonPath","packageJson","JSON","parse","version","Date","toISOString","split","error","console","warn","getVersionString","includeV","displayVersion","log"],"mappings":"AAKA,SAASA,YAAY,QAAQ,KAAK;AAClC,SAASC,IAAI,EAAEC,OAAO,QAAQ,OAAO;AACrC,SAASC,aAAa,QAAQ,MAAM;AAGpC,MAAMC,aAAaD,cAAc,YAAYE,GAAG;AAChD,MAAMC,YAAYJ,QAAQE;AAG1B,IAAIG;AACJ,IAAIC;AAEJ,IAAI;IAEF,MAAMC,kBAAkBR,KAAKK,WAAW;IACxC,MAAMI,cAAcC,KAAKC,KAAK,CAACZ,aAAaS,iBAAiB;IAC7DF,UAAUG,YAAYG,OAAO;IAC7BL,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD,EAAE,OAAOC,OAAO;IAEdC,QAAQC,IAAI,CAAC;IACbZ,UAAU;IACVC,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD;AAEA,SAAST,OAAO,EAAEC,UAAU,GAAG;AAG/B,OAAO,SAASY,iBAAiBC,WAAW,IAAI;IAC9C,OAAOA,WAAW,CAAC,CAAC,EAAEd,SAAS,GAAGA;AACpC;AAGA,OAAO,SAASe;IACdJ,QAAQK,GAAG,CAACH;AACd"}
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/utils/error-handler.ts"],"sourcesContent":["/**\n * Utility for proper error handling in TypeScript\n */\n\nimport {\n getErrorMessage as getErrorMsg,\n getErrorStack as getErrorStk,\n isError as isErr,\n} from './type-guards.js';\n\nexport class AppError extends Error {\n constructor(\n message: string,\n public code?: string,\n public statusCode?: number,\n ) {\n super(message);\n this.name = 'AppError';\n Object.setPrototypeOf(this, AppError.prototype);\n }\n}\n\n// Re-export from type-guards for backward compatibility\nexport const isError = isErr;\nexport const getErrorMessage = getErrorMsg;\nexport const getErrorStack = getErrorStk;\n\nexport function handleError(error: unknown, context?: string): never {\n const message = getErrorMessage(error);\n const stack = getErrorStack(error);\n\n console.error(`Error${context ? ` in ${context}` : ''}: ${message}`);\n if (stack && process.env.NODE_ENV === 'development') {\n console.error('Stack trace:', stack);\n }\n\n process.exit(1);\n}\n"],"names":["getErrorMessage","getErrorMsg","getErrorStack","getErrorStk","isError","isErr","AppError","Error","message","code","statusCode","name","Object","setPrototypeOf","prototype","handleError","error","context","stack","console","process","env","NODE_ENV","exit"],"mappings":"AAIA,SACEA,mBAAmBC,WAAW,EAC9BC,iBAAiBC,WAAW,EAC5BC,WAAWC,KAAK,QACX,mBAAmB;AAE1B,OAAO,MAAMC,iBAAiBC;;;IAC5B,YACEC,OAAe,EACf,AAAOC,IAAa,EACpB,AAAOC,UAAmB,CAC1B;QACA,KAAK,CAACF,eAHCC,OAAAA,WACAC,aAAAA;QAGP,IAAI,CAACC,IAAI,GAAG;QACZC,OAAOC,cAAc,CAAC,IAAI,EAAEP,SAASQ,SAAS;IAChD;AACF;AAGA,OAAO,MAAMV,UAAUC,MAAM;AAC7B,OAAO,MAAML,kBAAkBC,YAAY;AAC3C,OAAO,MAAMC,gBAAgBC,YAAY;AAEzC,OAAO,SAASY,YAAYC,KAAc,EAAEC,OAAgB;IAC1D,MAAMT,UAAUR,gBAAgBgB;IAChC,MAAME,QAAQhB,cAAcc;IAE5BG,QAAQH,KAAK,CAAC,CAAC,KAAK,EAAEC,UAAU,CAAC,IAAI,EAAEA,SAAS,GAAG,GAAG,EAAE,EAAET,SAAS;IACnE,IAAIU,SAASE,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QACnDH,QAAQH,KAAK,CAAC,gBAAgBE;IAChC;IAEAE,QAAQG,IAAI,CAAC;AACf"}
|
||||
{"version":3,"sources":["../../../src/utils/error-handler.js"],"sourcesContent":["// Re-export from TypeScript file\nexport * from './error-handler.ts';\n"],"names":[],"mappings":"AACA,cAAc,qBAAqB"}rorStack as getErrorStk,\n isError as isErr,\n} from './type-guards.js';\n\nexport class AppError extends Error {\n constructor(\n message: string,\n public code?: string,\n public statusCode?: number,\n ) {\n super(message);\n this.name = 'AppError';\n Object.setPrototypeOf(this, AppError.prototype);\n }\n}\n\n// Re-export from type-guards for backward compatibility\nexport const isError = isErr;\nexport const getErrorMessage = getErrorMsg;\nexport const getErrorStack = getErrorStk;\n\nexport function handleError(error: unknown, context?: string): never {\n const message = getErrorMessage(error);\n const stack = getErrorStack(error);\n\n console.error(`Error${context ? ` in ${context}` : ''}: ${message}`);\n if (stack && process.env.NODE_ENV === 'development') {\n console.error('Stack trace:', stack);\n }\n\n process.exit(1);\n}\n"],"names":["getErrorMessage","getErrorMsg","getErrorStack","getErrorStk","isError","isErr","AppError","Error","message","code","statusCode","name","Object","setPrototypeOf","prototype","handleError","error","context","stack","console","process","env","NODE_ENV","exit"],"mappings":"AAIA,SACEA,mBAAmBC,WAAW,EAC9BC,iBAAiBC,WAAW,EAC5BC,WAAWC,KAAK,QACX,mBAAmB;AAE1B,OAAO,MAAMC,iBAAiBC;;;IAC5B,YACEC,OAAe,EACf,AAAOC,IAAa,EACpB,AAAOC,UAAmB,CAC1B;QACA,KAAK,CAACF,eAHCC,OAAAA,WACAC,aAAAA;QAGP,IAAI,CAACC,IAAI,GAAG;QACZC,OAAOC,cAAc,CAAC,IAAI,EAAEP,SAASQ,SAAS;IAChD;AACF;AAGA,OAAO,MAAMV,UAAUC,MAAM;AAC7B,OAAO,MAAML,kBAAkBC,YAAY;AAC3C,OAAO,MAAMC,gBAAgBC,YAAY;AAEzC,OAAO,SAASY,YAAYC,KAAc,EAAEC,OAAgB;IAC1D,MAAMT,UAAUR,gBAAgBgB;IAChC,MAAME,QAAQhB,cAAcc;IAE5BG,QAAQH,KAAK,CAAC,CAAC,KAAK,EAAEC,UAAU,CAAC,IAAI,EAAEA,SAAS,GAAG,GAAG,EAAE,EAAET,SAAS;IACnE,IAAIU,SAASE,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;QACnDH,QAAQH,KAAK,CAAC,gBAAgBE;IAChC;IAEAE,QAAQG,IAAI,CAAC;AACf"}
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/utils/key-redactor.ts"],"sourcesContent":["/**\n * API Key Redaction Utility\n * Prevents sensitive data from leaking into logs, memory, or git commits\n */\n\nexport interface RedactionConfig {\n patterns: RegExp[];\n replacement: string;\n maskLength: number;\n}\n\nexport class KeyRedactor {\n private static readonly API_KEY_PATTERNS = [\n // Anthropic API keys\n /sk-ant-[a-zA-Z0-9_-]{95,}/gi,\n\n // OpenRouter API keys\n /sk-or-[a-zA-Z0-9_-]{32,}/gi,\n\n // Google/Gemini API keys\n /AIza[a-zA-Z0-9_-]{35}/gi,\n\n // Generic API keys\n /[a-zA-Z0-9_-]{20,}API[a-zA-Z0-9_-]{20,}/gi,\n\n // Bearer tokens\n /Bearer\\s+[a-zA-Z0-9_\\-\\.]{20,}/gi,\n\n // Environment variable format\n /([A-Z_]+_API_KEY|[A-Z_]+_TOKEN|[A-Z_]+_SECRET)=[\"']?([^\"'\\s]+)[\"']?/gi,\n\n // Supabase keys\n /eyJ[a-zA-Z0-9_-]*\\.eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/gi,\n ];\n\n private static readonly SENSITIVE_FIELDS = [\n 'apiKey',\n 'api_key',\n 'token',\n 'secret',\n 'password',\n 'private_key',\n 'privateKey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n ];\n\n /**\n * Redact API keys and sensitive data from text\n */\n static redact(text: string, showPrefix = true): string {\n if (!text) return text;\n\n let redacted = text;\n\n // Redact using patterns\n this.API_KEY_PATTERNS.forEach(pattern => {\n redacted = redacted.replace(pattern, (match) => {\n if (showPrefix && match.length > 8) {\n const prefix = match.substring(0, 8);\n return `${prefix}...[REDACTED]`;\n }\n return '[REDACTED_API_KEY]';\n });\n });\n\n return redacted;\n }\n\n /**\n * Redact sensitive fields in objects\n */\n static redactObject<T extends Record<string, any>>(obj: T, deep = true): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = { ...obj };\n\n Object.keys(redacted).forEach(key => {\n const lowerKey = key.toLowerCase();\n\n // Check if field name is sensitive\n const isSensitive = this.SENSITIVE_FIELDS.some(field =>\n lowerKey.includes(field)\n );\n\n if (isSensitive && typeof redacted[key] === 'string') {\n const value = redacted[key] as string;\n if (value && value.length > 8) {\n redacted[key] = `${value.substring(0, 4)}...[REDACTED]` as any;\n } else {\n redacted[key] = '[REDACTED]' as any;\n }\n } else if (deep && typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactObject(redacted[key], deep);\n } else if (typeof redacted[key] === 'string') {\n // Redact any API keys in string values\n redacted[key] = this.redact(redacted[key]) as any;\n }\n });\n\n return redacted;\n }\n\n /**\n * Sanitize text for safe logging\n */\n static sanitize(text: string): string {\n return this.redact(text, true);\n }\n\n /**\n * Sanitize command arguments\n */\n static sanitizeArgs(args: string[]): string[] {\n return args.map(arg => {\n // Check if arg is a flag value pair\n if (arg.includes('key') || arg.includes('token') || arg.includes('secret')) {\n return this.redact(arg);\n }\n return arg;\n });\n }\n\n /**\n * Check if text contains unredacted sensitive data\n */\n static containsSensitiveData(text: string): boolean {\n return this.API_KEY_PATTERNS.some(pattern => pattern.test(text));\n }\n\n /**\n * Validate that text is safe for logging/storage\n */\n static validate(text: string): { safe: boolean; warnings: string[] } {\n const warnings: string[] = [];\n\n this.API_KEY_PATTERNS.forEach((pattern, index) => {\n if (pattern.test(text)) {\n warnings.push(`Potential API key detected (pattern ${index + 1})`);\n }\n });\n\n return {\n safe: warnings.length === 0,\n warnings,\n };\n }\n\n /**\n * Redact environment variables\n */\n static redactEnv(env: Record<string, string | undefined>): Record<string, string> {\n const redacted: Record<string, string> = {};\n\n Object.keys(env).forEach(key => {\n const value = env[key];\n if (!value) {\n redacted[key] = '';\n return;\n }\n\n const lowerKey = key.toLowerCase();\n const isSensitive = lowerKey.includes('key') ||\n lowerKey.includes('token') ||\n lowerKey.includes('secret') ||\n lowerKey.includes('password');\n\n if (isSensitive) {\n redacted[key] = value.length > 8\n ? `${value.substring(0, 4)}...[REDACTED]`\n : '[REDACTED]';\n } else {\n redacted[key] = value;\n }\n });\n\n return redacted;\n }\n}\n\n// Export singleton instance\nexport const redactor = KeyRedactor;\n"],"names":["KeyRedactor","API_KEY_PATTERNS","SENSITIVE_FLine truncated
|
||||
{"version":3,"sources":["../../../src/utils/key-redactor.js"],"sourcesContent":["/**\n * API Key Redaction Utility\n * Prevents sensitive data from leaking into logs, memory, or git commits\n */\n\nexport class KeyRedactor {\n static API_KEY_PATTERNS = [\n // Anthropic API keys\n /sk-ant-[a-zA-Z0-9_-]{95,}/gi,\n\n // OpenRouter API keys\n /sk-or-[a-zA-Z0-9_-]{32,}/gi,\n\n // Google/Gemini API keys\n /AIza[a-zA-Z0-9_-]{35}/gi,\n\n // Generic API keys\n /[a-zA-Z0-9_-]{20,}API[a-zA-Z0-9_-]{20,}/gi,\n\n // Bearer tokens\n /Bearer\\s+[a-zA-Z0-9_\\-\\.]{20,}/gi,\n\n // Environment variable format\n /([A-Z_]+_API_KEY|[A-Z_]+_TOKEN|[A-Z_]+_SECRET)=[\"']?([^\"'\\s]+)[\"']?/gi,\n\n // Supabase keys\n /eyJ[a-zA-Z0-9_-]*\\.eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/gi,\n ];\n\n static SENSITIVE_FIELDS = [\n 'apiKey',\n 'api_key',\n 'token',\n 'secret',\n 'password',\n 'private_key',\n 'privateKey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n ];\n\n /**\n * Redact API keys and sensitive data from text\n */\n static redact(text, showPrefix = true) {\n if (!text) return text;\n\n let redacted = text;\n\n // Redact using patterns\n this.API_KEY_PATTERNS.forEach(pattern => {\n redacted = redacted.replace(pattern, (match) => {\n if (showPrefix && match.length > 8) {\n const prefix = match.substring(0, 8);\n return `${prefix}...[REDACTED]`;\n }\n return '[REDACTED_API_KEY]';\n });\n });\n\n return redacted;\n }\n\n /**\n * Redact sensitive fields in objects\n */\n static redactObject(obj, deep = true) {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = { ...obj };\n\n Object.keys(redacted).forEach(key => {\n const lowerKey = key.toLowerCase();\n\n // Check if field name is sensitive\n const isSensitive = this.SENSITIVE_FIELDS.some(field =>\n lowerKey.includes(field)\n );\n\n if (isSensitive && typeof redacted[key] === 'string') {\n const value = redacted[key];\n if (value && value.length > 8) {\n redacted[key] = `${value.substring(0, 4)}...[REDACTED]`;\n } else {\n redacted[key] = '[REDACTED]';\n }\n } else if (deep && typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactObject(redacted[key], deep);\n } else if (typeof redacted[key] === 'string') {\n // Redact any API keys in string values\n redacted[key] = this.redact(redacted[key]);\n }\n });\n\n return redacted;\n }\n\n /**\n * Sanitize text for safe logging\n */\n static sanitize(text) {\n return this.redact(text, true);\n }\n\n /**\n * Sanitize command arguments\n */\n static sanitizeArgs(args) {\n return args.map(arg => {\n // Check if arg is a flag value pair\n if (arg.includes('key') || arg.includes('token') || arg.includes('secret')) {\n return this.redact(arg);\n }\n return arg;\n });\n }\n\n /**\n * Check if text contains unredacted sensitive data\n */\n static containsSensitiveData(text) {\n return this.API_KEY_PATTERNS.some(pattern => pattern.test(text));\n }\n\n /**\n * Validate that text is safe for logging/storage\n */\n static validate(text) {\n const warnings = [];\n\n this.API_KEY_PATTERNS.forEach((pattern, index) => {\n if (pattern.test(text)) {\n warnings.push(`Potential API key detected (pattern ${index + 1})`);\n }\n });\n\n return {\n safe: warnings.length === 0,\n warnings,\n };\n }\n\n /**\n * Redact environment variables\n */\n static redactEnv(env) {\n const redacted = {};\n\n Object.keys(env).forEach(key => {\n const value = env[key];\n if (!value) {\n redacted[key] = '';\n return;\n }\n\n const lowerKey = key.toLowerCase();\n const isSensitive = lowerKey.includes('key') ||\n lowerKey.includes('token') ||\n lowerKey.includes('secret') ||\n lowerKey.includes('password');\n\n if (isSensitive) {\n redacted[key] = value.length > 8\n ? `${value.substring(0, 4)}...[REDACTED]`\n : '[REDACTED]';\n } else {\n redacted[key] = value;\n }\n });\n\n return redacted;\n }\n}\n\n// Export singleton instance\nexport const redactor = KeyRedactor;\n"],"names":["KeyRedactor","API_KEY_PATTERNS","SENSITIVE_FIELDS","redact","text","showPrefix","redacted","forEach","pattern","replace","match","length","prefix","substring","redactObject","obj","deep","Object","keys","key","lowerKey","toLowerCase","isSensitive","some","field","includes","value","sanitize","sanitizeArgs","args","map","arg","containsSensitiveData","test","validate","warnings","index","push","safe","redactEnv","env","redactor"],"mappings":"AAKA,OAAO,MAAMA;IACX,OALine truncated
|
||||
@@ -1,13 +1,11 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import * as fs from 'fs/promises';
|
||||
import * as path from 'path';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
const execAsync = promisify(exec);
|
||||
let MetricsReader = class MetricsReader {
|
||||
constructor(){
|
||||
this.metricsDir = '.claude-flow/metrics';
|
||||
this.sessionsDir = '.claude-flow/sessions';
|
||||
}
|
||||
export class MetricsReader {
|
||||
metricsDir = '.claude-flow/metrics';
|
||||
sessionsDir = '.claude-flow/sessions';
|
||||
async getSystemMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'system-metrics.json');
|
||||
@@ -18,15 +16,6 @@ let MetricsReader = class MetricsReader {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
async getTaskQueue() {
|
||||
try {
|
||||
const queueFile = '.claude-flow/tasks/queue.json';
|
||||
const content = await fs.readFile(queueFile, 'utf8');
|
||||
return JSON.parse(content);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
async getTaskMetrics() {
|
||||
try {
|
||||
const filePath = path.join(this.metricsDir, 'task-metrics.json');
|
||||
@@ -47,30 +36,30 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getActiveAgents() {
|
||||
try {
|
||||
const perfMetrics = await this.getPerformanceMetrics();
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
const agents = [];
|
||||
const agentsDir = '.claude-flow/agents';
|
||||
try {
|
||||
const agentFiles = await fs.readdir(agentsDir);
|
||||
for (const file of agentFiles){
|
||||
if (file.endsWith('.json')) {
|
||||
try {
|
||||
const content = await fs.readFile(path.join(agentsDir, file), 'utf8');
|
||||
const agent = JSON.parse(content);
|
||||
agents.push(agent);
|
||||
} catch {}
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
if (agents.length === 0) {
|
||||
const sessionFiles = await this.getSessionFiles();
|
||||
for (const file of sessionFiles){
|
||||
try {
|
||||
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
||||
const sessionData = JSON.parse(content);
|
||||
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
||||
agents.push(...sessionData.agents);
|
||||
}
|
||||
} catch {}
|
||||
} catch {}
|
||||
}
|
||||
if (agents.length === 0 && perfMetrics) {
|
||||
const activeCount = perfMetrics.activeAgents || 0;
|
||||
const totalCount = perfMetrics.totalAgents || 0;
|
||||
for(let i = 0; i < totalCount; i++){
|
||||
agents.push({
|
||||
id: `agent-${i + 1}`,
|
||||
name: `Agent ${i + 1}`,
|
||||
type: i === 0 ? 'orchestrator' : 'worker',
|
||||
status: i < activeCount ? 'active' : 'idle',
|
||||
activeTasks: i < activeCount ? 1 : 0,
|
||||
lastActivity: Date.now() - i * 1000
|
||||
});
|
||||
}
|
||||
}
|
||||
return agents;
|
||||
@@ -146,7 +135,7 @@ let MetricsReader = class MetricsReader {
|
||||
}
|
||||
async getMCPServerStatus() {
|
||||
try {
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp" | grep -v grep | wc -l');
|
||||
const { stdout } = await execAsync('ps aux | grep -E "mcp-server\\.js|claude-flow mcp start" | grep -v grep | wc -l');
|
||||
const processCount = parseInt(stdout.trim(), 10);
|
||||
const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E "claude-flow start" | grep -v grep | wc -l');
|
||||
const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;
|
||||
@@ -175,7 +164,6 @@ let MetricsReader = class MetricsReader {
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
export { MetricsReader };
|
||||
}
|
||||
|
||||
//# sourceMappingURL=metrics-reader.js.map
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/utils/metrics-reader.js"],"sourcesContent":["import { promises as fs } from 'fs';\nimport path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nclass MetricsReader {\n constructor() {\n this.metricsDir = '.claude-flow/metrics';\n this.sessionsDir = '.claude-flow/sessions';\n }\n\n async getSystemMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskQueue() {\n try {\n const queueFile = '.claude-flow/tasks/queue.json';\n const content = await fs.readFile(queueFile, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getTaskMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents() {\n try {\n const agents = [];\n \n // Check for agents in the .claude-flow/agents directory\n const agentsDir = '.claude-flow/agents';\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const file of agentFiles) {\n if (file.endsWith('.json')) {\n try {\n const content = await fs.readFile(path.join(agentsDir, file), 'utf8');\n const agent = JSON.parse(content);\n agents.push(agent);\n } catch {\n // Skip invalid agent files\n }\n }\n }\n } catch {\n // Agents directory doesn't exist yet\n }\n \n // If no agents found in directory, check session files\n if (agents.length === 0) {\n const sessionFiles = await this.getSessionFiles();\n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus() {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit = 10) {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n status: task.success ? 'completed' : 'failed',\n startTime: task.timestamp - task.duration,\n endTime: task.timestamp,\n duration: task.duration\n }));\n } catch (error) {\n return [];\n }\n }\n\n async getOverallHealth() {\n try {\n const systemMetrics = await this.getSystemMetrics();\n const perfMetrics = await this.getPerformanceMetrics();\n \n if (!systemMetrics && !perfMetrics) {\n return 'error';\n }\n \n // Check memory usage\n if (systemMetrics && systemMetrics.memoryUsagePercent > 90) {\n return 'error';\n }\n \n if (systemMetrics && systemMetrics.memoryUsagePercent > 75) {\n return 'warning';\n }\n \n // Check CPU load\n if (systemMetrics && systemMetrics.cpuLoad > 0.8) {\n return 'warning';\n }\n \n // Check task failure rate\n if (perfMetrics && perfMetrics.totalTasks > 0) {\n const failureRate = perfMetrics.failedTasks / perfMetrics.totalTasks;\n if (failureRate > 0.5) {\n return 'error';\n }\n if (failureRatLine truncated
|
||||
{"version":3,"sources":["../../../src/utils/metrics-reader.ts"],"sourcesContent":["import * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\ninterface SystemMetrics {\n timestamp: number;\n memoryTotal: number;\n memoryUsed: number;\n memoryFree: number;\n memoryUsagePercent: number;\n memoryEfficiency: number;\n cpuCount: number;\n cpuLoad: number;\n platform: string;\n uptime: number;\n}\n\ninterface TaskMetric {\n id: string;\n type: string;\n success: boolean;\n duration: number;\n timestamp: number;\n metadata: Record<string, any>;\n}\n\ninterface PerformanceMetrics {\n startTime: number;\n totalTasks: number;\n successfulTasks: number;\n failedTasks: number;\n totalAgents: number;\n activeAgents: number;\n neuralEvents: number;\n}\n\ninterface Agent {\n id: string;\n name: string;\n type: string;\n status: 'active' | 'idle' | 'busy';\n activeTasks: number;\n lastActivity?: number;\n}\n\ninterface SessionData {\n id: string;\n startTime: number;\n endTime?: number;\n agents: Agent[];\n tasks: any[];\n status: 'active' | 'completed' | 'paused';\n}\n\ninterface MCPServerStatus {\n running: boolean;\n processCount: number;\n orchestratorRunning: boolean;\n port: number | null;\n connections: number;\n}\n\nexport class MetricsReader {\n private metricsDir = '.claude-flow/metrics';\n private sessionsDir = '.claude-flow/sessions';\n\n async getSystemMetrics(): Promise<SystemMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics: SystemMetrics[] = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskMetrics(): Promise<TaskMetric[]> {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics(): Promise<PerformanceMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents(): Promise<Agent[]> {\n try {\n // First check performance metrics for agent count\n const perfMetrics = await this.getPerformanceMetrics();\n \n // Also check session files for more detailed agent info\n const sessionFiles = await this.getSessionFiles();\n const agents: Agent[] = [];\n \n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n \n // If no agents found in sessions, create mock agents based on performance metrics\n if (agents.length === 0 && perfMetrics) {\n const activeCount = perfMetrics.activeAgents || 0;\n const totalCount = perfMetrics.totalAgents || 0;\n \n for (let i = 0; i < totalCount; i++) {\n agents.push({\n id: `agent-${i + 1}`,\n name: `Agent ${i + 1}`,\n type: i === 0 ? 'orchestrator' : 'worker',\n status: i < activeCount ? 'active' : 'idle',\n activeTasks: i < activeCount ? 1 : 0,\n lastActivity: Date.now() - (i * 1000)\n });\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus(): Promise<SessionData | null> {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit: number = 10): Promise<any[]> {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n Line truncated
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "claude-flow",
|
||||
"version": "2.7.5",
|
||||
"version": "2.7.6",
|
||||
"description": "Enterprise-grade AI agent orchestration with WASM-powered ReasoningBank memory and AgentDB vector database (always uses latest agentic-flow)",
|
||||
"mcpName": "io.github.ruvnet/claude-flow",
|
||||
"main": "cli.mjs",
|
||||
|
||||
Reference in new issue
Block a user