claude-flow 2.7.34 → 2.7.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/bin/claude-flow +1 -1
- package/dist/src/__tests__/benchmarks/performance.bench.js +0 -19
- package/dist/src/__tests__/benchmarks/performance.bench.js.map +1 -1
- package/dist/src/__tests__/hook-matchers.test.js.map +1 -1
- package/dist/src/agents/agent-registry.js.map +1 -1
- package/dist/src/api/auth-service.js.map +1 -1
- package/dist/src/api/claude-client-enhanced.js +4 -2
- package/dist/src/api/claude-client-enhanced.js.map +1 -1
- package/dist/src/api/claude-client.js +4 -2
- package/dist/src/api/claude-client.js.map +1 -1
- package/dist/src/api/database-service.js.map +1 -1
- package/dist/src/api/swarm-api.js +1 -1
- package/dist/src/api/swarm-api.js.map +1 -1
- package/dist/src/cli/commands/hive-mind/wizard.js +1 -1
- package/dist/src/cli/commands/hive-mind/wizard.js.map +1 -1
- package/dist/src/cli/help-formatter.js +0 -5
- package/dist/src/cli/init/index.js +55 -33
- package/dist/src/cli/init/index.js.map +1 -1
- package/dist/src/cli/simple-commands/init/skills-copier.js +1 -1
- package/dist/src/cli/simple-commands/init/skills-copier.js.map +1 -1
- package/dist/src/cli/simple-orchestrator.js +1 -1
- package/dist/src/cli/simple-orchestrator.js.map +1 -1
- package/dist/src/coordination/conflict-resolution.js +1 -1
- package/dist/src/coordination/conflict-resolution.js.map +1 -1
- package/dist/src/coordination/load-balancer.js +1 -1
- package/dist/src/coordination/load-balancer.js.map +1 -1
- package/dist/src/core/DatabaseManager.js +39 -9
- package/dist/src/core/DatabaseManager.js.map +1 -1
- package/dist/src/core/config.js +1 -1
- package/dist/src/core/config.js.map +1 -1
- package/dist/src/enterprise/audit-manager.js +1 -1
- package/dist/src/enterprise/audit-manager.js.map +1 -1
- package/dist/src/providers/openai-provider.js +2 -2
- package/dist/src/providers/openai-provider.js.map +1 -1
- package/dist/src/sdk/checkpoint-manager.js +1 -1
- package/dist/src/sdk/checkpoint-manager.js.map +1 -1
- package/dist/src/services/agentic-flow-hooks/workflow-hooks.js +1 -1
- package/dist/src/services/agentic-flow-hooks/workflow-hooks.js.map +1 -1
- package/dist/src/swarm/coordinator.js +1 -1
- package/dist/src/swarm/coordinator.js.map +1 -1
- package/dist/src/utils/error-recovery.js +215 -0
- package/dist/src/utils/error-recovery.js.map +1 -0
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +10 -0
- package/dist/src/verification/rollback.js +2 -2
- package/dist/src/verification/rollback.js.map +1 -1
- package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js +4 -2
- package/dist/src/verification/tests/mocks/false-reporting-scenarios.test.js.map +1 -1
- package/docs/.claude-flow/metrics/performance.json +3 -3
- package/docs/.claude-flow/metrics/task-metrics.json +3 -3
- package/docs/architecture/README.md +555 -0
- package/docs/architecture/github-workflows-optimization-strategy.md +1079 -0
- package/docs/architecture/workflow-architecture-diagram.md +615 -0
- package/docs/architecture/workflow-optimization-implementation-guide.md +593 -0
- package/docs/features/AUTOMATIC_ERROR_RECOVERY_v2.7.35.md +321 -0
- package/docs/features/automatic-error-recovery.md +333 -0
- package/docs/fixes/WORKFLOW_FIXES.md +292 -0
- package/docs/fixes/WORKFLOW_FIXES_FINAL_STATUS.md +291 -0
- package/docs/fixes/github-workflow-fixes-pr888.md +279 -0
- package/docs/fixes/workflow-fixes-action-plan.md +388 -0
- package/docs/github-issues/README.md +88 -0
- package/docs/github-issues/wsl-enotempty-automatic-recovery.md +470 -0
- package/docs/github-workflow-fixes.md +219 -0
- package/docs/reviews/github-workflows-analysis-report.md +820 -0
- package/docs/reviews/pr-888-review-report.md +560 -0
- package/docs/testing/CONFIRMATION_AUTOMATIC_ERROR_RECOVERY.md +384 -0
- package/docs/testing/DOCKER_TEST_RESULTS_v2.7.35.md +305 -0
- package/docs/troubleshooting/wsl-better-sqlite3-error.md +239 -0
- package/docs/validation/workflow-fix-verification.md +206 -0
- package/package.json +7 -7
- package/scripts/create-github-issue.sh +64 -0
- package/scripts/test-docker-wsl.sh +198 -0
- package/src/__tests__/benchmarks/performance.bench.ts +2 -25
- package/src/__tests__/hook-matchers.test.ts +2 -0
- package/src/agents/agent-registry.ts +1 -1
- package/src/api/auth-service.ts +1 -1
- package/src/api/claude-client-enhanced.ts +2 -1
- package/src/api/claude-client.ts +2 -2
- package/src/api/database-service.ts +1 -2
- package/src/api/swarm-api.ts +2 -2
- package/src/cli/commands/hive-mind/wizard.ts +1 -1
- package/src/cli/init/index.ts +72 -42
- package/src/cli/simple-commands/init/skills-copier.js +1 -1
- package/src/cli/simple-orchestrator.ts +1 -1
- package/src/coordination/conflict-resolution.ts +1 -1
- package/src/coordination/load-balancer.ts +1 -1
- package/src/core/DatabaseManager.ts +55 -9
- package/src/core/config.ts +1 -1
- package/src/enterprise/audit-manager.ts +1 -1
- package/src/providers/openai-provider.ts +2 -2
- package/src/sdk/checkpoint-manager.ts +1 -1
- package/src/services/agentic-flow-hooks/workflow-hooks.ts +1 -1
- package/src/swarm/coordinator.ts +1 -1
- package/src/utils/error-recovery.ts +325 -0
- package/src/verification/rollback.ts +2 -2
- package/src/verification/tests/mocks/false-reporting-scenarios.test.ts +6 -3
- /package/docs/{BUG_REPORT_MEMORY_STATS.md → bug-reports/BUG_REPORT_MEMORY_STATS.md} +0 -0
- /package/docs/{MCP_2025_FEATURE_CONFIRMATION.md → features/MCP_2025_FEATURE_CONFIRMATION.md} +0 -0
- /package/docs/{OPTIONAL_LOCAL_EMBEDDINGS.md → features/OPTIONAL_LOCAL_EMBEDDINGS.md} +0 -0
- /package/docs/{mcp-2025-implementation-summary.md → features/mcp-2025-implementation-summary.md} +0 -0
- /package/docs/{mcp-spec-2025-implementation-plan.md → features/mcp-spec-2025-implementation-plan.md} +0 -0
- /package/docs/{AGENTIC_FLOW_ENABLED_LOG_FIX.md → fixes/AGENTIC_FLOW_ENABLED_LOG_FIX.md} +0 -0
- /package/docs/{MEMORY_COMMAND_FIX.md → fixes/MEMORY_COMMAND_FIX.md} +0 -0
- /package/docs/{NPX_MEMORY_FIX_v2.7.19.md → fixes/NPX_MEMORY_FIX_v2.7.19.md} +0 -0
- /package/docs/{REMOTE_INSTALL_FIX.md → fixes/REMOTE_INSTALL_FIX.md} +0 -0
- /package/docs/{SQLITE_FIX_COMPLETE_v2.7.21.md → fixes/SQLITE_FIX_COMPLETE_v2.7.21.md} +0 -0
- /package/docs/{NPM_PUBLISH_GUIDE_v2.7.33.md → guides/NPM_PUBLISH_GUIDE_v2.7.33.md} +0 -0
- /package/docs/{SWARM_INITIALIZATION_GUIDE.md → guides/SWARM_INITIALIZATION_GUIDE.md} +0 -0
- /package/docs/{AGENTDB_BRANCH_MERGE_VERIFICATION.md → integration/AGENTDB_BRANCH_MERGE_VERIFICATION.md} +0 -0
- /package/docs/{INTEGRATION_STATUS_FINAL.md → integration/INTEGRATION_STATUS_FINAL.md} +0 -0
- /package/docs/{agentic-flow-agentdb-mcp-integration.md → integration/agentic-flow-agentdb-mcp-integration.md} +0 -0
- /package/docs/{phase-1-2-implementation-summary.md → integration/phase-1-2-implementation-summary.md} +0 -0
- /package/docs/{.github-release-issue-v2.7.33.md → releases/.github-release-issue-v2.7.33.md} +0 -0
- /package/docs/{RELEASE_NOTES_v2.7.15.md → releases/RELEASE_NOTES_v2.7.15.md} +0 -0
- /package/docs/{RELEASE_NOTES_v2.7.33.md → releases/RELEASE_NOTES_v2.7.33.md} +0 -0
- /package/docs/{RELEASE_READINESS_SUMMARY.md → releases/RELEASE_READINESS_SUMMARY.md} +0 -0
- /package/docs/{RELEASE_SUMMARY_v2.7.33.md → releases/RELEASE_SUMMARY_v2.7.33.md} +0 -0
- /package/docs/{V2.7.14_RELEASE_NOTES.md → releases/V2.7.14_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.25_RELEASE_NOTES.md → releases/V2.7.25_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.26_RELEASE_SUMMARY.md → releases/V2.7.26_RELEASE_SUMMARY.md} +0 -0
- /package/docs/{V2.7.27_RELEASE_NOTES.md → releases/V2.7.27_RELEASE_NOTES.md} +0 -0
- /package/docs/{V2.7.28_RELEASE_NOTES.md → releases/V2.7.28_RELEASE_NOTES.md} +0 -0
- /package/docs/{AGENTIC_FLOW_INTEGRATION_REVIEW.md → reviews/AGENTIC_FLOW_INTEGRATION_REVIEW.md} +0 -0
- /package/docs/{BRANCH_REVIEW_SUMMARY.md → reviews/BRANCH_REVIEW_SUMMARY.md} +0 -0
- /package/docs/{DEEP_CODE_REVIEW_v2.7.33.md → reviews/DEEP_CODE_REVIEW_v2.7.33.md} +0 -0
- /package/docs/{LATEST_LIBRARIES_REVIEW.md → reviews/LATEST_LIBRARIES_REVIEW.md} +0 -0
- /package/docs/{REGRESSION_TEST_REPORT_v2.7.33.md → testing/REGRESSION_TEST_REPORT_v2.7.33.md} +0 -0
- /package/docs/{V2.7.27_TEST_REPORT.md → testing/V2.7.27_TEST_REPORT.md} +0 -0
- /package/docs/{regression-analysis-phase-1-2.md → testing/regression-analysis-phase-1-2.md} +0 -0
- /package/docs/{TRANSFORMER_INITIALIZATION_ISSUE.md → troubleshooting/TRANSFORMER_INITIALIZATION_ISSUE.md} +0 -0
- /package/docs/{FIX_VERIFICATION_MEMORY_STATS.md → validation/FIX_VERIFICATION_MEMORY_STATS.md} +0 -0
- /package/docs/{TOOL_VALIDATION_REPORT.md → validation/TOOL_VALIDATION_REPORT.md} +0 -0
- /package/docs/{VALIDATION_REPORT_v2.7.1.md → validation/VALIDATION_REPORT_v2.7.1.md} +0 -0
|
@@ -4,42 +4,64 @@ import { createSwarmCommands } from './swarm-commands.js';
|
|
|
4
4
|
import { createSparcEnvironment } from './sparc-environment.js';
|
|
5
5
|
import { createClaudeConfig } from './claude-config.js';
|
|
6
6
|
import { createBatchToolsGuide } from './batch-tools.js';
|
|
7
|
+
import { errorRecovery } from '../../utils/error-recovery.js';
|
|
7
8
|
export async function initCommand(options = {}) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
9
|
+
return errorRecovery.retryWithRecovery(async ()=>{
|
|
10
|
+
try {
|
|
11
|
+
const fs = await import('fs/promises');
|
|
12
|
+
const path = await import('path');
|
|
13
|
+
printSuccess('Initializing Claude-Flow project...');
|
|
14
|
+
if (errorRecovery.isWSL()) {
|
|
15
|
+
console.log('🔍 WSL environment detected');
|
|
16
|
+
const wslCheck = await errorRecovery.recoverWSLErrors();
|
|
17
|
+
if (wslCheck.recovered) {
|
|
18
|
+
console.log('✅ WSL environment optimized\n');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
console.log('\n📁 Phase 1: Creating directory structure...');
|
|
22
|
+
await createDirectoryStructure();
|
|
23
|
+
console.log('\n⚙️ Phase 2: Creating configuration...');
|
|
24
|
+
await createClaudeConfig(options);
|
|
25
|
+
console.log('\n🤖 Phase 3: Creating swarm commands...');
|
|
26
|
+
await createSwarmCommands();
|
|
27
|
+
console.log('\n🔧 Phase 4: Creating batch tools guides...');
|
|
28
|
+
await createBatchToolsGuide();
|
|
29
|
+
if (options.sparc) {
|
|
30
|
+
console.log('\n🚀 Phase 5: Creating SPARC environment...');
|
|
31
|
+
await createSparcEnvironment();
|
|
32
|
+
}
|
|
33
|
+
console.log('\n🎉 Project initialized successfully!');
|
|
34
|
+
console.log(' 📁 Created .claude/ directory structure');
|
|
35
|
+
console.log(' 📋 Created comprehensive swarm command documentation');
|
|
36
|
+
console.log(' 🔧 Created batch tools coordination guides');
|
|
37
|
+
console.log(' 📖 Created detailed usage examples with orchestration');
|
|
38
|
+
console.log('\n Next steps:');
|
|
39
|
+
console.log(' 1. Run "claude-flow swarm --help" to see swarm options');
|
|
40
|
+
console.log(' 2. Check .claude/commands/swarm/ for detailed documentation');
|
|
41
|
+
console.log(' 3. Review batch tools guide for orchestration patterns');
|
|
42
|
+
console.log(' 4. Run "claude-flow help" for all available commands');
|
|
43
|
+
if (options.sparc) {
|
|
44
|
+
console.log(' 5. Run "claude-flow sparc modes" to see available SPARC modes');
|
|
45
|
+
console.log(' 6. Use TodoWrite/TodoRead for task coordination');
|
|
46
|
+
console.log(' 7. Use Task tool for parallel agent execution');
|
|
47
|
+
}
|
|
48
|
+
} catch (error) {
|
|
49
|
+
const recovery = await errorRecovery.recoverInitErrors(error);
|
|
50
|
+
if (recovery.recovered) {
|
|
51
|
+
console.log('✅ Recovered from error, retrying initialization...\n');
|
|
52
|
+
throw error;
|
|
53
|
+
} else {
|
|
54
|
+
printError(`Failed to initialize project: ${error instanceof Error ? error.message : String(error)}`);
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
23
57
|
}
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
console.log('\n Next steps:');
|
|
30
|
-
console.log(' 1. Run "claude-flow swarm --help" to see swarm options');
|
|
31
|
-
console.log(' 2. Check .claude/commands/swarm/ for detailed documentation');
|
|
32
|
-
console.log(' 3. Review batch tools guide for orchestration patterns');
|
|
33
|
-
console.log(' 4. Run "claude-flow help" for all available commands');
|
|
34
|
-
if (options.sparc) {
|
|
35
|
-
console.log(' 5. Run "claude-flow sparc modes" to see available SPARC modes');
|
|
36
|
-
console.log(' 6. Use TodoWrite/TodoRead for task coordination');
|
|
37
|
-
console.log(' 7. Use Task tool for parallel agent execution');
|
|
58
|
+
}, {
|
|
59
|
+
maxRetries: options.force ? 5 : 3,
|
|
60
|
+
delay: 1000,
|
|
61
|
+
onRetry: (attempt, error)=>{
|
|
62
|
+
console.log(`\n🔄 Retry attempt ${attempt} after error recovery...`);
|
|
38
63
|
}
|
|
39
|
-
}
|
|
40
|
-
printError(`Failed to initialize project: ${error instanceof Error ? error.message : String(error)}`);
|
|
41
|
-
throw error;
|
|
42
|
-
}
|
|
64
|
+
});
|
|
43
65
|
}
|
|
44
66
|
|
|
45
67
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/cli/init/index.ts"],"sourcesContent":["// init/index.ts - Main init command orchestrator\nimport { printSuccess, printError } from '../utils.js';\nimport { createDirectoryStructure } from './directory-structure.js';\nimport { createSwarmCommands } from './swarm-commands.js';\nimport { createSparcEnvironment } from './sparc-environment.js';\nimport { createClaudeConfig } from './claude-config.js';\nimport { createBatchToolsGuide } from './batch-tools.js';\n\nexport interface InitOptions {\n sparc?: boolean;\n force?: boolean;\n}\n\nexport async function initCommand(options: InitOptions = {}) {\n try {\n
|
|
1
|
+
{"version":3,"sources":["../../../../src/cli/init/index.ts"],"sourcesContent":["// init/index.ts - Main init command orchestrator\nimport { printSuccess, printError } from '../utils.js';\nimport { createDirectoryStructure } from './directory-structure.js';\nimport { createSwarmCommands } from './swarm-commands.js';\nimport { createSparcEnvironment } from './sparc-environment.js';\nimport { createClaudeConfig } from './claude-config.js';\nimport { createBatchToolsGuide } from './batch-tools.js';\nimport { errorRecovery } from '../../utils/error-recovery.js';\n\nexport interface InitOptions {\n sparc?: boolean;\n force?: boolean;\n}\n\nexport async function initCommand(options: InitOptions = {}) {\n // Wrap entire initialization in retry logic with automatic recovery\n return errorRecovery.retryWithRecovery(\n async () => {\n try {\n const fs = await import('fs/promises');\n const path = await import('path');\n\n printSuccess('Initializing Claude-Flow project...');\n\n // Check WSL environment and apply fixes proactively\n if (errorRecovery.isWSL()) {\n console.log('🔍 WSL environment detected');\n const wslCheck = await errorRecovery.recoverWSLErrors();\n if (wslCheck.recovered) {\n console.log('✅ WSL environment optimized\\n');\n }\n }\n\n // Phase 1: Create directory structure\n console.log('\\n📁 Phase 1: Creating directory structure...');\n await createDirectoryStructure();\n\n // Phase 2: Create base configuration\n console.log('\\n⚙️ Phase 2: Creating configuration...');\n await createClaudeConfig(options);\n\n // Phase 3: Create swarm commands and documentation\n console.log('\\n🤖 Phase 3: Creating swarm commands...');\n await createSwarmCommands();\n\n // Phase 4: Create batch tools guides\n console.log('\\n🔧 Phase 4: Creating batch tools guides...');\n await createBatchToolsGuide();\n\n // Phase 5: SPARC environment (if requested)\n if (options.sparc) {\n console.log('\\n🚀 Phase 5: Creating SPARC environment...');\n await createSparcEnvironment();\n }\n\n // Success summary\n console.log('\\n🎉 Project initialized successfully!');\n console.log(' 📁 Created .claude/ directory structure');\n console.log(' 📋 Created comprehensive swarm command documentation');\n console.log(' 🔧 Created batch tools coordination guides');\n console.log(' 📖 Created detailed usage examples with orchestration');\n\n console.log('\\n Next steps:');\n console.log(' 1. Run \"claude-flow swarm --help\" to see swarm options');\n console.log(' 2. Check .claude/commands/swarm/ for detailed documentation');\n console.log(' 3. Review batch tools guide for orchestration patterns');\n console.log(' 4. Run \"claude-flow help\" for all available commands');\n\n if (options.sparc) {\n console.log(' 5. Run \"claude-flow sparc modes\" to see available SPARC modes');\n console.log(' 6. Use TodoWrite/TodoRead for task coordination');\n console.log(' 7. Use Task tool for parallel agent execution');\n }\n } catch (error) {\n // Attempt automatic error recovery\n const recovery = await errorRecovery.recoverInitErrors(error);\n\n if (recovery.recovered) {\n console.log('✅ Recovered from error, retrying initialization...\\n');\n throw error; // Trigger retry\n } else {\n printError(\n `Failed to initialize project: ${error instanceof Error ? error.message : String(error)}`,\n );\n throw error;\n }\n }\n },\n {\n maxRetries: options.force ? 5 : 3,\n delay: 1000,\n onRetry: (attempt, error) => {\n console.log(`\\n🔄 Retry attempt ${attempt} after error recovery...`);\n }\n }\n );\n}\n"],"names":["printSuccess","printError","createDirectoryStructure","createSwarmCommands","createSparcEnvironment","createClaudeConfig","createBatchToolsGuide","errorRecovery","initCommand","options","retryWithRecovery","fs","path","isWSL","console","log","wslCheck","recoverWSLErrors","recovered","sparc","error","recovery","recoverInitErrors","Error","message","String","maxRetries","force","delay","onRetry","attempt"],"mappings":"A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C;YACd;QACF,EAAE,OAAOK,OAAO;YAEd,MAAMC,WAAW,MAAMd,cAAce,iBAAiB,CAACF;YAEvD,IAAIC,SAASH,SAAS,EAAE;gBACtBJ,QAAQC,GAAG,CAAC;gBACZ,MAAMK;YACR,OAAO;gBACLnB,WACE,CAAC,8BAA8B,EAAEmB,iBAAiBG,QAAQH,MAAMI,OAAO,GAAGC,OAAOL,QAAQ;gBAE3F,MAAMA;YACR;QACF;IACF,GACA;QACEM,YAAYjB,QAAQkB,KAAK,GAAG,IAAI;QAChCC,OAAO;QACPC,SAAS,CAACC,SAASV;YACjBN,QAAQC,GAAG,CAAC,CAAC,mBAAmB,EAAEe,QAAQ,wBAAwB,CAAC;QACrE;IACF;AAEJ"}
|
|
@@ -6,7 +6,7 @@ const __dirname = dirname(__filename);
|
|
|
6
6
|
export async function copySkillFiles(targetDir, options = {}) {
|
|
7
7
|
console.log(' 🚀 copySkillFiles function called');
|
|
8
8
|
console.log(` 📂 Target directory: ${targetDir}`);
|
|
9
|
-
console.log(` ⚙️ Options
|
|
9
|
+
console.log(` ⚙️ Options: { force: ${options.force || 'false'}, dryRun: ${options.dryRun || 'false'} }`);
|
|
10
10
|
console.log(` 📍 __dirname: ${__dirname}`);
|
|
11
11
|
const { force = false, dryRun = false } = options;
|
|
12
12
|
const packageSkillsDir = join(__dirname, '../../../../.claude/skills');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/cli/simple-commands/init/skills-copier.js"],"sourcesContent":["// skills-copier.js - Copy all skill files during initialization\nimport { promises as fs } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Copy all skill files from the installed package to project directory\n */\nexport async function copySkillFiles(targetDir, options = {}) {\n console.log(' 🚀 copySkillFiles function called');\n console.log(` 📂 Target directory: ${targetDir}`);\n console.log(` ⚙️ Options:`, options);\n console.log(` 📍 __dirname: ${__dirname}`);\n\n const { force = false, dryRun = false } = options;\n\n // Path to skill files - try multiple locations\n // From npm package: src/cli/simple-commands/init/ -> root = ../../../../\n const packageSkillsDir = join(__dirname, '../../../../.claude/skills');\n const localSkillsDir = join(__dirname, '../../../../../.claude/skills'); // Local development (one more level up)\n const globalNpmSkillsDir = '/usr/local/lib/node_modules/claude-flow/.claude/skills'; // Global npm install\n\n let sourceSkillsDir;\n\n // Try package location first (most common for npm installs), then local dev, then global npm\n const locationsToTry = [\n { path: packageSkillsDir, label: 'packaged skill files' },\n { path: localSkillsDir, label: 'local development skill files' },\n { path: globalNpmSkillsDir, label: 'global npm skill files' }\n ];\n\n for (const location of locationsToTry) {\n try {\n console.log(` 🔍 Checking: ${location.path}`);\n await fs.access(location.path);\n // Verify it's actually a directory with skills\n const items = await fs.readdir(location.path);\n console.log(` 📊 Found ${items.length} items at ${location.path}`);\n if (items.length > 0) {\n sourceSkillsDir = location.path;\n console.log(` 📁 Using ${location.label}`);\n console.log(` 📍 Path: ${location.path}`);\n break;\n }\n } catch (err) {\n console.log(` ❌ Failed to access ${location.path}: ${err.message}`);\n // Try next location\n continue;\n }\n }\n\n if (!sourceSkillsDir) {\n console.log(' ⚠️ No skill files found in any location');\n console.log(' 🔍 Searched locations:');\n locationsToTry.forEach(loc => console.log(` - ${loc.path}`));\n return { success: false, error: 'Skill files not found' };\n }\n\n const targetSkillsDir = join(targetDir, '.claude/skills');\n\n console.log('📁 Copying skill system files...');\n console.log(` 📂 Source: ${sourceSkillsDir}`);\n console.log(` 📂 Target: ${targetSkillsDir}`);\n\n try {\n // Create target directory\n if (!dryRun) {\n await fs.mkdir(targetSkillsDir, { recursive: true });\n }\n\n const copiedFiles = [];\n const errors = [];\n\n // Recursively copy all skill files\n async function copyRecursive(srcDir, destDir) {\n const items = await fs.readdir(srcDir, { withFileTypes: true });\n\n for (const item of items) {\n const srcPath = join(srcDir, item.name);\n const destPath = join(destDir, item.name);\n\n if (item.isDirectory()) {\n if (!dryRun) {\n await fs.mkdir(destPath, { recursive: true });\n }\n await copyRecursive(srcPath, destPath);\n } else if (item.isFile() && item.name.endsWith('.md')) {\n try {\n // Check if file already exists\n let shouldCopy = force;\n if (!force) {\n try {\n await fs.access(destPath);\n // File exists, skip unless force is true\n continue;\n } catch {\n // File doesn't exist, safe to copy\n shouldCopy = true;\n }\n }\n\n if (shouldCopy && !dryRun) {\n const content = await fs.readFile(srcPath, 'utf8');\n await fs.writeFile(destPath, content, 'utf8');\n copiedFiles.push(destPath.replace(targetDir + '/', ''));\n } else if (dryRun) {\n copiedFiles.push(destPath.replace(targetDir + '/', ''));\n }\n } catch (err) {\n errors.push(`Failed to copy ${item.name}: ${err.message}`);\n }\n }\n }\n }\n\n await copyRecursive(sourceSkillsDir, targetSkillsDir);\n\n if (!dryRun && copiedFiles.length > 0) {\n console.log(` ✅ Copied ${copiedFiles.length} skill files`);\n console.log(' 📋 Skill system initialized');\n console.log(' 🎯 Available skills: skill-builder');\n } else if (dryRun) {\n console.log(` [DRY RUN] Would copy ${copiedFiles.length} skill files`);\n }\n\n if (errors.length > 0) {\n console.log(' ⚠️ Some skill files could not be copied:');\n errors.forEach(error => console.log(` - ${error}`));\n }\n\n return {\n success: true,\n copiedFiles,\n errors,\n totalSkills: copiedFiles.filter(f => f.includes('SKILL.md')).length\n };\n\n } catch (err) {\n console.log(` ❌ Failed to copy skill files: ${err.message}`);\n return {\n success: false,\n error: err.message,\n copiedFiles: [],\n errors: [err.message]\n };\n }\n}\n\n/**\n * Create skill directories structure\n */\nexport async function createSkillDirectories(targetDir, dryRun = false) {\n const skillDirs = [\n '.claude/skills',\n ];\n\n if (dryRun) {\n console.log(` [DRY RUN] Would create ${skillDirs.length} skill directories`);\n return;\n }\n\n for (const dir of skillDirs) {\n await fs.mkdir(join(targetDir, dir), { recursive: true });\n }\n\n console.log(` ✅ Created ${skillDirs.length} skill directories`);\n}\n\n/**\n * Validate skill system after copying\n */\nexport async function validateSkillSystem(targetDir) {\n const skillsDir = join(targetDir, '.claude/skills');\n\n try {\n const items = await fs.readdir(skillsDir, { withFileTypes: true });\n const skillDirs = items.filter(item => item.isDirectory());\n\n let totalSkills = 0;\n const skillNames = [];\n\n for (const skillDir of skillDirs) {\n const skillPath = join(skillsDir, skillDir.name);\n const skillMdPath = join(skillPath, 'SKILL.md');\n\n try {\n await fs.access(skillMdPath);\n totalSkills++;\n skillNames.push(skillDir.name);\n } catch {\n // No SKILL.md, not a valid skill\n }\n }\n\n console.log(' 🔍 Skill system validation:');\n console.log(` • Total skills: ${totalSkills}`);\n console.log(` • Skills: ${skillNames.join(', ')}`);\n\n return {\n valid: totalSkills > 0, // Should have at least 1 skill\n totalSkills,\n skillNames\n };\n\n } catch (err) {\n console.log(` ⚠️ Skill system validation failed: ${err.message}`);\n return {\n valid: false,\n error: err.message\n };\n }\n}\n"],"names":["promises","fs","join","dirname","fileURLToPath","__filename","url","__dirname","copySkillFiles","targetDir","options","console","log","force","dryRun","packageSkillsDir","localSkillsDir","globalNpmSkillsDir","sourceSkillsDir","locationsToTry","path","label","location","access","items","readdir","length","err","message","forEach","loc","success","error","targetSkillsDir","mkdir","recursive","copiedFiles","errors","copyRecursive","srcDir","destDir","withFileTypes","item","srcPath","name","destPath","isDirectory","isFile","endsWith","shouldCopy","content","readFile","writeFile","push","replace","totalSkills","filter","f","includes","createSkillDirectories","skillDirs","dir","validateSkillSystem","skillsDir","skillNames","skillDir","skillPath","skillMdPath","valid"],"mappings":"AACA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,SAASC,IAAI,EAAEC,OAAO,QAAQ,OAAO;AACrC,SAASC,aAAa,QAAQ,MAAM;AAEpC,MAAMC,aAAaD,cAAc,YAAYE,GAAG;AAChD,MAAMC,YAAYJ,QAAQE;AAK1B,OAAO,eAAeG,eAAeC,SAAS,EAAEC,UAAU,CAAC,CAAC;IAC1DC,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC,CAAC,uBAAuB,EAAEH,WAAW;IACj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{"version":3,"sources":["../../../../../src/cli/simple-commands/init/skills-copier.js"],"sourcesContent":["// skills-copier.js - Copy all skill files during initialization\nimport { promises as fs } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Copy all skill files from the installed package to project directory\n */\nexport async function copySkillFiles(targetDir, options = {}) {\n console.log(' 🚀 copySkillFiles function called');\n console.log(` 📂 Target directory: ${targetDir}`);\n console.log(` ⚙️ Options: { force: ${options.force || 'false'}, dryRun: ${options.dryRun || 'false'} }`);\n console.log(` 📍 __dirname: ${__dirname}`);\n\n const { force = false, dryRun = false } = options;\n\n // Path to skill files - try multiple locations\n // From npm package: src/cli/simple-commands/init/ -> root = ../../../../\n const packageSkillsDir = join(__dirname, '../../../../.claude/skills');\n const localSkillsDir = join(__dirname, '../../../../../.claude/skills'); // Local development (one more level up)\n const globalNpmSkillsDir = '/usr/local/lib/node_modules/claude-flow/.claude/skills'; // Global npm install\n\n let sourceSkillsDir;\n\n // Try package location first (most common for npm installs), then local dev, then global npm\n const locationsToTry = [\n { path: packageSkillsDir, label: 'packaged skill files' },\n { path: localSkillsDir, label: 'local development skill files' },\n { path: globalNpmSkillsDir, label: 'global npm skill files' }\n ];\n\n for (const location of locationsToTry) {\n try {\n console.log(` 🔍 Checking: ${location.path}`);\n await fs.access(location.path);\n // Verify it's actually a directory with skills\n const items = await fs.readdir(location.path);\n console.log(` 📊 Found ${items.length} items at ${location.path}`);\n if (items.length > 0) {\n sourceSkillsDir = location.path;\n console.log(` 📁 Using ${location.label}`);\n console.log(` 📍 Path: ${location.path}`);\n break;\n }\n } catch (err) {\n console.log(` ❌ Failed to access ${location.path}: ${err.message}`);\n // Try next location\n continue;\n }\n }\n\n if (!sourceSkillsDir) {\n console.log(' ⚠️ No skill files found in any location');\n console.log(' 🔍 Searched locations:');\n locationsToTry.forEach(loc => console.log(` - ${loc.path}`));\n return { success: false, error: 'Skill files not found' };\n }\n\n const targetSkillsDir = join(targetDir, '.claude/skills');\n\n console.log('📁 Copying skill system files...');\n console.log(` 📂 Source: ${sourceSkillsDir}`);\n console.log(` 📂 Target: ${targetSkillsDir}`);\n\n try {\n // Create target directory\n if (!dryRun) {\n await fs.mkdir(targetSkillsDir, { recursive: true });\n }\n\n const copiedFiles = [];\n const errors = [];\n\n // Recursively copy all skill files\n async function copyRecursive(srcDir, destDir) {\n const items = await fs.readdir(srcDir, { withFileTypes: true });\n\n for (const item of items) {\n const srcPath = join(srcDir, item.name);\n const destPath = join(destDir, item.name);\n\n if (item.isDirectory()) {\n if (!dryRun) {\n await fs.mkdir(destPath, { recursive: true });\n }\n await copyRecursive(srcPath, destPath);\n } else if (item.isFile() && item.name.endsWith('.md')) {\n try {\n // Check if file already exists\n let shouldCopy = force;\n if (!force) {\n try {\n await fs.access(destPath);\n // File exists, skip unless force is true\n continue;\n } catch {\n // File doesn't exist, safe to copy\n shouldCopy = true;\n }\n }\n\n if (shouldCopy && !dryRun) {\n const content = await fs.readFile(srcPath, 'utf8');\n await fs.writeFile(destPath, content, 'utf8');\n copiedFiles.push(destPath.replace(targetDir + '/', ''));\n } else if (dryRun) {\n copiedFiles.push(destPath.replace(targetDir + '/', ''));\n }\n } catch (err) {\n errors.push(`Failed to copy ${item.name}: ${err.message}`);\n }\n }\n }\n }\n\n await copyRecursive(sourceSkillsDir, targetSkillsDir);\n\n if (!dryRun && copiedFiles.length > 0) {\n console.log(` ✅ Copied ${copiedFiles.length} skill files`);\n console.log(' 📋 Skill system initialized');\n console.log(' 🎯 Available skills: skill-builder');\n } else if (dryRun) {\n console.log(` [DRY RUN] Would copy ${copiedFiles.length} skill files`);\n }\n\n if (errors.length > 0) {\n console.log(' ⚠️ Some skill files could not be copied:');\n errors.forEach(error => console.log(` - ${error}`));\n }\n\n return {\n success: true,\n copiedFiles,\n errors,\n totalSkills: copiedFiles.filter(f => f.includes('SKILL.md')).length\n };\n\n } catch (err) {\n console.log(` ❌ Failed to copy skill files: ${err.message}`);\n return {\n success: false,\n error: err.message,\n copiedFiles: [],\n errors: [err.message]\n };\n }\n}\n\n/**\n * Create skill directories structure\n */\nexport async function createSkillDirectories(targetDir, dryRun = false) {\n const skillDirs = [\n '.claude/skills',\n ];\n\n if (dryRun) {\n console.log(` [DRY RUN] Would create ${skillDirs.length} skill directories`);\n return;\n }\n\n for (const dir of skillDirs) {\n await fs.mkdir(join(targetDir, dir), { recursive: true });\n }\n\n console.log(` ✅ Created ${skillDirs.length} skill directories`);\n}\n\n/**\n * Validate skill system after copying\n */\nexport async function validateSkillSystem(targetDir) {\n const skillsDir = join(targetDir, '.claude/skills');\n\n try {\n const items = await fs.readdir(skillsDir, { withFileTypes: true });\n const skillDirs = items.filter(item => item.isDirectory());\n\n let totalSkills = 0;\n const skillNames = [];\n\n for (const skillDir of skillDirs) {\n const skillPath = join(skillsDir, skillDir.name);\n const skillMdPath = join(skillPath, 'SKILL.md');\n\n try {\n await fs.access(skillMdPath);\n totalSkills++;\n skillNames.push(skillDir.name);\n } catch {\n // No SKILL.md, not a valid skill\n }\n }\n\n console.log(' 🔍 Skill system validation:');\n console.log(` • Total skills: ${totalSkills}`);\n console.log(` • Skills: ${skillNames.join(', ')}`);\n\n return {\n valid: totalSkills > 0, // Should have at least 1 skill\n totalSkills,\n skillNames\n };\n\n } catch (err) {\n console.log(` ⚠️ Skill system validation failed: ${err.message}`);\n return {\n valid: false,\n error: err.message\n };\n }\n}\n"],"names":["promises","fs","join","dirname","fileURLToPath","__filename","url","__dirname","copySkillFiles","targetDir","options","console","log","force","dryRun","packageSkillsDir","localSkillsDir","globalNpmSkillsDir","sourceSkillsDir","locationsToTry","path","label","location","access","items","readdir","length","err","message","forEach","loc","success","error","targetSkillsDir","mkdir","recursive","copiedFiles","errors","copyRecursive","srcDir","destDir","withFileTypes","item","srcPath","name","destPath","isDirectory","isFile","endsWith","shouldCopy","content","readFile","writeFile","push","replace","totalSkills","filter","f","includes","createSkillDirectories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C4C;gBAChBZ;gBACAS,WAAWX,IAAI,CAACY,SAASrB,IAAI;YAC/B,EAAE,OAAM,CAER;QACF;QAEAjC,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC,CAAC,oBAAoB,EAAE2C,aAAa;QAChD5C,QAAQC,GAAG,CAAC,CAAC,cAAc,EAAEoD,WAAW9D,IAAI,CAAC,OAAO;QAEpD,OAAO;YACLkE,OAAOb,cAAc;YACrBA;YACAS;QACF;IAEF,EAAE,OAAOrC,KAAK;QACZhB,QAAQC,GAAG,CAAC,CAAC,sCAAsC,EAAEe,IAAIC,OAAO,EAAE;QAClE,OAAO;YACLwC,OAAO;YACPpC,OAAOL,IAAIC,OAAO;QACpB;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cli/simple-orchestrator.ts"],"sourcesContent":["/**\n * Simple orchestrator implementation for Node.js compatibility\n */\n\nimport { EventEmitter } from 'events';\nimport express from 'express';\nimport { WebSocketServer } from 'ws';\nimport { createServer } from 'http';\nimport { spawn } from 'child_process';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport cors from 'cors';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Simple in-memory stores\nconst agents = new Map();\nconst tasks = new Map();\nconst memory = new Map();\n\n// Event bus\nconst eventBus = new EventEmitter();\n\n// Component status\nconst componentStatus = {\n eventBus: false,\n orchestrator: false,\n memoryManager: false,\n terminalPool: false,\n mcpServer: false,\n coordinationManager: false,\n webUI: false,\n};\n\n// Simple MCP server\nfunction startMCPServer(port: number) {\n console.log(`🌐 Starting MCP server on port ${port}...`);\n // In a real implementation, this would start the actual MCP server\n componentStatus.mcpServer = true;\n return true;\n}\n\n// Enhanced web UI with console interface\nfunction startWebUI(host: string, port: number) {\n const app = express();\n const server = createServer(app);\n const wss = new WebSocketServer({ server });\n\n // Add CORS middleware for cross-origin support\n app.use(\n cors({\n origin: '*',\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n }),\n );\n\n // Global error handler middleware\n app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {\n console.error('Global error handler:', err);\n res.status(err.status || 500).json({\n error: err.message || 'Internal server error',\n timestamp: new Date().toISOString(),\n });\n });\n\n // Request logging middleware\n app.use((req, res, next) => {\n console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);\n next();\n });\n\n // Store CLI output history and active connections\n const outputHistory: string[] = [];\n const activeConnections: Set<any> = new Set();\n\n // CLI output capture system\n let cliProcess: any = null;\n\n const consoleHTML = `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Claude-Flow Console</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n body {\n font-family: 'Consolas', 'Monaco', 'Courier New', monospace;\n background: #0d1117;\n color: #c9d1d9;\n height: 100vh;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .header {\n background: #161b22;\n border-bottom: 1px solid #21262d;\n padding: 10px 20px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n }\n .title {\n font-weight: bold;\n color: #58a6ff;\n }\n .connection-status {\n font-size: 12px;\n color: #7c3aed;\n }\n .console-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .console-output {\n flex: 1;\n overflow-y: auto;\n padding: 10px;\n background: #0d1117;\n font-size: 13px;\n line-height: 1.4;\n white-space: pre-wrap;\n word-wrap: break-word;\n }\n .console-input {\n background: #161b22;\n border: none;\n border-top: 1px solid #21262d;\n padding: 10px;\n color: #c9d1d9;\n font-family: inherit;\n font-size: 13px;\n outline: none;\n }\n .console-input:focus {\n background: #21262d;\n }\n .prompt {\n color: #58a6ff;\n font-weight: bold;\n }\n .error {\n color: #ff7b72;\n }\n .success {\n color: #3fb950;\n }\n .warning {\n color: #ffa657;\n }\n .info {\n color: #79c0ff;\n }\n .dim {\n color: #8b949e;\n }\n .scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #21262d #0d1117;\n }\n .scrollbar::-webkit-scrollbar {\n width: 8px;\n }\n .scrollbar::-webkit-scrollbar-track {\n background: #0d1117;\n }\n .scrollbar::-webkit-scrollbar-thumb {\n background: #21262d;\n border-radius: 4px;\n }\n .scrollbar::-webkit-scrollbar-thumb:hover {\n background: #30363d;\n }\n .system-status {\n display: flex;\n gap: 15px;\n font-size: 11px;\n }\n .status-item {\n display: flex;\n align-items: center;\n gap: 5px;\n }\n .status-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #3fb950;\n }\n .status-dot.inactive {\n background: #f85149;\n }\n </style>\n </head>\n <body>\n <div class=\"header\">\n <div class=\"title\">🧠 Claude-Flow Console</div>\n <div class=\"system-status\">\n <div class=\"status-item\">\n <div class=\"status-dot\" id=\"ws-status\"></div>\n <span id=\"ws-text\">Connecting...</span>\n </div>\n <div class=\"status-item\">\n <div class=\"status-dot\" id=\"cli-status\"></div>\n <span id=\"cli-text\">CLI Ready</span>\n </div>\n </div>\n </div>\n <div class=\"console-container\">\n <div class=\"console-output scrollbar\" id=\"output\"></div>\n <input type=\"text\" class=\"console-input\" id=\"input\" placeholder=\"Enter claude-flow command...\" autocomplete=\"off\">\n </div>\n\n <script>\n const output = document.getElementById('output');\n const input = document.getElementById('input');\n const wsStatus = document.getElementById('ws-status');\n const wsText = document.getElementById('ws-text');\n const cliStatus = document.getElementById('cli-status');\n const cliText = document.getElementById('cli-text');\n \n let ws = null;\n let commandHistory = [];\n let historyIndex = -1;\n let reconnectAttempts = 0;\n let reconnectTimer = null;\n let isReconnecting = false;\n const MAX_RECONNECT_ATTEMPTS = 10;\n const BASE_RECONNECT_DELAY = 1000;\n \n function getReconnectDelay() {\n // Exponential backoff with jitter\n const exponentialDelay = Math.min(BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts), 30000);\n const jitter = Math.random() * 0.3 * exponentialDelay;\n return exponentialDelay + jitter;\n }\n \n function connect() {\n if (isReconnecting || (ws && ws.readyState === WebSocket.CONNECTING)) {\n console.log('Already connecting, skipping duplicate attempt');\n return;\n }\n \n isReconnecting = true;\n const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';\n const wsUrl = \\`\\${protocol}//\\${window.location.host}\\`;\n \n try {\n console.log(\\`Attempting WebSocket connection to \\${wsUrl}\\`);\n ws = new WebSocket(wsUrl);\n \n ws.onopen = () => {\n console.log('WebSocket connected successfully');\n wsStatus.classList.remove('inactive');\n wsText.textContent = 'Connected';\n reconnectAttempts = 0;\n isReconnecting = false;\n \n if (reconnectTimer) {\n clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n \n appendOutput('\\n<span class=\"success\">🔗 Connected to Claude-Flow Console</span>\\n');\n appendOutput('<span class=\"info\">Type \"help\" for available commands or use any claude-flow command</span>\\n\\n');\n };\n \n ws.onmessage = (event) => {\n try {\n const data = JSON.parse(event.data);\n handleMessage(data);\n } catch (error) {\n console.error('Failed to parse WebSocket message:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ Invalid message received: \\${(error instanceof Error ? error.message : String(error))}</span>\\n\\`);\n }\n };\n \n ws.onclose = (event) => {\n console.log(\\`WebSocket closed: code=\\${event.code}, reason=\\${event.reason}\\`);\n wsStatus.classList.add('inactive');\n wsText.textContent = 'Disconnected';\n isReconnecting = false;\n \n if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {\n reconnectAttempts++;\n const delay = getReconnectDelay();\n appendOutput(\\`\\n<span class=\"error\">🔗 Connection lost. Reconnecting in \\${Math.round(delay/1000)}s... (attempt \\${reconnectAttempts}/\\${MAX_RECONNECT_ATTEMPTS})</span>\\n\\`);\n \n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n connect();\n }, delay);\n } else {\n appendOutput(\\`\\n<span class=\"error\">❌ Failed to reconnect after \\${MAX_RECONNECT_ATTEMPTS} attempts. Please refresh the page.</span>\\n\\`);\n wsText.textContent = 'Failed to connect';\n }\n };\n \n ws.onerror = (error) => {\n console.error('WebSocket error:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ WebSocket error: \\${(error instanceof Error ? error.message : String(error)) || 'Connection failed'}</span>\\n\\`);\n isReconnecting = false;\n };\n \n } catch (error) {\n console.error('Failed to create WebSocket:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ Failed to create WebSocket connection: \\${(error instanceof Error ? error.message : String(error))}</span>\\n\\`);\n isReconnecting = false;\n \n // Try reconnect if not exceeded max attempts\n if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {\n reconnectAttempts++;\n const delay = getReconnectDelay();\n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n connect();\n }, delay);\n }\n }\n }\n \n function handleMessage(data) {\n switch (data.type) {\n case 'output':\n appendOutput(data.data);\n break;\n case 'error':\n appendOutput('<span class=\"error\">' + data.data + '</span>');\n break;\n case 'command_complete':\n appendOutput('\\n<span class=\"prompt\">claude-flow> </span>');\n break;\n case 'status':\n updateStatus(data.data);\n break;\n }\n }\n \n function appendOutput(text) {\n output.innerHTML += text;\n output.scrollTop = output.scrollHeight;\n }\n \n function updateStatus(status) {\n // Update CLI status based on server response\n if (status.cliActive) {\n cliStatus.classList.remove('inactive');\n cliText.textContent = 'CLI Active';\n } else {\n cliStatus.classList.add('inactive');\n cliText.textContent = 'CLI Inactive';\n }\n }\n \n function sendCommand(command) {\n if (ws && ws.readyState === WebSocket.OPEN) {\n appendOutput('<span class=\"prompt\">claude-flow> </span>' + command + '\\n');\n ws.send(JSON.stringify({\n type: 'command',\n data: command\n }));\n \n // Add to history\n if (command.trim() && commandHistory[commandHistory.length - 1] !== command) {\n commandHistory.push(command);\n if (commandHistory.length > 100) {\n commandHistory.shift();\n }\n }\n historyIndex = commandHistory.length;\n }\n }\n \n // Input handling\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') {\n const command = input.value.trim();\n if (command) {\n sendCommand(command);\n input.value = '';\n }\n } else if (e.key === 'ArrowUp') {\n e.preventDefault();\n if (historyIndex > 0) {\n historyIndex--;\n input.value = commandHistory[historyIndex] || '';\n }\n } else if (e.key === 'ArrowDown') {\n e.preventDefault();\n if (historyIndex < commandHistory.length - 1) {\n historyIndex++;\n input.value = commandHistory[historyIndex] || '';\n } else {\n historyIndex = commandHistory.length;\n input.value = '';\n }\n } else if (e.key === 'Tab') {\n e.preventDefault();\n // Basic tab completion for common commands\n const value = input.value;\n const commands = ['help', 'status', 'agent', 'task', 'memory', 'config', 'start', 'stop'];\n const matches = commands.filter(cmd => cmd.startsWith(value));\n if (matches.length === 1) {\n input.value = matches[0] + ' ';\n }\n }\n });\n \n // Focus input on page load\n window.addEventListener('load', () => {\n input.focus();\n connect();\n });\n \n // Implement heartbeat to detect stale connections\n setInterval(() => {\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));\n }\n }, 30000); // Ping every 30 seconds\n \n // Handle page visibility changes\n document.addEventListener('visibilitychange', () => {\n if (!document.hidden && ws && ws.readyState !== WebSocket.OPEN) {\n console.log('Page became visible, checking connection...');\n reconnectAttempts = 0; // Reset attempts when page becomes visible\n connect();\n }\n });\n \n // Keep input focused\n document.addEventListener('click', () => {\n input.focus();\n });\n </script>\n </body>\n </html>\n `;\n\n app.get('/', (req, res) => {\n res.send(consoleHTML);\n });\n\n // API endpoints\n app.get('/api/status', (req, res) => {\n res.json({\n components: componentStatus,\n metrics: {\n agents: agents.size,\n tasks: tasks.size,\n memory: memory.size,\n connectedClients: activeConnections.size,\n },\n });\n });\n\n app.get('/api/history', (req, res) => {\n const limit = parseInt(req.query.limit as string) || 100;\n res.json({\n history: outputHistory.slice(-limit),\n total: outputHistory.length,\n });\n });\n\n app.post('/api/command', express.json(), (req, res) => {\n const { command } = req.body;\n if (!command) {\n res.status(400).json({ error: 'Command is required' });\n return;\n }\n\n // Execute command and return immediately\n // Output will be sent via WebSocket\n try {\n broadcastToClients({\n type: 'output',\n data: `<span class=\"prompt\">API> </span>${command}\\\\n`,\n });\n\n executeCliCommand(command, null);\n\n res.json({ success: true, message: 'Command executed' });\n } catch (error) {\n res.status(500).json({ error: error instanceof Error ? error.message : String(error) });\n }\n });\n\n app.get('/api/agents', (req, res) => {\n const agentList = Array.from(agents.entries()).map(([id, agent]) => ({\n id,\n ...agent,\n }));\n res.json(agentList);\n });\n\n app.get('/api/tasks', (req, res) => {\n const taskList = Array.from(tasks.entries()).map(([id, task]) => ({\n id,\n ...task,\n }));\n res.json(taskList);\n });\n\n app.get('/api/memory', (req, res) => {\n const memoryList = Array.from(memory.entries()).map(([key, value]) => ({\n key,\n value,\n type: typeof value,\n size: JSON.stringify(value).length,\n }));\n res.json(memoryList);\n });\n\n // Health check endpoint\n app.get('/health', (req, res) => {\n res.json({\n status: 'healthy',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n components: componentStatus,\n });\n });\n\n // WebSocket for real-time CLI interaction\n wss.on('connection', (ws, req) => {\n const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;\n console.log(`🔌 WebSocket client connected from ${clientIp}`);\n activeConnections.add(ws);\n\n // Send initial status and history\n ws.send(\n JSON.stringify({\n type: 'status',\n data: { ...componentStatus, cliActive: true },\n }),\n );\n\n // Send recent output history\n outputHistory.slice(-50).forEach((line) => {\n ws.send(\n JSON.stringify({\n type: 'output',\n data: line,\n }),\n );\n });\n\n // Handle incoming commands\n ws.on('message', (message) => {\n try {\n const data = JSON.parse(message.toString());\n console.log(`Received command from client: ${data.type}`);\n\n if (data.type === 'command') {\n handleCliCommand(data.data, ws);\n } else if (data.type === 'ping') {\n // Handle ping/pong for connection keepalive\n ws.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));\n }\n } catch (error) {\n console.error('Failed to handle WebSocket message:', error);\n ws.send(\n JSON.stringify({\n type: 'error',\n data: `Invalid message format: ${error instanceof Error ? error.message : String(error)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n });\n\n ws.on('close', () => {\n console.log('🔌 WebSocket client disconnected');\n activeConnections.delete(ws);\n });\n\n ws.on('error', (error) => {\n console.error('WebSocket client error:', error);\n // Send detailed error information to client before closing\n try {\n ws.send(\n JSON.stringify({\n type: 'error',\n data: `Server WebSocket error: ${(error instanceof Error ? error.message : String(error)) || 'Unknown error'}`,\n timestamp: new Date().toISOString(),\n }),\n );\n } catch (sendError) {\n console.error('Failed to send error to client:', sendError);\n }\n activeConnections.delete(ws);\n });\n });\n\n // Helper function to send response to specific client or broadcast\n function sendResponse(ws: any, data: any) {\n if (ws) {\n ws.send(JSON.stringify(data));\n } else {\n broadcastToClients(data);\n }\n }\n\n // CLI command execution handler\n function handleCliCommand(command: string, ws: any) {\n try {\n // Add timestamp and format output\n const timestamp = new Date().toLocaleTimeString();\n const logEntry = `[${timestamp}] Executing: ${command}`;\n outputHistory.push(logEntry);\n\n // Broadcast to all connected clients\n broadcastToClients({\n type: 'output',\n data: `<span class=\"dim\">[${timestamp}]</span> <span class=\"info\">Executing:</span> ${command}\\\\n`,\n });\n\n // Execute the command\n executeCliCommand(command, ws);\n } catch (error) {\n const errorMsg = `Error executing command: ${error instanceof Error ? error.message : String(error)}`;\n outputHistory.push(errorMsg);\n sendResponse(ws, {\n type: 'error',\n data: errorMsg,\n });\n }\n }\n\n // Execute CLI commands and capture output\n function executeCliCommand(command: string, ws: any) {\n // Handle built-in commands first\n if (command === 'help') {\n const helpText = `<span class=\"success\">Available Commands:</span>\n• <span class=\"info\">help</span> - Show this help message\n• <span class=\"info\">status</span> - Show system status\n• <span class=\"info\">agent list</span> - List all agents\n• <span class=\"info\">agent spawn [type]</span> - Spawn a new agent\n• <span class=\"info\">task list</span> - List all tasks\n• <span class=\"info\">memory list</span> - List memory entries\n• <span class=\"info\">config show</span> - Show configuration\n• <span class=\"info\">clear</span> - Clear console\n• <span class=\"info\">version</span> - Show version information\n\n<span class=\"warning\">Note:</span> This is a web console interface for claude-flow CLI commands.\n`;\n sendResponse(ws, {\n type: 'output',\n data: helpText,\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n if (command === 'clear') {\n sendResponse(ws, {\n type: 'output',\n data: '\\\\x1b[2J\\\\x1b[H', // ANSI clear screen\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n if (command === 'status') {\n const statusText = `<span class=\"success\">System Status:</span>\n• Event Bus: <span class=\"${componentStatus.eventBus ? 'success' : 'error'}\">${componentStatus.eventBus ? 'Active' : 'Inactive'}</span>\n• Orchestrator: <span class=\"${componentStatus.orchestrator ? 'success' : 'error'}\">${componentStatus.orchestrator ? 'Active' : 'Inactive'}</span>\n• Memory Manager: <span class=\"${componentStatus.memoryManager ? 'success' : 'error'}\">${componentStatus.memoryManager ? 'Active' : 'Inactive'}</span>\n• Terminal Pool: <span class=\"${componentStatus.terminalPool ? 'success' : 'error'}\">${componentStatus.terminalPool ? 'Active' : 'Inactive'}</span>\n• MCP Server: <span class=\"${componentStatus.mcpServer ? 'success' : 'error'}\">${componentStatus.mcpServer ? 'Active' : 'Inactive'}</span>\n• Coordination Manager: <span class=\"${componentStatus.coordinationManager ? 'success' : 'error'}\">${componentStatus.coordinationManager ? 'Active' : 'Inactive'}</span>\n• Web UI: <span class=\"${componentStatus.webUI ? 'success' : 'error'}\">${componentStatus.webUI ? 'Active' : 'Inactive'}</span>\n\n<span class=\"info\">Metrics:</span>\n• Active Agents: ${agents.size}\n• Pending Tasks: ${tasks.size}\n• Memory Entries: ${memory.size}\n`;\n sendResponse(ws, {\n type: 'output',\n data: statusText,\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n // For other commands, spawn a subprocess\n const args = command.split(' ');\n const cmd = args[0];\n const cmdArgs = args.slice(1);\n\n // Determine the correct claude-flow executable path\n const rootDir = path.resolve(__dirname, '../..');\n const cliPath = path.join(rootDir, 'bin', 'claude-flow');\n\n // Spawn the command\n const child = spawn('node', [path.join(rootDir, 'src/cli/simple-cli.js'), ...cmdArgs], {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, CLAUDE_FLOW_WEB_MODE: 'true' },\n });\n\n // Handle stdout\n child.stdout.on('data', (data) => {\n const output = data.toString();\n outputHistory.push(output);\n\n // Convert ANSI colors to HTML spans\n const htmlOutput = convertAnsiToHtml(output);\n\n broadcastToClients({\n type: 'output',\n data: htmlOutput,\n });\n });\n\n // Handle stderr\n child.stderr.on('data', (data) => {\n const error = data.toString();\n outputHistory.push(error);\n\n broadcastToClients({\n type: 'error',\n data: convertAnsiToHtml(error),\n });\n });\n\n // Handle process exit\n child.on('close', (code) => {\n const exitMsg =\n code === 0\n ? `<span class=\"success\">Command completed successfully</span>`\n : `<span class=\"error\">Command failed with exit code ${code}</span>`;\n\n broadcastToClients({\n type: 'output',\n data: `\\\\n${exitMsg}\\\\n`,\n });\n\n sendResponse(ws, { type: 'command_complete' });\n });\n\n child.on('error', (error) => {\n const errorMsg = `<span class=\"error\">Failed to execute command: ${error instanceof Error ? error.message : String(error)}</span>`;\n outputHistory.push(errorMsg);\n\n sendResponse(ws, {\n type: 'error',\n data: errorMsg,\n });\n\n sendResponse(ws, { type: 'command_complete' });\n });\n }\n\n // Broadcast message to all connected clients\n function broadcastToClients(message: any) {\n const messageStr = JSON.stringify(message);\n activeConnections.forEach((client) => {\n if (client.readyState === 1) {\n // WebSocket.OPEN\n client.send(messageStr);\n }\n });\n }\n\n // Convert ANSI escape codes to HTML\n function convertAnsiToHtml(text: string): string {\n return text\n .replace(/\\x1b\\[0m/g, '</span>')\n .replace(/\\x1b\\[1m/g, '<span style=\"font-weight: bold;\">')\n .replace(/\\x1b\\[31m/g, '<span class=\"error\">')\n .replace(/\\x1b\\[32m/g, '<span class=\"success\">')\n .replace(/\\x1b\\[33m/g, '<span class=\"warning\">')\n .replace(/\\x1b\\[34m/g, '<span class=\"info\">')\n .replace(/\\x1b\\[35m/g, '<span style=\"color: #d946ef;\">')\n .replace(/\\x1b\\[36m/g, '<span style=\"color: #06b6d4;\">')\n .replace(/\\x1b\\[37m/g, '<span class=\"dim\">')\n .replace(/\\x1b\\[90m/g, '<span class=\"dim\">')\n .replace(/\\x1b\\[[0-9;]*m/g, '') // Remove any remaining ANSI codes\n .replace(/\\n/g, '\\\\n')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/<span/g, '<span')\n .replace(/span>/g, 'span>');\n }\n\n return new Promise((resolve, reject) => {\n server.on('error', (err: any) => {\n if (err.code === 'EADDRINUSE') {\n console.error(`\\n❌ Port ${port} is already in use`);\n console.log(`💡 Try a different port: claude-flow start --ui --port ${port + 1}`);\n console.log(`💡 Or stop the process using port ${port}: lsof -ti:${port} | xargs kill -9`);\n componentStatus.webUI = false;\n reject(err);\n } else {\n console.error('❌ Web UI server error:', err.message, err.stack);\n reject(err);\n }\n });\n\n server.listen(port, host, () => {\n console.log(`🌐 Web UI available at http://${host}:${port}`);\n componentStatus.webUI = true;\n resolve(server);\n });\n });\n}\n\n// Start all components\nexport async function startOrchestrator(options: any) {\n console.log('\\n🚀 Starting orchestration components...\\n');\n\n // Start Event Bus\n console.log('⚡ Starting Event Bus...');\n componentStatus.eventBus = true;\n eventBus.emit('system:start');\n console.log('✅ Event Bus started');\n\n // Start Orchestrator Engine\n console.log('🧠 Starting Orchestrator Engine...');\n componentStatus.orchestrator = true;\n console.log('✅ Orchestrator Engine started');\n\n // Start Memory Manager\n console.log('💾 Starting Memory Manager...');\n componentStatus.memoryManager = true;\n console.log('✅ Memory Manager started');\n\n // Start Terminal Pool\n console.log('🖥️ Starting Terminal Pool...');\n componentStatus.terminalPool = true;\n console.log('✅ Terminal Pool started');\n\n // Start MCP Server\n const mcpPort = options.mcpPort || 3001;\n startMCPServer(mcpPort);\n console.log('✅ MCP Server started');\n\n // Start Coordination Manager\n console.log('🔄 Starting Coordination Manager...');\n componentStatus.coordinationManager = true;\n console.log('✅ Coordination Manager started');\n\n // Start Web UI if requested\n if (options.ui && !options.noUi) {\n const host = options.host || 'localhost';\n const port = options.port || 3000;\n try {\n await startWebUI(host, port);\n } catch (err: any) {\n if (err.code === 'EADDRINUSE') {\n console.log('\\n⚠️ Web UI could not start due to port conflict');\n console.log(' Orchestrator is running without Web UI');\n } else {\n console.error('\\n⚠️ Web UI failed to start:', err.message);\n }\n }\n }\n\n console.log('\\n✅ All components started successfully!');\n console.log('\\n📊 System Status:');\n console.log(' • Event Bus: Active');\n console.log(' • Orchestrator: Active');\n console.log(' • Memory Manager: Active');\n console.log(' • Terminal Pool: Active');\n console.log(' • MCP Server: Active');\n console.log(' • Coordination Manager: Active');\n if (options.ui && !options.noUi) {\n console.log(\n ` • Web UI: Active at http://${options.host || 'localhost'}:${options.port || 3000}`,\n );\n }\n\n console.log('\\n💡 Use \"claude-flow status\" to check system status');\n console.log('💡 Use \"claude-flow stop\" to stop the orchestrator');\n\n // Keep the process running\n if (!options.daemon) {\n console.log('\\n📌 Press Ctrl+C to stop the orchestrator...\\n');\n\n // Handle graceful shutdown\n process.on('SIGINT', () => {\n console.log('\\n\\n🛑 Shutting down orchestrator...');\n process.exit(0);\n });\n }\n}\n\n// Export component status for other commands\nexport function getComponentStatus() {\n return componentStatus;\n}\n\n// Export stores for other commands\nexport function getStores() {\n return { agents, tasks, memory };\n}\n"],"names":["EventEmitter","express","WebSocketServer","createServer","spawn","path","fileURLToPath","cors","__filename","url","__dirname","dirname","agents","Map","tasks","memory","eventBus","componentStatus","orchestrator","memoryManager","terminalPool","mcpServer","coordinationManager","webUI","startMCPServer","port","console","log","startWebUI","host","app","server","wss","use","origin","methods","allowedHeaders","credentials","err","req","res","next","error","status","json","message","timestamp","Date","toISOString","method","outputHistory","activeConnections","Set","cliProcess","consoleHTML","get","send","components","metrics","size","connectedClients","limit","parseInt","query","history","slice","total","length","post","command","body","broadcastToClients","type","data","executeCliCommand","success","Error","String","agentList","Array","from","entries","map","id","agent","taskList","task","memoryList","key","value","JSON","stringify","uptime","process","on","ws","clientIp","headers","socket","remoteAddress","add","cliActive","forEach","line","parse","toString","handleCliCommand","now","delete","sendError","sendResponse","toLocaleTimeString","logEntry","push","errorMsg","helpText","statusText","args","split","cmd","cmdArgs","rootDir","resolve","cliPath","join","child","stdio","env","CLAUDE_FLOW_WEB_MODE","stdout","output","htmlOutput","convertAnsiToHtml","stderr","code","exitMsg","messageStr","client","readyState","text","replace","Promise","reject","stack","listen","startOrchestrator","options","emit","mcpPort","ui","noUi","daemon","exit","getComponentStatus","getStores"],"mappings":"AAIA,SAASA,YAAY,QAAQ,SAAS;AACtC,OAAOC,aAAa,UAAU;AAC9B,SAASC,eAAe,QAAQ,KAAK;AACrC,SAASC,YAAY,QAAQ,OAAO;AACpC,SAASC,KAAK,QAAQ,gBAAgB;AACtC,OAAOC,UAAU,OAAO;AACxB,SAASC,aAAa,QAAQ,MAAM;AACpC,OAAOC,UAAU,OAAO;AAExB,MAAMC,aAAaF,cAAc,YAAYG,GAAG;AAChD,MAAMC,YAAYL,KAAKM,OAAO,CAACH;AAG/B,MAAMI,SAAS,IAAIC;AACnB,MAAMC,QAAQ,IAAID;AAClB,MAAME,SAAS,IAAIF;AAGnB,MAAMG,WAAW,IAAIhB;AAGrB,MAAMiB,kBAAkB;IACtBD,UAAU;IACVE,cAAc;IACdC,eAAe;IACfC,cAAc;IACdC,WAAW;IACXC,qBAAqB;IACrBC,OAAO;AACT;AAGA,SAASC,eAAeC,IAAY;IAClCC,QAAQC,GAAG,CAAC,CAAC,+BAA+B,EAAEF,KAAK,GAAG,CAAC;IAEvDR,gBAAgBI,SAAS,GAAG;IAC5B,OAAO;AACT;AAGA,SAASO,WAAWC,IAAY,EAAEJ,IAAY;IAC5C,MAAMK,MAAM7B;IACZ,MAAM8B,SAAS5B,aAAa2B;IAC5B,MAAME,MAAM,IAAI9B,gBAAgB;QAAE6B;IAAO;IAGzCD,IAAIG,GAAG,CACL1B,KAAK;QACH2B,QAAQ;QACRC,SAAS;YAAC;YAAO;YAAQ;YAAO;YAAU;SAAU;QACp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K,MAAM,EAAE;QACnB7H,QAAQC,GAAG,CAAC;QAGZkE,QAAQC,EAAE,CAAC,UAAU;YACnBpE,QAAQC,GAAG,CAAC;YACZkE,QAAQ2D,IAAI,CAAC;QACf;IACF;AACF;AAGA,OAAO,SAASC;IACd,OAAOxI;AACT;AAGA,OAAO,SAASyI;IACd,OAAO;QAAE9I;QAAQE;QAAOC;IAAO;AACjC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/cli/simple-orchestrator.ts"],"sourcesContent":["/**\n * Simple orchestrator implementation for Node.js compatibility\n */\n\nimport { EventEmitter } from 'events';\nimport express from 'express';\nimport { WebSocketServer } from 'ws';\nimport { createServer } from 'http';\nimport { spawn } from 'child_process';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport cors from 'cors';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Simple in-memory stores\nconst agents = new Map();\nconst tasks = new Map();\nconst memory = new Map();\n\n// Event bus\nconst eventBus = new EventEmitter();\n\n// Component status\nconst componentStatus = {\n eventBus: false,\n orchestrator: false,\n memoryManager: false,\n terminalPool: false,\n mcpServer: false,\n coordinationManager: false,\n webUI: false,\n};\n\n// Simple MCP server\nfunction startMCPServer(port: number) {\n console.log(`🌐 Starting MCP server on port ${port}...`);\n // In a real implementation, this would start the actual MCP server\n componentStatus.mcpServer = true;\n return true;\n}\n\n// Enhanced web UI with console interface\nfunction startWebUI(host: string, port: number) {\n const app = express();\n const server = createServer(app);\n const wss = new WebSocketServer({ server });\n\n // Add CORS middleware for cross-origin support\n app.use(\n cors({\n origin: '*',\n methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],\n allowedHeaders: ['Content-Type', 'Authorization'],\n credentials: true,\n }),\n );\n\n // Global error handler middleware\n app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {\n console.error('Global error handler:', err);\n res.status(err.status || 500).json({\n error: err.message || 'Internal server error',\n timestamp: new Date().toISOString(),\n });\n });\n\n // Request logging middleware\n app.use((req, res, next) => {\n console.log(`${new Date().toISOString()} ${req.method} ${req.path}`);\n next();\n });\n\n // Store CLI output history and active connections\n const outputHistory: string[] = [];\n const activeConnections: Set<any> = new Set();\n\n // CLI output capture system\n const cliProcess: any = null;\n\n const consoleHTML = `\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Claude-Flow Console</title>\n <style>\n * {\n margin: 0;\n padding: 0;\n box-sizing: border-box;\n }\n body {\n font-family: 'Consolas', 'Monaco', 'Courier New', monospace;\n background: #0d1117;\n color: #c9d1d9;\n height: 100vh;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .header {\n background: #161b22;\n border-bottom: 1px solid #21262d;\n padding: 10px 20px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n }\n .title {\n font-weight: bold;\n color: #58a6ff;\n }\n .connection-status {\n font-size: 12px;\n color: #7c3aed;\n }\n .console-container {\n flex: 1;\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n .console-output {\n flex: 1;\n overflow-y: auto;\n padding: 10px;\n background: #0d1117;\n font-size: 13px;\n line-height: 1.4;\n white-space: pre-wrap;\n word-wrap: break-word;\n }\n .console-input {\n background: #161b22;\n border: none;\n border-top: 1px solid #21262d;\n padding: 10px;\n color: #c9d1d9;\n font-family: inherit;\n font-size: 13px;\n outline: none;\n }\n .console-input:focus {\n background: #21262d;\n }\n .prompt {\n color: #58a6ff;\n font-weight: bold;\n }\n .error {\n color: #ff7b72;\n }\n .success {\n color: #3fb950;\n }\n .warning {\n color: #ffa657;\n }\n .info {\n color: #79c0ff;\n }\n .dim {\n color: #8b949e;\n }\n .scrollbar {\n scrollbar-width: thin;\n scrollbar-color: #21262d #0d1117;\n }\n .scrollbar::-webkit-scrollbar {\n width: 8px;\n }\n .scrollbar::-webkit-scrollbar-track {\n background: #0d1117;\n }\n .scrollbar::-webkit-scrollbar-thumb {\n background: #21262d;\n border-radius: 4px;\n }\n .scrollbar::-webkit-scrollbar-thumb:hover {\n background: #30363d;\n }\n .system-status {\n display: flex;\n gap: 15px;\n font-size: 11px;\n }\n .status-item {\n display: flex;\n align-items: center;\n gap: 5px;\n }\n .status-dot {\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #3fb950;\n }\n .status-dot.inactive {\n background: #f85149;\n }\n </style>\n </head>\n <body>\n <div class=\"header\">\n <div class=\"title\">🧠 Claude-Flow Console</div>\n <div class=\"system-status\">\n <div class=\"status-item\">\n <div class=\"status-dot\" id=\"ws-status\"></div>\n <span id=\"ws-text\">Connecting...</span>\n </div>\n <div class=\"status-item\">\n <div class=\"status-dot\" id=\"cli-status\"></div>\n <span id=\"cli-text\">CLI Ready</span>\n </div>\n </div>\n </div>\n <div class=\"console-container\">\n <div class=\"console-output scrollbar\" id=\"output\"></div>\n <input type=\"text\" class=\"console-input\" id=\"input\" placeholder=\"Enter claude-flow command...\" autocomplete=\"off\">\n </div>\n\n <script>\n const output = document.getElementById('output');\n const input = document.getElementById('input');\n const wsStatus = document.getElementById('ws-status');\n const wsText = document.getElementById('ws-text');\n const cliStatus = document.getElementById('cli-status');\n const cliText = document.getElementById('cli-text');\n \n let ws = null;\n let commandHistory = [];\n let historyIndex = -1;\n let reconnectAttempts = 0;\n let reconnectTimer = null;\n let isReconnecting = false;\n const MAX_RECONNECT_ATTEMPTS = 10;\n const BASE_RECONNECT_DELAY = 1000;\n \n function getReconnectDelay() {\n // Exponential backoff with jitter\n const exponentialDelay = Math.min(BASE_RECONNECT_DELAY * Math.pow(2, reconnectAttempts), 30000);\n const jitter = Math.random() * 0.3 * exponentialDelay;\n return exponentialDelay + jitter;\n }\n \n function connect() {\n if (isReconnecting || (ws && ws.readyState === WebSocket.CONNECTING)) {\n console.log('Already connecting, skipping duplicate attempt');\n return;\n }\n \n isReconnecting = true;\n const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';\n const wsUrl = \\`\\${protocol}//\\${window.location.host}\\`;\n \n try {\n console.log(\\`Attempting WebSocket connection to \\${wsUrl}\\`);\n ws = new WebSocket(wsUrl);\n \n ws.onopen = () => {\n console.log('WebSocket connected successfully');\n wsStatus.classList.remove('inactive');\n wsText.textContent = 'Connected';\n reconnectAttempts = 0;\n isReconnecting = false;\n \n if (reconnectTimer) {\n clearTimeout(reconnectTimer);\n reconnectTimer = null;\n }\n \n appendOutput('\\n<span class=\"success\">🔗 Connected to Claude-Flow Console</span>\\n');\n appendOutput('<span class=\"info\">Type \"help\" for available commands or use any claude-flow command</span>\\n\\n');\n };\n \n ws.onmessage = (event) => {\n try {\n const data = JSON.parse(event.data);\n handleMessage(data);\n } catch (error) {\n console.error('Failed to parse WebSocket message:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ Invalid message received: \\${(error instanceof Error ? error.message : String(error))}</span>\\n\\`);\n }\n };\n \n ws.onclose = (event) => {\n console.log(\\`WebSocket closed: code=\\${event.code}, reason=\\${event.reason}\\`);\n wsStatus.classList.add('inactive');\n wsText.textContent = 'Disconnected';\n isReconnecting = false;\n \n if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {\n reconnectAttempts++;\n const delay = getReconnectDelay();\n appendOutput(\\`\\n<span class=\"error\">🔗 Connection lost. Reconnecting in \\${Math.round(delay/1000)}s... (attempt \\${reconnectAttempts}/\\${MAX_RECONNECT_ATTEMPTS})</span>\\n\\`);\n \n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n connect();\n }, delay);\n } else {\n appendOutput(\\`\\n<span class=\"error\">❌ Failed to reconnect after \\${MAX_RECONNECT_ATTEMPTS} attempts. Please refresh the page.</span>\\n\\`);\n wsText.textContent = 'Failed to connect';\n }\n };\n \n ws.onerror = (error) => {\n console.error('WebSocket error:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ WebSocket error: \\${(error instanceof Error ? error.message : String(error)) || 'Connection failed'}</span>\\n\\`);\n isReconnecting = false;\n };\n \n } catch (error) {\n console.error('Failed to create WebSocket:', error);\n appendOutput(\\`\\n<span class=\"error\">❌ Failed to create WebSocket connection: \\${(error instanceof Error ? error.message : String(error))}</span>\\n\\`);\n isReconnecting = false;\n \n // Try reconnect if not exceeded max attempts\n if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {\n reconnectAttempts++;\n const delay = getReconnectDelay();\n reconnectTimer = setTimeout(() => {\n reconnectTimer = null;\n connect();\n }, delay);\n }\n }\n }\n \n function handleMessage(data) {\n switch (data.type) {\n case 'output':\n appendOutput(data.data);\n break;\n case 'error':\n appendOutput('<span class=\"error\">' + data.data + '</span>');\n break;\n case 'command_complete':\n appendOutput('\\n<span class=\"prompt\">claude-flow> </span>');\n break;\n case 'status':\n updateStatus(data.data);\n break;\n }\n }\n \n function appendOutput(text) {\n output.innerHTML += text;\n output.scrollTop = output.scrollHeight;\n }\n \n function updateStatus(status) {\n // Update CLI status based on server response\n if (status.cliActive) {\n cliStatus.classList.remove('inactive');\n cliText.textContent = 'CLI Active';\n } else {\n cliStatus.classList.add('inactive');\n cliText.textContent = 'CLI Inactive';\n }\n }\n \n function sendCommand(command) {\n if (ws && ws.readyState === WebSocket.OPEN) {\n appendOutput('<span class=\"prompt\">claude-flow> </span>' + command + '\\n');\n ws.send(JSON.stringify({\n type: 'command',\n data: command\n }));\n \n // Add to history\n if (command.trim() && commandHistory[commandHistory.length - 1] !== command) {\n commandHistory.push(command);\n if (commandHistory.length > 100) {\n commandHistory.shift();\n }\n }\n historyIndex = commandHistory.length;\n }\n }\n \n // Input handling\n input.addEventListener('keydown', (e) => {\n if (e.key === 'Enter') {\n const command = input.value.trim();\n if (command) {\n sendCommand(command);\n input.value = '';\n }\n } else if (e.key === 'ArrowUp') {\n e.preventDefault();\n if (historyIndex > 0) {\n historyIndex--;\n input.value = commandHistory[historyIndex] || '';\n }\n } else if (e.key === 'ArrowDown') {\n e.preventDefault();\n if (historyIndex < commandHistory.length - 1) {\n historyIndex++;\n input.value = commandHistory[historyIndex] || '';\n } else {\n historyIndex = commandHistory.length;\n input.value = '';\n }\n } else if (e.key === 'Tab') {\n e.preventDefault();\n // Basic tab completion for common commands\n const value = input.value;\n const commands = ['help', 'status', 'agent', 'task', 'memory', 'config', 'start', 'stop'];\n const matches = commands.filter(cmd => cmd.startsWith(value));\n if (matches.length === 1) {\n input.value = matches[0] + ' ';\n }\n }\n });\n \n // Focus input on page load\n window.addEventListener('load', () => {\n input.focus();\n connect();\n });\n \n // Implement heartbeat to detect stale connections\n setInterval(() => {\n if (ws && ws.readyState === WebSocket.OPEN) {\n ws.send(JSON.stringify({ type: 'ping', timestamp: Date.now() }));\n }\n }, 30000); // Ping every 30 seconds\n \n // Handle page visibility changes\n document.addEventListener('visibilitychange', () => {\n if (!document.hidden && ws && ws.readyState !== WebSocket.OPEN) {\n console.log('Page became visible, checking connection...');\n reconnectAttempts = 0; // Reset attempts when page becomes visible\n connect();\n }\n });\n \n // Keep input focused\n document.addEventListener('click', () => {\n input.focus();\n });\n </script>\n </body>\n </html>\n `;\n\n app.get('/', (req, res) => {\n res.send(consoleHTML);\n });\n\n // API endpoints\n app.get('/api/status', (req, res) => {\n res.json({\n components: componentStatus,\n metrics: {\n agents: agents.size,\n tasks: tasks.size,\n memory: memory.size,\n connectedClients: activeConnections.size,\n },\n });\n });\n\n app.get('/api/history', (req, res) => {\n const limit = parseInt(req.query.limit as string) || 100;\n res.json({\n history: outputHistory.slice(-limit),\n total: outputHistory.length,\n });\n });\n\n app.post('/api/command', express.json(), (req, res) => {\n const { command } = req.body;\n if (!command) {\n res.status(400).json({ error: 'Command is required' });\n return;\n }\n\n // Execute command and return immediately\n // Output will be sent via WebSocket\n try {\n broadcastToClients({\n type: 'output',\n data: `<span class=\"prompt\">API> </span>${command}\\\\n`,\n });\n\n executeCliCommand(command, null);\n\n res.json({ success: true, message: 'Command executed' });\n } catch (error) {\n res.status(500).json({ error: error instanceof Error ? error.message : String(error) });\n }\n });\n\n app.get('/api/agents', (req, res) => {\n const agentList = Array.from(agents.entries()).map(([id, agent]) => ({\n id,\n ...agent,\n }));\n res.json(agentList);\n });\n\n app.get('/api/tasks', (req, res) => {\n const taskList = Array.from(tasks.entries()).map(([id, task]) => ({\n id,\n ...task,\n }));\n res.json(taskList);\n });\n\n app.get('/api/memory', (req, res) => {\n const memoryList = Array.from(memory.entries()).map(([key, value]) => ({\n key,\n value,\n type: typeof value,\n size: JSON.stringify(value).length,\n }));\n res.json(memoryList);\n });\n\n // Health check endpoint\n app.get('/health', (req, res) => {\n res.json({\n status: 'healthy',\n timestamp: new Date().toISOString(),\n uptime: process.uptime(),\n components: componentStatus,\n });\n });\n\n // WebSocket for real-time CLI interaction\n wss.on('connection', (ws, req) => {\n const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;\n console.log(`🔌 WebSocket client connected from ${clientIp}`);\n activeConnections.add(ws);\n\n // Send initial status and history\n ws.send(\n JSON.stringify({\n type: 'status',\n data: { ...componentStatus, cliActive: true },\n }),\n );\n\n // Send recent output history\n outputHistory.slice(-50).forEach((line) => {\n ws.send(\n JSON.stringify({\n type: 'output',\n data: line,\n }),\n );\n });\n\n // Handle incoming commands\n ws.on('message', (message) => {\n try {\n const data = JSON.parse(message.toString());\n console.log(`Received command from client: ${data.type}`);\n\n if (data.type === 'command') {\n handleCliCommand(data.data, ws);\n } else if (data.type === 'ping') {\n // Handle ping/pong for connection keepalive\n ws.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));\n }\n } catch (error) {\n console.error('Failed to handle WebSocket message:', error);\n ws.send(\n JSON.stringify({\n type: 'error',\n data: `Invalid message format: ${error instanceof Error ? error.message : String(error)}`,\n timestamp: new Date().toISOString(),\n }),\n );\n }\n });\n\n ws.on('close', () => {\n console.log('🔌 WebSocket client disconnected');\n activeConnections.delete(ws);\n });\n\n ws.on('error', (error) => {\n console.error('WebSocket client error:', error);\n // Send detailed error information to client before closing\n try {\n ws.send(\n JSON.stringify({\n type: 'error',\n data: `Server WebSocket error: ${(error instanceof Error ? error.message : String(error)) || 'Unknown error'}`,\n timestamp: new Date().toISOString(),\n }),\n );\n } catch (sendError) {\n console.error('Failed to send error to client:', sendError);\n }\n activeConnections.delete(ws);\n });\n });\n\n // Helper function to send response to specific client or broadcast\n function sendResponse(ws: any, data: any) {\n if (ws) {\n ws.send(JSON.stringify(data));\n } else {\n broadcastToClients(data);\n }\n }\n\n // CLI command execution handler\n function handleCliCommand(command: string, ws: any) {\n try {\n // Add timestamp and format output\n const timestamp = new Date().toLocaleTimeString();\n const logEntry = `[${timestamp}] Executing: ${command}`;\n outputHistory.push(logEntry);\n\n // Broadcast to all connected clients\n broadcastToClients({\n type: 'output',\n data: `<span class=\"dim\">[${timestamp}]</span> <span class=\"info\">Executing:</span> ${command}\\\\n`,\n });\n\n // Execute the command\n executeCliCommand(command, ws);\n } catch (error) {\n const errorMsg = `Error executing command: ${error instanceof Error ? error.message : String(error)}`;\n outputHistory.push(errorMsg);\n sendResponse(ws, {\n type: 'error',\n data: errorMsg,\n });\n }\n }\n\n // Execute CLI commands and capture output\n function executeCliCommand(command: string, ws: any) {\n // Handle built-in commands first\n if (command === 'help') {\n const helpText = `<span class=\"success\">Available Commands:</span>\n• <span class=\"info\">help</span> - Show this help message\n• <span class=\"info\">status</span> - Show system status\n• <span class=\"info\">agent list</span> - List all agents\n• <span class=\"info\">agent spawn [type]</span> - Spawn a new agent\n• <span class=\"info\">task list</span> - List all tasks\n• <span class=\"info\">memory list</span> - List memory entries\n• <span class=\"info\">config show</span> - Show configuration\n• <span class=\"info\">clear</span> - Clear console\n• <span class=\"info\">version</span> - Show version information\n\n<span class=\"warning\">Note:</span> This is a web console interface for claude-flow CLI commands.\n`;\n sendResponse(ws, {\n type: 'output',\n data: helpText,\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n if (command === 'clear') {\n sendResponse(ws, {\n type: 'output',\n data: '\\\\x1b[2J\\\\x1b[H', // ANSI clear screen\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n if (command === 'status') {\n const statusText = `<span class=\"success\">System Status:</span>\n• Event Bus: <span class=\"${componentStatus.eventBus ? 'success' : 'error'}\">${componentStatus.eventBus ? 'Active' : 'Inactive'}</span>\n• Orchestrator: <span class=\"${componentStatus.orchestrator ? 'success' : 'error'}\">${componentStatus.orchestrator ? 'Active' : 'Inactive'}</span>\n• Memory Manager: <span class=\"${componentStatus.memoryManager ? 'success' : 'error'}\">${componentStatus.memoryManager ? 'Active' : 'Inactive'}</span>\n• Terminal Pool: <span class=\"${componentStatus.terminalPool ? 'success' : 'error'}\">${componentStatus.terminalPool ? 'Active' : 'Inactive'}</span>\n• MCP Server: <span class=\"${componentStatus.mcpServer ? 'success' : 'error'}\">${componentStatus.mcpServer ? 'Active' : 'Inactive'}</span>\n• Coordination Manager: <span class=\"${componentStatus.coordinationManager ? 'success' : 'error'}\">${componentStatus.coordinationManager ? 'Active' : 'Inactive'}</span>\n• Web UI: <span class=\"${componentStatus.webUI ? 'success' : 'error'}\">${componentStatus.webUI ? 'Active' : 'Inactive'}</span>\n\n<span class=\"info\">Metrics:</span>\n• Active Agents: ${agents.size}\n• Pending Tasks: ${tasks.size}\n• Memory Entries: ${memory.size}\n`;\n sendResponse(ws, {\n type: 'output',\n data: statusText,\n });\n sendResponse(ws, { type: 'command_complete' });\n return;\n }\n\n // For other commands, spawn a subprocess\n const args = command.split(' ');\n const cmd = args[0];\n const cmdArgs = args.slice(1);\n\n // Determine the correct claude-flow executable path\n const rootDir = path.resolve(__dirname, '../..');\n const cliPath = path.join(rootDir, 'bin', 'claude-flow');\n\n // Spawn the command\n const child = spawn('node', [path.join(rootDir, 'src/cli/simple-cli.js'), ...cmdArgs], {\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, CLAUDE_FLOW_WEB_MODE: 'true' },\n });\n\n // Handle stdout\n child.stdout.on('data', (data) => {\n const output = data.toString();\n outputHistory.push(output);\n\n // Convert ANSI colors to HTML spans\n const htmlOutput = convertAnsiToHtml(output);\n\n broadcastToClients({\n type: 'output',\n data: htmlOutput,\n });\n });\n\n // Handle stderr\n child.stderr.on('data', (data) => {\n const error = data.toString();\n outputHistory.push(error);\n\n broadcastToClients({\n type: 'error',\n data: convertAnsiToHtml(error),\n });\n });\n\n // Handle process exit\n child.on('close', (code) => {\n const exitMsg =\n code === 0\n ? `<span class=\"success\">Command completed successfully</span>`\n : `<span class=\"error\">Command failed with exit code ${code}</span>`;\n\n broadcastToClients({\n type: 'output',\n data: `\\\\n${exitMsg}\\\\n`,\n });\n\n sendResponse(ws, { type: 'command_complete' });\n });\n\n child.on('error', (error) => {\n const errorMsg = `<span class=\"error\">Failed to execute command: ${error instanceof Error ? error.message : String(error)}</span>`;\n outputHistory.push(errorMsg);\n\n sendResponse(ws, {\n type: 'error',\n data: errorMsg,\n });\n\n sendResponse(ws, { type: 'command_complete' });\n });\n }\n\n // Broadcast message to all connected clients\n function broadcastToClients(message: any) {\n const messageStr = JSON.stringify(message);\n activeConnections.forEach((client) => {\n if (client.readyState === 1) {\n // WebSocket.OPEN\n client.send(messageStr);\n }\n });\n }\n\n // Convert ANSI escape codes to HTML\n function convertAnsiToHtml(text: string): string {\n return text\n .replace(/\\x1b\\[0m/g, '</span>')\n .replace(/\\x1b\\[1m/g, '<span style=\"font-weight: bold;\">')\n .replace(/\\x1b\\[31m/g, '<span class=\"error\">')\n .replace(/\\x1b\\[32m/g, '<span class=\"success\">')\n .replace(/\\x1b\\[33m/g, '<span class=\"warning\">')\n .replace(/\\x1b\\[34m/g, '<span class=\"info\">')\n .replace(/\\x1b\\[35m/g, '<span style=\"color: #d946ef;\">')\n .replace(/\\x1b\\[36m/g, '<span style=\"color: #06b6d4;\">')\n .replace(/\\x1b\\[37m/g, '<span class=\"dim\">')\n .replace(/\\x1b\\[90m/g, '<span class=\"dim\">')\n .replace(/\\x1b\\[[0-9;]*m/g, '') // Remove any remaining ANSI codes\n .replace(/\\n/g, '\\\\n')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/<span/g, '<span')\n .replace(/span>/g, 'span>');\n }\n\n return new Promise((resolve, reject) => {\n server.on('error', (err: any) => {\n if (err.code === 'EADDRINUSE') {\n console.error(`\\n❌ Port ${port} is already in use`);\n console.log(`💡 Try a different port: claude-flow start --ui --port ${port + 1}`);\n console.log(`💡 Or stop the process using port ${port}: lsof -ti:${port} | xargs kill -9`);\n componentStatus.webUI = false;\n reject(err);\n } else {\n console.error('❌ Web UI server error:', err.message, err.stack);\n reject(err);\n }\n });\n\n server.listen(port, host, () => {\n console.log(`🌐 Web UI available at http://${host}:${port}`);\n componentStatus.webUI = true;\n resolve(server);\n });\n });\n}\n\n// Start all components\nexport async function startOrchestrator(options: any) {\n console.log('\\n🚀 Starting orchestration components...\\n');\n\n // Start Event Bus\n console.log('⚡ Starting Event Bus...');\n componentStatus.eventBus = true;\n eventBus.emit('system:start');\n console.log('✅ Event Bus started');\n\n // Start Orchestrator Engine\n console.log('🧠 Starting Orchestrator Engine...');\n componentStatus.orchestrator = true;\n console.log('✅ Orchestrator Engine started');\n\n // Start Memory Manager\n console.log('💾 Starting Memory Manager...');\n componentStatus.memoryManager = true;\n console.log('✅ Memory Manager started');\n\n // Start Terminal Pool\n console.log('🖥️ Starting Terminal Pool...');\n componentStatus.terminalPool = true;\n console.log('✅ Terminal Pool started');\n\n // Start MCP Server\n const mcpPort = options.mcpPort || 3001;\n startMCPServer(mcpPort);\n console.log('✅ MCP Server started');\n\n // Start Coordination Manager\n console.log('🔄 Starting Coordination Manager...');\n componentStatus.coordinationManager = true;\n console.log('✅ Coordination Manager started');\n\n // Start Web UI if requested\n if (options.ui && !options.noUi) {\n const host = options.host || 'localhost';\n const port = options.port || 3000;\n try {\n await startWebUI(host, port);\n } catch (err: any) {\n if (err.code === 'EADDRINUSE') {\n console.log('\\n⚠️ Web UI could not start due to port conflict');\n console.log(' Orchestrator is running without Web UI');\n } else {\n console.error('\\n⚠️ Web UI failed to start:', err.message);\n }\n }\n }\n\n console.log('\\n✅ All components started successfully!');\n console.log('\\n📊 System Status:');\n console.log(' • Event Bus: Active');\n console.log(' • Orchestrator: Active');\n console.log(' • Memory Manager: Active');\n console.log(' • Terminal Pool: Active');\n console.log(' • MCP Server: Active');\n console.log(' • Coordination Manager: Active');\n if (options.ui && !options.noUi) {\n console.log(\n ` • Web UI: Active at http://${options.host || 'localhost'}:${options.port || 3000}`,\n );\n }\n\n console.log('\\n💡 Use \"claude-flow status\" to check system status');\n console.log('💡 Use \"claude-flow stop\" to stop the orchestrator');\n\n // Keep the process running\n if (!options.daemon) {\n console.log('\\n📌 Press Ctrl+C to stop the orchestrator...\\n');\n\n // Handle graceful shutdown\n process.on('SIGINT', () => {\n console.log('\\n\\n🛑 Shutting down orchestrator...');\n process.exit(0);\n });\n }\n}\n\n// Export component status for other commands\nexport function getComponentStatus() {\n return componentStatus;\n}\n\n// Export stores for other commands\nexport function getStores() {\n return { agents, tasks, memory };\n}\n"],"names":["EventEmitter","express","WebSocketServer","createServer","spawn","path","fileURLToPath","cors","__filename","url","__dirname","dirname","agents","Map","tasks","memory","eventBus","componentStatus","orchestrator","memoryManager","terminalPool","mcpServer","coordinationManager","webUI","startMCPServer","port","console","log","startWebUI","host","app","server","wss","use","origin","methods","allowedHeaders","credentials","err","req","res","next","error","status","json","message","timestamp","Date","toISOString","method","outputHistory","activeConnections","Set","cliProcess","consoleHTML","get","send","components","metrics","size","connectedClients","limit","parseInt","query","history","slice","total","length","post","command","body","broadcastToClients","type","data","executeCliCommand","success","Error","String","agentList","Array","from","entries","map","id","agent","taskList","task","memoryList","key","value","JSON","stringify","uptime","process","on","ws","clientIp","headers","socket","remoteAddress","add","cliActive","forEach","line","parse","toString","handleCliCommand","now","delete","sendError","sendResponse","toLocaleTimeString","logEntry","push","errorMsg","helpText","statusText","args","split","cmd","cmdArgs","rootDir","resolve","cliPath","join","child","stdio","env","CLAUDE_FLOW_WEB_MODE","stdout","output","htmlOutput","convertAnsiToHtml","stderr","code","exitMsg","messageStr","client","readyState","text","replace","Promise","reject","stack","listen","startOrchestrator","options","emit","mcpPort","ui","noUi","daemon","exit","getComponentStatus","getStores"],"mappings":"AAIA,SAASA,YAAY,QAAQ,SAAS;AACtC,OAAOC,aAAa,UAAU;AAC9B,SAASC,eAAe,QAAQ,KAAK;AACrC,SAASC,YAAY,QAAQ,OAAO;AACpC,SAASC,KAAK,QAAQ,gBAAgB;AACtC,OAAOC,UAAU,OAAO;AACxB,SAASC,aAAa,QAAQ,MAAM;AACpC,OAAOC,UAAU,OAAO;AAExB,MAAMC,aAAaF,cAAc,YAAYG,GAAG;AAChD,MAAMC,YAAYL,KAAKM,OAAO,CAACH;AAG/B,MAAMI,SAAS,IAAIC;AACnB,MAAMC,QAAQ,IAAID;AAClB,MAAME,SAAS,IAAIF;AAGnB,MAAMG,WAAW,IAAIhB;AAGrB,MAAMiB,kBAAkB;IACtBD,UAAU;IACVE,cAAc;IACdC,eAAe;IACfC,cAAc;IACdC,WAAW;IACXC,qBAAqB;IACrBC,OAAO;AACT;AAGA,SAASC,eAAeC,IAAY;IAClCC,QAAQC,GAAG,CAAC,CAAC,+BAA+B,EAAEF,KAAK,GAAG,CAAC;IAEvDR,gBAAgBI,SAAS,GAAG;IAC5B,OAAO;AACT;AAGA,SAASO,WAAWC,IAAY,EAAEJ,IAAY;IAC5C,MAAMK,MAAM7B;IACZ,MAAM8B,SAAS5B,aAAa2B;IAC5B,MAAME,MAAM,IAAI9B,gBAAgB;QAAE6B;IAAO;IAGzCD,IAAIG,GAAG,CACL1B,KAAK;QACH2B,QAAQ;QACRC,SAAS;YAAC;YAAO;YAAQ;YAAO;YAAU;SAAU;QACpDC,gBAAgB;YAAC;YAAgB;SAAgB;QACjDC,aAAa;IACf;IAIFP,IAAIG,GAAG,CAAC,CAACK,KAAUC,KAAsBC,KAAuBC;QAC9Df,QAAQgB,KAAK,CAAC,yBAAyBJ;QACvCE,IAAIG,MAAM,CAACL,IAAIK,MAAM,IAAI,KAAKC,IAAI,CAAC;YACjCF,OAAOJ,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QAAOC;IAAO;AACjC"}
|
|
@@ -144,7 +144,7 @@ export class ConflictResolver {
|
|
|
144
144
|
if (!conflict) {
|
|
145
145
|
throw new Error(`Conflict not found: ${conflictId}`);
|
|
146
146
|
}
|
|
147
|
-
|
|
147
|
+
const context = {};
|
|
148
148
|
if (preferredStrategy === 'priority') {
|
|
149
149
|
context.agentPriorities = new Map(conflict.agents.map((id, index)=>[
|
|
150
150
|
id,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/coordination/conflict-resolution.ts"],"sourcesContent":["/**\n * Conflict resolution mechanisms for multi-agent coordination\n */\n\nimport type { ILogger } from '../core/logger.js';\nimport type { IEventBus } from '../core/event-bus.js';\nimport type { Task, Resource } from '../utils/types.js';\n\nexport interface ResourceConflict {\n id: string;\n resourceId: string;\n agents: string[];\n timestamp: Date;\n resolved: boolean;\n resolution?: ConflictResolution;\n}\n\nexport interface TaskConflict {\n id: string;\n taskId: string;\n agents: string[];\n type: 'assignment' | 'dependency' | 'output';\n timestamp: Date;\n resolved: boolean;\n resolution?: ConflictResolution;\n}\n\nexport interface ConflictResolution {\n type: 'priority' | 'timestamp' | 'vote' | 'manual' | 'retry';\n winner?: string;\n losers?: string[];\n reason: string;\n timestamp: Date;\n}\n\nexport interface ConflictResolutionStrategy {\n name: string;\n resolve(conflict: ResourceConflict | TaskConflict, context: any): Promise<ConflictResolution>;\n}\n\n/**\n * Priority-based resolution strategy\n */\nexport class PriorityResolutionStrategy implements ConflictResolutionStrategy {\n name = 'priority';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { agentPriorities: Map<string, number> },\n ): Promise<ConflictResolution> {\n const priorities = conflict.agents.map((agentId) => ({\n agentId,\n priority: context.agentPriorities.get(agentId) || 0,\n }));\n\n // Sort by priority (descending)\n priorities.sort((a, b) => b.priority - a.priority);\n\n const winner = priorities[0].agentId;\n const losers = priorities.slice(1).map((p) => p.agentId);\n\n return {\n type: 'priority',\n winner,\n losers,\n reason: `Agent ${winner} has highest priority (${priorities[0].priority})`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * First-come-first-served resolution strategy\n */\nexport class TimestampResolutionStrategy implements ConflictResolutionStrategy {\n name = 'timestamp';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { requestTimestamps: Map<string, Date> },\n ): Promise<ConflictResolution> {\n const timestamps = conflict.agents.map((agentId) => ({\n agentId,\n timestamp: context.requestTimestamps.get(agentId) || new Date(),\n }));\n\n // Sort by timestamp (ascending - earliest first)\n timestamps.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n const winner = timestamps[0].agentId;\n const losers = timestamps.slice(1).map((t) => t.agentId);\n\n return {\n type: 'timestamp',\n winner,\n losers,\n reason: `Agent ${winner} made the earliest request`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * Voting-based resolution strategy (for multi-agent consensus)\n */\nexport class VotingResolutionStrategy implements ConflictResolutionStrategy {\n name = 'vote';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { votes: Map<string, string[]> }, // agentId -> votes for that agent\n ): Promise<ConflictResolution> {\n const voteCounts = new Map<string, number>();\n\n // Count votes\n for (const [agentId, voters] of context.votes) {\n voteCounts.set(agentId, voters.length);\n }\n\n // Find winner\n let maxVotes = 0;\n let winner = '';\n const losers: string[] = [];\n\n for (const [agentId, votes] of voteCounts) {\n if (votes > maxVotes) {\n if (winner) {\n losers.push(winner);\n }\n maxVotes = votes;\n winner = agentId;\n } else {\n losers.push(agentId);\n }\n }\n\n return {\n type: 'vote',\n winner,\n losers,\n reason: `Agent ${winner} received the most votes (${maxVotes})`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * Conflict resolution manager\n */\nexport class ConflictResolver {\n private strategies = new Map<string, ConflictResolutionStrategy>();\n private conflicts = new Map<string, ResourceConflict | TaskConflict>();\n private resolutionHistory: ConflictResolution[] = [];\n\n constructor(\n private logger: ILogger,\n private eventBus: IEventBus,\n ) {\n // Register default strategies\n this.registerStrategy(new PriorityResolutionStrategy());\n this.registerStrategy(new TimestampResolutionStrategy());\n this.registerStrategy(new VotingResolutionStrategy());\n }\n\n /**\n * Register a conflict resolution strategy\n */\n registerStrategy(strategy: ConflictResolutionStrategy): void {\n this.strategies.set(strategy.name, strategy);\n this.logger.info('Registered conflict resolution strategy', { name: strategy.name });\n }\n\n /**\n * Report a resource conflict\n */\n async reportResourceConflict(resourceId: string, agents: string[]): Promise<ResourceConflict> {\n const conflict: ResourceConflict = {\n id: `conflict-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n resourceId,\n agents,\n timestamp: new Date(),\n resolved: false,\n };\n\n this.conflicts.set(conflict.id, conflict);\n this.logger.warn('Resource conflict reported', conflict);\n\n // Emit conflict event\n this.eventBus.emit('conflict:resource', conflict);\n\n return conflict;\n }\n\n /**\n * Report a task conflict\n */\n async reportTaskConflict(\n taskId: string,\n agents: string[],\n type: TaskConflict['type'],\n ): Promise<TaskConflict> {\n const conflict: TaskConflict = {\n id: `conflict-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n taskId,\n agents,\n type,\n timestamp: new Date(),\n resolved: false,\n };\n\n this.conflicts.set(conflict.id, conflict);\n this.logger.warn('Task conflict reported', conflict);\n\n // Emit conflict event\n this.eventBus.emit('conflict:task', conflict);\n\n return conflict;\n }\n\n /**\n * Resolve a conflict using a specific strategy\n */\n async resolveConflict(\n conflictId: string,\n strategyName: string,\n context: any,\n ): Promise<ConflictResolution> {\n const conflict = this.conflicts.get(conflictId);\n if (!conflict) {\n throw new Error(`Conflict not found: ${conflictId}`);\n }\n\n if (conflict.resolved) {\n throw new Error(`Conflict already resolved: ${conflictId}`);\n }\n\n const strategy = this.strategies.get(strategyName);\n if (!strategy) {\n throw new Error(`Strategy not found: ${strategyName}`);\n }\n\n // Resolve the conflict\n const resolution = await strategy.resolve(conflict, context);\n\n // Update conflict\n conflict.resolved = true;\n conflict.resolution = resolution;\n\n // Store in history\n this.resolutionHistory.push(resolution);\n\n // Emit resolution event\n this.eventBus.emit('conflict:resolved', {\n conflict,\n resolution,\n });\n\n this.logger.info('Conflict resolved', {\n conflictId,\n strategy: strategyName,\n resolution,\n });\n\n return resolution;\n }\n\n /**\n * Auto-resolve conflicts based on configuration\n */\n async autoResolve(\n conflictId: string,\n preferredStrategy: string = 'priority',\n ): Promise<ConflictResolution> {\n const conflict = this.conflicts.get(conflictId);\n if (!conflict) {\n throw new Error(`Conflict not found: ${conflictId}`);\n }\n\n // Build context based on conflict type\n let context: any = {};\n\n if (preferredStrategy === 'priority') {\n // In a real implementation, fetch agent priorities from configuration\n context.agentPriorities = new Map(\n conflict.agents.map((id, index) => [id, conflict.agents.length - index]),\n );\n } else if (preferredStrategy === 'timestamp') {\n // In a real implementation, fetch request timestamps\n context.requestTimestamps = new Map(\n conflict.agents.map((id, index) => [id, new Date(Date.now() - index * 1000)]),\n );\n }\n\n return this.resolveConflict(conflictId, preferredStrategy, context);\n }\n\n /**\n * Get active conflicts\n */\n getActiveConflicts(): Array<ResourceConflict | TaskConflict> {\n return Array.from(this.conflicts.values()).filter((c) => !c.resolved);\n }\n\n /**\n * Get conflict history\n */\n getConflictHistory(limit?: number): ConflictResolution[] {\n if (limit) {\n return this.resolutionHistory.slice(-limit);\n }\n return [...this.resolutionHistory];\n }\n\n /**\n * Clear resolved conflicts older than a certain age\n */\n cleanupOldConflicts(maxAgeMs: number): number {\n const now = Date.now();\n let removed = 0;\n\n for (const [id, conflict] of this.conflicts) {\n if (conflict.resolved && now - conflict.timestamp.getTime() > maxAgeMs) {\n this.conflicts.delete(id);\n removed++;\n }\n }\n\n // Also cleanup old history\n const cutoffTime = now - maxAgeMs;\n this.resolutionHistory = this.resolutionHistory.filter(\n (r) => r.timestamp.getTime() > cutoffTime,\n );\n\n return removed;\n }\n\n /**\n * Get conflict statistics\n */\n getStats(): Record<string, unknown> {\n const stats = {\n totalConflicts: this.conflicts.size,\n activeConflicts: 0,\n resolvedConflicts: 0,\n resolutionsByStrategy: {} as Record<string, number>,\n conflictsByType: {\n resource: 0,\n task: 0,\n },\n };\n\n for (const conflict of this.conflicts.values()) {\n if (conflict.resolved) {\n stats.resolvedConflicts++;\n\n if (conflict.resolution) {\n const strategy = conflict.resolution.type;\n stats.resolutionsByStrategy[strategy] = (stats.resolutionsByStrategy[strategy] || 0) + 1;\n }\n } else {\n stats.activeConflicts++;\n }\n\n if ('resourceId' in conflict) {\n stats.conflictsByType.resource++;\n } else {\n stats.conflictsByType.task++;\n }\n }\n\n return stats;\n }\n}\n\n/**\n * Optimistic concurrency control for resource updates\n */\nexport class OptimisticLockManager {\n private versions = new Map<string, number>();\n private locks = new Map<string, { version: number; holder: string; timestamp: Date }>();\n\n constructor(private logger: ILogger) {}\n\n /**\n * Acquire an optimistic lock\n */\n acquireLock(resourceId: string, agentId: string): number {\n const currentVersion = this.versions.get(resourceId) || 0;\n\n this.locks.set(resourceId, {\n version: currentVersion,\n holder: agentId,\n timestamp: new Date(),\n });\n\n this.logger.debug('Optimistic lock acquired', {\n resourceId,\n agentId,\n version: currentVersion,\n });\n\n return currentVersion;\n }\n\n /**\n * Validate and update with optimistic lock\n */\n validateAndUpdate(resourceId: string, agentId: string, expectedVersion: number): boolean {\n const currentVersion = this.versions.get(resourceId) || 0;\n const lock = this.locks.get(resourceId);\n\n // Check if versions match\n if (currentVersion !== expectedVersion) {\n this.logger.warn('Optimistic lock conflict', {\n resourceId,\n agentId,\n expectedVersion,\n currentVersion,\n });\n return false;\n }\n\n // Check if this agent holds the lock\n if (!lock || lock.holder !== agentId) {\n this.logger.warn('Agent does not hold lock', {\n resourceId,\n agentId,\n });\n return false;\n }\n\n // Update version\n this.versions.set(resourceId, currentVersion + 1);\n this.locks.delete(resourceId);\n\n this.logger.debug('Optimistic update successful', {\n resourceId,\n agentId,\n newVersion: currentVersion + 1,\n });\n\n return true;\n }\n\n /**\n * Release a lock without updating\n */\n releaseLock(resourceId: string, agentId: string): void {\n const lock = this.locks.get(resourceId);\n\n if (lock && lock.holder === agentId) {\n this.locks.delete(resourceId);\n this.logger.debug('Optimistic lock released', {\n resourceId,\n agentId,\n });\n }\n }\n\n /**\n * Clean up stale locks\n */\n cleanupStaleLocks(maxAgeMs: number): number {\n const now = Date.now();\n let removed = 0;\n\n for (const [resourceId, lock] of this.locks) {\n if (now - lock.timestamp.getTime() > maxAgeMs) {\n this.locks.delete(resourceId);\n removed++;\n\n this.logger.warn('Removed stale lock', {\n resourceId,\n holder: lock.holder,\n age: now - lock.timestamp.getTime(),\n });\n }\n }\n\n return removed;\n }\n}\n"],"names":["PriorityResolutionStrategy","name","resolve","conflict","context","priorities","agents","map","agentId","priority","agentPriorities","get","sort","a","b","winner","losers","slice","p","type","reason","timestamp","Date","TimestampResolutionStrategy","timestamps","requestTimestamps","getTime","t","VotingResolutionStrategy","voteCounts","Map","voters","votes","set","length","maxVotes","push","ConflictResolver","strategies","conflicts","resolutionHistory","logger","eventBus","registerStrategy","strategy","info","reportResourceConflict","resourceId","id","now","Math","random","toString","substr","resolved","warn","emit","reportTaskConflict","taskId","resolveConflict","conflictId","strategyName","Error","resolution","autoResolve","preferredStrategy","index","getActiveConflicts","Array","from","values","filter","c","getConflictHistory","limit","cleanupOldConflicts","maxAgeMs","removed","delete","cutoffTime","r","getStats","stats","totalConflicts","size","activeConflicts","resolvedConflicts","resolutionsByStrategy","conflictsByType","resource","task","OptimisticLockManager","versions","locks","acquireLock","currentVersion","version","holder","debug","validateAndUpdate","expectedVersion","lock","newVersion","releaseLock","cleanupStaleLocks","age"],"mappings":"AA2CA,OAAO,MAAMA;IACXC,OAAO,WAAW;IAElB,MAAMC,QACJC,QAAyC,EACzCC,OAAiD,EACpB;QAC7B,MAAMC,aAAaF,SAASG,MAAM,CAACC,GAAG,CAAC,CAACC,UAAa,CAAA;gBACnDA;gBACAC,UAAUL,QAAQM,eAAe,CAACC,GAAG,CAACH,YAAY;YACpD,CAAA;QAGAH,WAAWO,IAAI,CAAC,CAACC,GAAGC,IAAMA,EAAEL,Q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AACf,MAAM,CAAC/B;YAClB,IAAI,CAACN,MAAM,CAACyD,KAAK,CAAC,4BAA4B;gBAC5CnD;gBACAvC;YACF;QACF;IACF;IAKAgG,kBAAkB5B,QAAgB,EAAU;QAC1C,MAAM3B,MAAM3B,KAAK2B,GAAG;QACpB,IAAI4B,UAAU;QAEd,KAAK,MAAM,CAAC9B,YAAYsD,KAAK,IAAI,IAAI,CAACR,KAAK,CAAE;YAC3C,IAAI5C,MAAMoD,KAAKhF,SAAS,CAACK,OAAO,KAAKkD,UAAU;gBAC7C,IAAI,CAACiB,KAAK,CAACf,MAAM,CAAC/B;gBAClB8B;gBAEA,IAAI,CAACpC,MAAM,CAACc,IAAI,CAAC,sBAAsB;oBACrCR;oBACAkD,QAAQI,KAAKJ,MAAM;oBACnBQ,KAAKxD,MAAMoD,KAAKhF,SAAS,CAACK,OAAO;gBACnC;YACF;QACF;QAEA,OAAOmD;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/coordination/conflict-resolution.ts"],"sourcesContent":["/**\n * Conflict resolution mechanisms for multi-agent coordination\n */\n\nimport type { ILogger } from '../core/logger.js';\nimport type { IEventBus } from '../core/event-bus.js';\nimport type { Task, Resource } from '../utils/types.js';\n\nexport interface ResourceConflict {\n id: string;\n resourceId: string;\n agents: string[];\n timestamp: Date;\n resolved: boolean;\n resolution?: ConflictResolution;\n}\n\nexport interface TaskConflict {\n id: string;\n taskId: string;\n agents: string[];\n type: 'assignment' | 'dependency' | 'output';\n timestamp: Date;\n resolved: boolean;\n resolution?: ConflictResolution;\n}\n\nexport interface ConflictResolution {\n type: 'priority' | 'timestamp' | 'vote' | 'manual' | 'retry';\n winner?: string;\n losers?: string[];\n reason: string;\n timestamp: Date;\n}\n\nexport interface ConflictResolutionStrategy {\n name: string;\n resolve(conflict: ResourceConflict | TaskConflict, context: any): Promise<ConflictResolution>;\n}\n\n/**\n * Priority-based resolution strategy\n */\nexport class PriorityResolutionStrategy implements ConflictResolutionStrategy {\n name = 'priority';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { agentPriorities: Map<string, number> },\n ): Promise<ConflictResolution> {\n const priorities = conflict.agents.map((agentId) => ({\n agentId,\n priority: context.agentPriorities.get(agentId) || 0,\n }));\n\n // Sort by priority (descending)\n priorities.sort((a, b) => b.priority - a.priority);\n\n const winner = priorities[0].agentId;\n const losers = priorities.slice(1).map((p) => p.agentId);\n\n return {\n type: 'priority',\n winner,\n losers,\n reason: `Agent ${winner} has highest priority (${priorities[0].priority})`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * First-come-first-served resolution strategy\n */\nexport class TimestampResolutionStrategy implements ConflictResolutionStrategy {\n name = 'timestamp';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { requestTimestamps: Map<string, Date> },\n ): Promise<ConflictResolution> {\n const timestamps = conflict.agents.map((agentId) => ({\n agentId,\n timestamp: context.requestTimestamps.get(agentId) || new Date(),\n }));\n\n // Sort by timestamp (ascending - earliest first)\n timestamps.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());\n\n const winner = timestamps[0].agentId;\n const losers = timestamps.slice(1).map((t) => t.agentId);\n\n return {\n type: 'timestamp',\n winner,\n losers,\n reason: `Agent ${winner} made the earliest request`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * Voting-based resolution strategy (for multi-agent consensus)\n */\nexport class VotingResolutionStrategy implements ConflictResolutionStrategy {\n name = 'vote';\n\n async resolve(\n conflict: ResourceConflict | TaskConflict,\n context: { votes: Map<string, string[]> }, // agentId -> votes for that agent\n ): Promise<ConflictResolution> {\n const voteCounts = new Map<string, number>();\n\n // Count votes\n for (const [agentId, voters] of context.votes) {\n voteCounts.set(agentId, voters.length);\n }\n\n // Find winner\n let maxVotes = 0;\n let winner = '';\n const losers: string[] = [];\n\n for (const [agentId, votes] of voteCounts) {\n if (votes > maxVotes) {\n if (winner) {\n losers.push(winner);\n }\n maxVotes = votes;\n winner = agentId;\n } else {\n losers.push(agentId);\n }\n }\n\n return {\n type: 'vote',\n winner,\n losers,\n reason: `Agent ${winner} received the most votes (${maxVotes})`,\n timestamp: new Date(),\n };\n }\n}\n\n/**\n * Conflict resolution manager\n */\nexport class ConflictResolver {\n private strategies = new Map<string, ConflictResolutionStrategy>();\n private conflicts = new Map<string, ResourceConflict | TaskConflict>();\n private resolutionHistory: ConflictResolution[] = [];\n\n constructor(\n private logger: ILogger,\n private eventBus: IEventBus,\n ) {\n // Register default strategies\n this.registerStrategy(new PriorityResolutionStrategy());\n this.registerStrategy(new TimestampResolutionStrategy());\n this.registerStrategy(new VotingResolutionStrategy());\n }\n\n /**\n * Register a conflict resolution strategy\n */\n registerStrategy(strategy: ConflictResolutionStrategy): void {\n this.strategies.set(strategy.name, strategy);\n this.logger.info('Registered conflict resolution strategy', { name: strategy.name });\n }\n\n /**\n * Report a resource conflict\n */\n async reportResourceConflict(resourceId: string, agents: string[]): Promise<ResourceConflict> {\n const conflict: ResourceConflict = {\n id: `conflict-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n resourceId,\n agents,\n timestamp: new Date(),\n resolved: false,\n };\n\n this.conflicts.set(conflict.id, conflict);\n this.logger.warn('Resource conflict reported', conflict);\n\n // Emit conflict event\n this.eventBus.emit('conflict:resource', conflict);\n\n return conflict;\n }\n\n /**\n * Report a task conflict\n */\n async reportTaskConflict(\n taskId: string,\n agents: string[],\n type: TaskConflict['type'],\n ): Promise<TaskConflict> {\n const conflict: TaskConflict = {\n id: `conflict-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n taskId,\n agents,\n type,\n timestamp: new Date(),\n resolved: false,\n };\n\n this.conflicts.set(conflict.id, conflict);\n this.logger.warn('Task conflict reported', conflict);\n\n // Emit conflict event\n this.eventBus.emit('conflict:task', conflict);\n\n return conflict;\n }\n\n /**\n * Resolve a conflict using a specific strategy\n */\n async resolveConflict(\n conflictId: string,\n strategyName: string,\n context: any,\n ): Promise<ConflictResolution> {\n const conflict = this.conflicts.get(conflictId);\n if (!conflict) {\n throw new Error(`Conflict not found: ${conflictId}`);\n }\n\n if (conflict.resolved) {\n throw new Error(`Conflict already resolved: ${conflictId}`);\n }\n\n const strategy = this.strategies.get(strategyName);\n if (!strategy) {\n throw new Error(`Strategy not found: ${strategyName}`);\n }\n\n // Resolve the conflict\n const resolution = await strategy.resolve(conflict, context);\n\n // Update conflict\n conflict.resolved = true;\n conflict.resolution = resolution;\n\n // Store in history\n this.resolutionHistory.push(resolution);\n\n // Emit resolution event\n this.eventBus.emit('conflict:resolved', {\n conflict,\n resolution,\n });\n\n this.logger.info('Conflict resolved', {\n conflictId,\n strategy: strategyName,\n resolution,\n });\n\n return resolution;\n }\n\n /**\n * Auto-resolve conflicts based on configuration\n */\n async autoResolve(\n conflictId: string,\n preferredStrategy: string = 'priority',\n ): Promise<ConflictResolution> {\n const conflict = this.conflicts.get(conflictId);\n if (!conflict) {\n throw new Error(`Conflict not found: ${conflictId}`);\n }\n\n // Build context based on conflict type\n const context: any = {};\n\n if (preferredStrategy === 'priority') {\n // In a real implementation, fetch agent priorities from configuration\n context.agentPriorities = new Map(\n conflict.agents.map((id, index) => [id, conflict.agents.length - index]),\n );\n } else if (preferredStrategy === 'timestamp') {\n // In a real implementation, fetch request timestamps\n context.requestTimestamps = new Map(\n conflict.agents.map((id, index) => [id, new Date(Date.now() - index * 1000)]),\n );\n }\n\n return this.resolveConflict(conflictId, preferredStrategy, context);\n }\n\n /**\n * Get active conflicts\n */\n getActiveConflicts(): Array<ResourceConflict | TaskConflict> {\n return Array.from(this.conflicts.values()).filter((c) => !c.resolved);\n }\n\n /**\n * Get conflict history\n */\n getConflictHistory(limit?: number): ConflictResolution[] {\n if (limit) {\n return this.resolutionHistory.slice(-limit);\n }\n return [...this.resolutionHistory];\n }\n\n /**\n * Clear resolved conflicts older than a certain age\n */\n cleanupOldConflicts(maxAgeMs: number): number {\n const now = Date.now();\n let removed = 0;\n\n for (const [id, conflict] of this.conflicts) {\n if (conflict.resolved && now - conflict.timestamp.getTime() > maxAgeMs) {\n this.conflicts.delete(id);\n removed++;\n }\n }\n\n // Also cleanup old history\n const cutoffTime = now - maxAgeMs;\n this.resolutionHistory = this.resolutionHistory.filter(\n (r) => r.timestamp.getTime() > cutoffTime,\n );\n\n return removed;\n }\n\n /**\n * Get conflict statistics\n */\n getStats(): Record<string, unknown> {\n const stats = {\n totalConflicts: this.conflicts.size,\n activeConflicts: 0,\n resolvedConflicts: 0,\n resolutionsByStrategy: {} as Record<string, number>,\n conflictsByType: {\n resource: 0,\n task: 0,\n },\n };\n\n for (const conflict of this.conflicts.values()) {\n if (conflict.resolved) {\n stats.resolvedConflicts++;\n\n if (conflict.resolution) {\n const strategy = conflict.resolution.type;\n stats.resolutionsByStrategy[strategy] = (stats.resolutionsByStrategy[strategy] || 0) + 1;\n }\n } else {\n stats.activeConflicts++;\n }\n\n if ('resourceId' in conflict) {\n stats.conflictsByType.resource++;\n } else {\n stats.conflictsByType.task++;\n }\n }\n\n return stats;\n }\n}\n\n/**\n * Optimistic concurrency control for resource updates\n */\nexport class OptimisticLockManager {\n private versions = new Map<string, number>();\n private locks = new Map<string, { version: number; holder: string; timestamp: Date }>();\n\n constructor(private logger: ILogger) {}\n\n /**\n * Acquire an optimistic lock\n */\n acquireLock(resourceId: string, agentId: string): number {\n const currentVersion = this.versions.get(resourceId) || 0;\n\n this.locks.set(resourceId, {\n version: currentVersion,\n holder: agentId,\n timestamp: new Date(),\n });\n\n this.logger.debug('Optimistic lock acquired', {\n resourceId,\n agentId,\n version: currentVersion,\n });\n\n return currentVersion;\n }\n\n /**\n * Validate and update with optimistic lock\n */\n validateAndUpdate(resourceId: string, agentId: string, expectedVersion: number): boolean {\n const currentVersion = this.versions.get(resourceId) || 0;\n const lock = this.locks.get(resourceId);\n\n // Check if versions match\n if (currentVersion !== expectedVersion) {\n this.logger.warn('Optimistic lock conflict', {\n resourceId,\n agentId,\n expectedVersion,\n currentVersion,\n });\n return false;\n }\n\n // Check if this agent holds the lock\n if (!lock || lock.holder !== agentId) {\n this.logger.warn('Agent does not hold lock', {\n resourceId,\n agentId,\n });\n return false;\n }\n\n // Update version\n this.versions.set(resourceId, currentVersion + 1);\n this.locks.delete(resourceId);\n\n this.logger.debug('Optimistic update successful', {\n resourceId,\n agentId,\n newVersion: currentVersion + 1,\n });\n\n return true;\n }\n\n /**\n * Release a lock without updating\n */\n releaseLock(resourceId: string, agentId: string): void {\n const lock = this.locks.get(resourceId);\n\n if (lock && lock.holder === agentId) {\n this.locks.delete(resourceId);\n this.logger.debug('Optimistic lock released', {\n resourceId,\n agentId,\n });\n }\n }\n\n /**\n * Clean up stale locks\n */\n cleanupStaleLocks(maxAgeMs: number): number {\n const now = Date.now();\n let removed = 0;\n\n for (const [resourceId, lock] of this.locks) {\n if (now - lock.timestamp.getTime() > maxAgeMs) {\n this.locks.delete(resourceId);\n removed++;\n\n this.logger.warn('Removed stale lock', {\n resourceId,\n holder: lock.holder,\n age: now - lock.timestamp.getTime(),\n });\n }\n }\n\n return removed;\n }\n}\n"],"names":["PriorityResolutionStrategy","name","resolve","conflict","context","priorities","agents","map","agentId","priority","agentPriorities","get","sort","a","b","winner","losers","slice","p","type","reason","timestamp","Date","TimestampResolutionStrategy","timestamps","requestTimestamps","getTime","t","VotingResolutionStrategy","voteCounts","Map","voters","votes","set","length","maxVotes","push","ConflictResolver","strategies","conflicts","resolutionHistory","logger","eventBus","registerStrategy","strategy","info","reportResourceConflict","resourceId","id","now","Math","random","toString","substr","resolved","warn","emit","reportTaskConflict","taskId","resolveConflict","conflictId","strategyName","Error","resolution","autoResolve","preferredStrategy","index","getActiveConflicts","Array","from","values","filter","c","getConflictHistory","limit","cleanupOldConflicts","maxAgeMs","removed","delete","cutoffTime","r","getStats","stats","totalConflicts","size","activeConflicts","resolvedConflicts","resolutionsByStrategy","conflictsByType","resource","task","OptimisticLockManager","versions","locks","acquireLock","currentVersion","version","holder","debug","validateAndUpdate","expectedVersion","lock","newVersion","releaseLock","cleanupStaleLocks","age"],"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AI,CAACN,MAAM,CAACyD,KAAK,CAAC,gCAAgC;YAChDnD;YACAvC;YACA8F,YAAYP,iBAAiB;QAC/B;QAEA,OAAO;IACT;IAKAQ,YAAYxD,UAAkB,EAAEvC,OAAe,EAAQ;QACrD,MAAM6F,OAAO,IAAI,CAACR,KAAK,CAAClF,GAAG,CAACoC;QAE5B,IAAIsD,QAAQA,KAAKJ,MAAM,KAAKzF,SAAS;YACnC,IAAI,CAACqF,KAAK,CAACf,MAAM,CAAC/B;YAClB,IAAI,CAACN,MAAM,CAACyD,KAAK,CAAC,4BAA4B;gBAC5CnD;gBACAvC;YACF;QACF;IACF;IAKAgG,kBAAkB5B,QAAgB,EAAU;QAC1C,MAAM3B,MAAM3B,KAAK2B,GAAG;QACpB,IAAI4B,UAAU;QAEd,KAAK,MAAM,CAAC9B,YAAYsD,KAAK,IAAI,IAAI,CAACR,KAAK,CAAE;YAC3C,IAAI5C,MAAMoD,KAAKhF,SAAS,CAACK,OAAO,KAAKkD,UAAU;gBAC7C,IAAI,CAACiB,KAAK,CAACf,MAAM,CAAC/B;gBAClB8B;gBAEA,IAAI,CAACpC,MAAM,CAACc,IAAI,CAAC,sBAAsB;oBACrCR;oBACAkD,QAAQI,KAAKJ,MAAM;oBACnBQ,KAAKxD,MAAMoD,KAAKhF,SAAS,CAACK,OAAO;gBACnC;YACF;QACF;QAEA,OAAOmD;IACT;AACF"}
|
|
@@ -90,7 +90,7 @@ export class LoadBalancer extends EventEmitter {
|
|
|
90
90
|
async selectAgent(task, availableAgents, constraints) {
|
|
91
91
|
const startTime = Date.now();
|
|
92
92
|
try {
|
|
93
|
-
|
|
93
|
+
const candidates = this.filterAgentsByConstraints(availableAgents, task, constraints);
|
|
94
94
|
if (candidates.length === 0) {
|
|
95
95
|
throw new Error('No suitable agents available for task');
|
|
96
96
|
}
|