@claude-flow/cli 3.0.0-alpha.13 → 3.0.0-alpha.14

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.
Files changed (102) hide show
  1. package/package.json +12 -4
  2. package/.agentic-flow/intelligence.json +0 -17
  3. package/.claude-flow/agents/store.json +0 -16
  4. package/.claude-flow/daemon-state.json +0 -123
  5. package/.claude-flow/daemon-test.log +0 -0
  6. package/.claude-flow/daemon.log +0 -0
  7. package/.claude-flow/daemon2.log +0 -0
  8. package/.claude-flow/daemon3.log +0 -0
  9. package/.claude-flow/hive-mind/state.json +0 -51
  10. package/.claude-flow/metrics/agent-metrics.json +0 -1
  11. package/.claude-flow/metrics/codebase-map.json +0 -11
  12. package/.claude-flow/metrics/consolidation.json +0 -6
  13. package/.claude-flow/metrics/performance.json +0 -87
  14. package/.claude-flow/metrics/security-audit.json +0 -10
  15. package/.claude-flow/metrics/task-metrics.json +0 -10
  16. package/.claude-flow/metrics/test-gaps.json +0 -6
  17. package/__tests__/README.md +0 -140
  18. package/__tests__/TEST_SUMMARY.md +0 -144
  19. package/__tests__/cli.test.ts +0 -558
  20. package/__tests__/commands.test.ts +0 -726
  21. package/__tests__/config-adapter.test.ts +0 -362
  22. package/__tests__/config-loading.test.ts +0 -106
  23. package/__tests__/coverage/.tmp/coverage-0.json +0 -1
  24. package/__tests__/coverage/.tmp/coverage-1.json +0 -1
  25. package/__tests__/coverage/.tmp/coverage-2.json +0 -1
  26. package/__tests__/coverage/.tmp/coverage-3.json +0 -1
  27. package/__tests__/coverage/.tmp/coverage-4.json +0 -1
  28. package/__tests__/coverage/.tmp/coverage-5.json +0 -1
  29. package/__tests__/mcp-client.test.ts +0 -480
  30. package/__tests__/p1-commands.test.ts +0 -1064
  31. package/agents/architect.yaml +0 -11
  32. package/agents/coder.yaml +0 -11
  33. package/agents/reviewer.yaml +0 -10
  34. package/agents/security-architect.yaml +0 -10
  35. package/agents/tester.yaml +0 -10
  36. package/docs/CONFIG_LOADING.md +0 -236
  37. package/docs/IMPLEMENTATION_COMPLETE.md +0 -421
  38. package/docs/MCP_CLIENT_GUIDE.md +0 -620
  39. package/docs/REFACTORING_SUMMARY.md +0 -247
  40. package/scripts/publish.sh +0 -46
  41. package/src/commands/agent.ts +0 -955
  42. package/src/commands/claims.ts +0 -317
  43. package/src/commands/completions.ts +0 -558
  44. package/src/commands/config.ts +0 -452
  45. package/src/commands/daemon.ts +0 -621
  46. package/src/commands/deployment.ts +0 -323
  47. package/src/commands/doctor.ts +0 -382
  48. package/src/commands/embeddings.ts +0 -686
  49. package/src/commands/hive-mind.ts +0 -928
  50. package/src/commands/hooks.ts +0 -2603
  51. package/src/commands/index.ts +0 -154
  52. package/src/commands/init.ts +0 -597
  53. package/src/commands/mcp.ts +0 -753
  54. package/src/commands/memory.ts +0 -1161
  55. package/src/commands/migrate.ts +0 -447
  56. package/src/commands/neural.ts +0 -253
  57. package/src/commands/performance.ts +0 -292
  58. package/src/commands/plugins.ts +0 -316
  59. package/src/commands/process.ts +0 -695
  60. package/src/commands/providers.ts +0 -259
  61. package/src/commands/security.ts +0 -288
  62. package/src/commands/session.ts +0 -891
  63. package/src/commands/start.ts +0 -457
  64. package/src/commands/status.ts +0 -736
  65. package/src/commands/swarm.ts +0 -648
  66. package/src/commands/task.ts +0 -792
  67. package/src/commands/workflow.ts +0 -742
  68. package/src/config-adapter.ts +0 -210
  69. package/src/index.ts +0 -443
  70. package/src/infrastructure/in-memory-repositories.ts +0 -310
  71. package/src/init/claudemd-generator.ts +0 -631
  72. package/src/init/executor.ts +0 -762
  73. package/src/init/helpers-generator.ts +0 -628
  74. package/src/init/index.ts +0 -60
  75. package/src/init/mcp-generator.ts +0 -83
  76. package/src/init/settings-generator.ts +0 -284
  77. package/src/init/statusline-generator.ts +0 -211
  78. package/src/init/types.ts +0 -447
  79. package/src/mcp-client.ts +0 -241
  80. package/src/mcp-server.ts +0 -577
  81. package/src/mcp-tools/agent-tools.ts +0 -466
  82. package/src/mcp-tools/config-tools.ts +0 -370
  83. package/src/mcp-tools/hive-mind-tools.ts +0 -521
  84. package/src/mcp-tools/hooks-tools.ts +0 -1888
  85. package/src/mcp-tools/index.ts +0 -16
  86. package/src/mcp-tools/memory-tools.ts +0 -270
  87. package/src/mcp-tools/session-tools.ts +0 -359
  88. package/src/mcp-tools/swarm-tools.ts +0 -105
  89. package/src/mcp-tools/task-tools.ts +0 -347
  90. package/src/mcp-tools/types.ts +0 -33
  91. package/src/mcp-tools/workflow-tools.ts +0 -573
  92. package/src/output.ts +0 -639
  93. package/src/parser.ts +0 -417
  94. package/src/prompt.ts +0 -619
  95. package/src/services/index.ts +0 -15
  96. package/src/services/worker-daemon.ts +0 -726
  97. package/src/suggest.ts +0 -245
  98. package/src/types.ts +0 -287
  99. package/tmp.json +0 -0
  100. package/tsconfig.json +0 -16
  101. package/tsconfig.tsbuildinfo +0 -1
  102. package/vitest.config.ts +0 -13
@@ -1,955 +0,0 @@
1
- /**
2
- * V3 CLI Agent Command
3
- * Agent management commands for spawning, listing, and controlling agents
4
- */
5
-
6
- import type { Command, CommandContext, CommandResult } from '../types.js';
7
- import { output } from '../output.js';
8
- import { select, confirm, input } from '../prompt.js';
9
- import { callMCPTool, MCPClientError } from '../mcp-client.js';
10
-
11
- // Available agent types with descriptions
12
- const AGENT_TYPES = [
13
- { value: 'coder', label: 'Coder', hint: 'Code development with neural patterns' },
14
- { value: 'researcher', label: 'Researcher', hint: 'Research with web access and data analysis' },
15
- { value: 'tester', label: 'Tester', hint: 'Comprehensive testing with automation' },
16
- { value: 'reviewer', label: 'Reviewer', hint: 'Code review with security and quality checks' },
17
- { value: 'architect', label: 'Architect', hint: 'System design with enterprise patterns' },
18
- { value: 'coordinator', label: 'Coordinator', hint: 'Multi-agent orchestration and workflow' },
19
- { value: 'analyst', label: 'Analyst', hint: 'Performance analysis and optimization' },
20
- { value: 'optimizer', label: 'Optimizer', hint: 'Performance optimization and bottleneck analysis' },
21
- { value: 'security-architect', label: 'Security Architect', hint: 'Security architecture and threat modeling' },
22
- { value: 'security-auditor', label: 'Security Auditor', hint: 'CVE remediation and security testing' },
23
- { value: 'memory-specialist', label: 'Memory Specialist', hint: 'AgentDB unification (150x-12,500x faster)' },
24
- { value: 'swarm-specialist', label: 'Swarm Specialist', hint: 'Unified coordination engine' },
25
- { value: 'performance-engineer', label: 'Performance Engineer', hint: '2.49x-7.47x optimization targets' },
26
- { value: 'core-architect', label: 'Core Architect', hint: 'Domain-driven design restructure' },
27
- { value: 'test-architect', label: 'Test Architect', hint: 'TDD London School methodology' }
28
- ];
29
-
30
- // Agent spawn subcommand
31
- const spawnCommand: Command = {
32
- name: 'spawn',
33
- description: 'Spawn a new agent',
34
- options: [
35
- {
36
- name: 'type',
37
- short: 't',
38
- description: 'Agent type to spawn',
39
- type: 'string',
40
- choices: AGENT_TYPES.map(a => a.value)
41
- },
42
- {
43
- name: 'name',
44
- short: 'n',
45
- description: 'Agent name/identifier',
46
- type: 'string'
47
- },
48
- {
49
- name: 'provider',
50
- short: 'p',
51
- description: 'Provider to use (anthropic, openrouter, ollama)',
52
- type: 'string',
53
- default: 'anthropic'
54
- },
55
- {
56
- name: 'model',
57
- short: 'm',
58
- description: 'Model to use',
59
- type: 'string'
60
- },
61
- {
62
- name: 'task',
63
- description: 'Initial task for the agent',
64
- type: 'string'
65
- },
66
- {
67
- name: 'timeout',
68
- description: 'Agent timeout in seconds',
69
- type: 'number',
70
- default: 300
71
- },
72
- {
73
- name: 'auto-tools',
74
- description: 'Enable automatic tool usage',
75
- type: 'boolean',
76
- default: true
77
- }
78
- ],
79
- examples: [
80
- { command: 'claude-flow agent spawn --type coder --name bot-1', description: 'Spawn a coder agent' },
81
- { command: 'claude-flow agent spawn -t researcher --task "Research React 19"', description: 'Spawn researcher with task' }
82
- ],
83
- action: async (ctx: CommandContext): Promise<CommandResult> => {
84
- let agentType = ctx.flags.type as string;
85
- let agentName = ctx.flags.name as string;
86
-
87
- // Interactive mode if type not specified
88
- if (!agentType && ctx.interactive) {
89
- agentType = await select({
90
- message: 'Select agent type:',
91
- options: AGENT_TYPES
92
- });
93
- }
94
-
95
- if (!agentType) {
96
- output.printError('Agent type is required. Use --type or -t flag.');
97
- return { success: false, exitCode: 1 };
98
- }
99
-
100
- // Generate name if not provided
101
- if (!agentName) {
102
- agentName = `${agentType}-${Date.now().toString(36)}`;
103
- }
104
-
105
- output.printInfo(`Spawning ${agentType} agent: ${output.highlight(agentName)}`);
106
-
107
- try {
108
- // Call MCP tool to spawn agent
109
- const result = await callMCPTool<{
110
- agentId: string;
111
- agentType: string;
112
- status: string;
113
- createdAt: string;
114
- }>('agent/spawn', {
115
- agentType,
116
- id: agentName,
117
- config: {
118
- provider: ctx.flags.provider || 'anthropic',
119
- model: ctx.flags.model,
120
- task: ctx.flags.task,
121
- timeout: ctx.flags.timeout,
122
- autoTools: ctx.flags.autoTools,
123
- },
124
- priority: 'normal',
125
- metadata: {
126
- name: agentName,
127
- capabilities: getAgentCapabilities(agentType),
128
- },
129
- });
130
-
131
- output.writeln();
132
- output.printTable({
133
- columns: [
134
- { key: 'property', header: 'Property', width: 15 },
135
- { key: 'value', header: 'Value', width: 40 }
136
- ],
137
- data: [
138
- { property: 'ID', value: result.agentId },
139
- { property: 'Type', value: result.agentType },
140
- { property: 'Name', value: agentName },
141
- { property: 'Status', value: result.status },
142
- { property: 'Created', value: result.createdAt },
143
- { property: 'Capabilities', value: getAgentCapabilities(agentType).join(', ') }
144
- ]
145
- });
146
-
147
- output.writeln();
148
- output.printSuccess(`Agent ${agentName} spawned successfully`);
149
-
150
- if (ctx.flags.format === 'json') {
151
- output.printJson(result);
152
- }
153
-
154
- return { success: true, data: result };
155
- } catch (error) {
156
- if (error instanceof MCPClientError) {
157
- output.printError(`Failed to spawn agent: ${error.message}`);
158
- } else {
159
- output.printError(`Unexpected error: ${String(error)}`);
160
- }
161
- return { success: false, exitCode: 1 };
162
- }
163
- }
164
- };
165
-
166
- // Agent list subcommand
167
- const listCommand: Command = {
168
- name: 'list',
169
- aliases: ['ls'],
170
- description: 'List all active agents',
171
- options: [
172
- {
173
- name: 'all',
174
- short: 'a',
175
- description: 'Include inactive agents',
176
- type: 'boolean',
177
- default: false
178
- },
179
- {
180
- name: 'type',
181
- short: 't',
182
- description: 'Filter by agent type',
183
- type: 'string'
184
- },
185
- {
186
- name: 'status',
187
- short: 's',
188
- description: 'Filter by status',
189
- type: 'string'
190
- }
191
- ],
192
- action: async (ctx: CommandContext): Promise<CommandResult> => {
193
- try {
194
- // Call MCP tool to list agents
195
- const result = await callMCPTool<{
196
- agents: Array<{
197
- id: string;
198
- agentType: string;
199
- status: 'active' | 'idle' | 'terminated';
200
- createdAt: string;
201
- lastActivityAt?: string;
202
- }>;
203
- total: number;
204
- }>('agent/list', {
205
- status: ctx.flags.all ? 'all' : ctx.flags.status || undefined,
206
- agentType: ctx.flags.type || undefined,
207
- limit: 100,
208
- });
209
-
210
- if (ctx.flags.format === 'json') {
211
- output.printJson(result);
212
- return { success: true, data: result };
213
- }
214
-
215
- output.writeln();
216
- output.writeln(output.bold('Active Agents'));
217
- output.writeln();
218
-
219
- if (result.agents.length === 0) {
220
- output.printInfo('No agents found matching criteria');
221
- return { success: true, data: result };
222
- }
223
-
224
- // Format for display
225
- const displayAgents = result.agents.map(agent => ({
226
- id: agent.id,
227
- type: agent.agentType,
228
- status: agent.status,
229
- created: new Date(agent.createdAt).toLocaleTimeString(),
230
- lastActivity: agent.lastActivityAt
231
- ? new Date(agent.lastActivityAt).toLocaleTimeString()
232
- : 'N/A',
233
- }));
234
-
235
- output.printTable({
236
- columns: [
237
- { key: 'id', header: 'ID', width: 20 },
238
- { key: 'type', header: 'Type', width: 15 },
239
- { key: 'status', header: 'Status', width: 12, format: formatStatus },
240
- { key: 'created', header: 'Created', width: 12 },
241
- { key: 'lastActivity', header: 'Last Activity', width: 12 }
242
- ],
243
- data: displayAgents
244
- });
245
-
246
- output.writeln();
247
- output.printInfo(`Total: ${result.total} agents`);
248
-
249
- return { success: true, data: result };
250
- } catch (error) {
251
- if (error instanceof MCPClientError) {
252
- output.printError(`Failed to list agents: ${error.message}`);
253
- } else {
254
- output.printError(`Unexpected error: ${String(error)}`);
255
- }
256
- return { success: false, exitCode: 1 };
257
- }
258
- }
259
- };
260
-
261
- // Agent status subcommand
262
- const statusCommand: Command = {
263
- name: 'status',
264
- description: 'Show detailed status of an agent',
265
- options: [
266
- {
267
- name: 'id',
268
- description: 'Agent ID',
269
- type: 'string'
270
- }
271
- ],
272
- action: async (ctx: CommandContext): Promise<CommandResult> => {
273
- let agentId = ctx.args[0] || ctx.flags.id as string;
274
-
275
- if (!agentId && ctx.interactive) {
276
- agentId = await input({
277
- message: 'Enter agent ID:',
278
- validate: (v) => v.length > 0 || 'Agent ID is required'
279
- });
280
- }
281
-
282
- if (!agentId) {
283
- output.printError('Agent ID is required');
284
- return { success: false, exitCode: 1 };
285
- }
286
-
287
- try {
288
- // Call MCP tool to get agent status
289
- const status = await callMCPTool<{
290
- id: string;
291
- agentType: string;
292
- status: 'active' | 'idle' | 'terminated';
293
- createdAt: string;
294
- lastActivityAt?: string;
295
- config?: Record<string, unknown>;
296
- metrics?: {
297
- tasksCompleted: number;
298
- tasksInProgress: number;
299
- tasksFailed: number;
300
- averageExecutionTime: number;
301
- uptime: number;
302
- };
303
- }>('agent/status', {
304
- agentId,
305
- includeMetrics: true,
306
- includeHistory: false,
307
- });
308
-
309
- if (ctx.flags.format === 'json') {
310
- output.printJson(status);
311
- return { success: true, data: status };
312
- }
313
-
314
- output.writeln();
315
- output.printBox(
316
- [
317
- `Type: ${status.agentType}`,
318
- `Status: ${formatStatus(status.status)}`,
319
- `Created: ${new Date(status.createdAt).toLocaleString()}`,
320
- `Last Activity: ${status.lastActivityAt ? new Date(status.lastActivityAt).toLocaleString() : 'N/A'}`
321
- ].join('\n'),
322
- `Agent: ${status.id}`
323
- );
324
-
325
- if (status.metrics) {
326
- output.writeln();
327
- output.writeln(output.bold('Metrics'));
328
- const avgExecTime = status.metrics.averageExecutionTime ?? 0;
329
- const uptime = status.metrics.uptime ?? 0;
330
- output.printTable({
331
- columns: [
332
- { key: 'metric', header: 'Metric', width: 25 },
333
- { key: 'value', header: 'Value', width: 15, align: 'right' }
334
- ],
335
- data: [
336
- { metric: 'Tasks Completed', value: status.metrics.tasksCompleted ?? 0 },
337
- { metric: 'Tasks In Progress', value: status.metrics.tasksInProgress ?? 0 },
338
- { metric: 'Tasks Failed', value: status.metrics.tasksFailed ?? 0 },
339
- { metric: 'Avg Execution Time', value: `${avgExecTime.toFixed(2)}ms` },
340
- { metric: 'Uptime', value: `${(uptime / 1000 / 60).toFixed(1)}m` }
341
- ]
342
- });
343
- }
344
-
345
- return { success: true, data: status };
346
- } catch (error) {
347
- if (error instanceof MCPClientError) {
348
- output.printError(`Failed to get agent status: ${error.message}`);
349
- } else {
350
- output.printError(`Unexpected error: ${String(error)}`);
351
- }
352
- return { success: false, exitCode: 1 };
353
- }
354
- }
355
- };
356
-
357
- // Agent stop subcommand
358
- const stopCommand: Command = {
359
- name: 'stop',
360
- aliases: ['kill'],
361
- description: 'Stop a running agent',
362
- options: [
363
- {
364
- name: 'force',
365
- short: 'f',
366
- description: 'Force stop without graceful shutdown',
367
- type: 'boolean',
368
- default: false
369
- },
370
- {
371
- name: 'timeout',
372
- description: 'Graceful shutdown timeout in seconds',
373
- type: 'number',
374
- default: 30
375
- }
376
- ],
377
- action: async (ctx: CommandContext): Promise<CommandResult> => {
378
- const agentId = ctx.args[0];
379
-
380
- if (!agentId) {
381
- output.printError('Agent ID is required');
382
- return { success: false, exitCode: 1 };
383
- }
384
-
385
- const force = ctx.flags.force as boolean;
386
-
387
- if (!force && ctx.interactive) {
388
- const confirmed = await confirm({
389
- message: `Are you sure you want to stop agent ${agentId}?`,
390
- default: false
391
- });
392
-
393
- if (!confirmed) {
394
- output.printInfo('Operation cancelled');
395
- return { success: true };
396
- }
397
- }
398
-
399
- output.printInfo(`Stopping agent ${agentId}...`);
400
-
401
- try {
402
- // Call MCP tool to terminate agent
403
- const result = await callMCPTool<{
404
- agentId: string;
405
- terminated: boolean;
406
- terminatedAt: string;
407
- }>('agent/terminate', {
408
- agentId,
409
- graceful: !force,
410
- reason: 'Stopped by user via CLI',
411
- });
412
-
413
- if (!force) {
414
- output.writeln(output.dim(' Completing current task...'));
415
- output.writeln(output.dim(' Saving state...'));
416
- output.writeln(output.dim(' Releasing resources...'));
417
- }
418
-
419
- output.printSuccess(`Agent ${agentId} stopped successfully`);
420
-
421
- if (ctx.flags.format === 'json') {
422
- output.printJson(result);
423
- }
424
-
425
- return { success: true, data: result };
426
- } catch (error) {
427
- if (error instanceof MCPClientError) {
428
- output.printError(`Failed to stop agent: ${error.message}`);
429
- } else {
430
- output.printError(`Unexpected error: ${String(error)}`);
431
- }
432
- return { success: false, exitCode: 1 };
433
- }
434
- }
435
- };
436
-
437
- // Agent metrics subcommand
438
- const metricsCommand: Command = {
439
- name: 'metrics',
440
- description: 'Show agent performance metrics',
441
- options: [
442
- {
443
- name: 'period',
444
- short: 'p',
445
- description: 'Time period (1h, 24h, 7d, 30d)',
446
- type: 'string',
447
- default: '24h'
448
- }
449
- ],
450
- action: async (ctx: CommandContext): Promise<CommandResult> => {
451
- const agentId = ctx.args[0];
452
- const period = ctx.flags.period as string;
453
-
454
- // Default metrics (updated by MCP agent/metrics when available)
455
- const metrics = {
456
- period,
457
- summary: {
458
- totalAgents: 4,
459
- activeAgents: 3,
460
- tasksCompleted: 127,
461
- avgSuccessRate: '96.2%',
462
- totalTokens: 1234567,
463
- avgResponseTime: '1.45s'
464
- },
465
- byType: [
466
- { type: 'coder', count: 2, tasks: 45, successRate: '97%' },
467
- { type: 'researcher', count: 1, tasks: 32, successRate: '95%' },
468
- { type: 'tester', count: 1, tasks: 50, successRate: '98%' }
469
- ],
470
- performance: {
471
- flashAttention: '2.8x speedup',
472
- memoryReduction: '52%',
473
- searchImprovement: '150x faster'
474
- }
475
- };
476
-
477
- if (ctx.flags.format === 'json') {
478
- output.printJson(metrics);
479
- return { success: true, data: metrics };
480
- }
481
-
482
- output.writeln();
483
- output.writeln(output.bold(`Agent Metrics (${period})`));
484
- output.writeln();
485
-
486
- output.printTable({
487
- columns: [
488
- { key: 'metric', header: 'Metric', width: 20 },
489
- { key: 'value', header: 'Value', width: 15, align: 'right' }
490
- ],
491
- data: [
492
- { metric: 'Total Agents', value: metrics.summary.totalAgents },
493
- { metric: 'Active Agents', value: metrics.summary.activeAgents },
494
- { metric: 'Tasks Completed', value: metrics.summary.tasksCompleted },
495
- { metric: 'Success Rate', value: metrics.summary.avgSuccessRate },
496
- { metric: 'Total Tokens', value: metrics.summary.totalTokens.toLocaleString() },
497
- { metric: 'Avg Response Time', value: metrics.summary.avgResponseTime }
498
- ]
499
- });
500
-
501
- output.writeln();
502
- output.writeln(output.bold('By Agent Type'));
503
- output.printTable({
504
- columns: [
505
- { key: 'type', header: 'Type', width: 12 },
506
- { key: 'count', header: 'Count', width: 8, align: 'right' },
507
- { key: 'tasks', header: 'Tasks', width: 8, align: 'right' },
508
- { key: 'successRate', header: 'Success', width: 10, align: 'right' }
509
- ],
510
- data: metrics.byType
511
- });
512
-
513
- output.writeln();
514
- output.writeln(output.bold('V3 Performance Gains'));
515
- output.printList([
516
- `Flash Attention: ${output.success(metrics.performance.flashAttention)}`,
517
- `Memory Reduction: ${output.success(metrics.performance.memoryReduction)}`,
518
- `Search: ${output.success(metrics.performance.searchImprovement)}`
519
- ]);
520
-
521
- return { success: true, data: metrics };
522
- }
523
- };
524
-
525
- // Agent pool subcommand
526
- const poolCommand: Command = {
527
- name: 'pool',
528
- description: 'Manage agent pool for scaling',
529
- options: [
530
- {
531
- name: 'size',
532
- short: 's',
533
- description: 'Pool size',
534
- type: 'number'
535
- },
536
- {
537
- name: 'min',
538
- description: 'Minimum pool size',
539
- type: 'number',
540
- default: 1
541
- },
542
- {
543
- name: 'max',
544
- description: 'Maximum pool size',
545
- type: 'number',
546
- default: 10
547
- },
548
- {
549
- name: 'auto-scale',
550
- short: 'a',
551
- description: 'Enable auto-scaling',
552
- type: 'boolean',
553
- default: true
554
- }
555
- ],
556
- examples: [
557
- { command: 'claude-flow agent pool --size 5', description: 'Set pool size' },
558
- { command: 'claude-flow agent pool --min 2 --max 15', description: 'Configure auto-scaling' }
559
- ],
560
- action: async (ctx: CommandContext): Promise<CommandResult> => {
561
- try {
562
- const result = await callMCPTool<{
563
- poolId: string;
564
- currentSize: number;
565
- minSize: number;
566
- maxSize: number;
567
- autoScale: boolean;
568
- utilization: number;
569
- agents: Array<{ id: string; type: string; status: string }>;
570
- }>('agent/pool', {
571
- size: ctx.flags.size,
572
- min: ctx.flags.min,
573
- max: ctx.flags.max,
574
- autoScale: ctx.flags.autoScale ?? true,
575
- });
576
-
577
- if (ctx.flags.format === 'json') {
578
- output.printJson(result);
579
- return { success: true, data: result };
580
- }
581
-
582
- output.writeln();
583
- const utilization = result.utilization ?? 0;
584
- output.printBox(
585
- [
586
- `Pool ID: ${result.poolId ?? 'default'}`,
587
- `Current Size: ${result.currentSize ?? 0}`,
588
- `Min/Max: ${result.minSize ?? 0}/${result.maxSize ?? 100}`,
589
- `Auto-Scale: ${result.autoScale ? 'Yes' : 'No'}`,
590
- `Utilization: ${(utilization * 100).toFixed(1)}%`
591
- ].join('\n'),
592
- 'Agent Pool'
593
- );
594
-
595
- const agents = result.agents ?? [];
596
- if (agents.length > 0) {
597
- output.writeln();
598
- output.writeln(output.bold('Pool Agents'));
599
- output.printTable({
600
- columns: [
601
- { key: 'id', header: 'ID', width: 20 },
602
- { key: 'type', header: 'Type', width: 15 },
603
- { key: 'status', header: 'Status', width: 12, format: formatStatus }
604
- ],
605
- data: agents
606
- });
607
- }
608
-
609
- return { success: true, data: result };
610
- } catch (error) {
611
- if (error instanceof MCPClientError) {
612
- output.printError(`Pool error: ${error.message}`);
613
- } else {
614
- output.printError(`Unexpected error: ${String(error)}`);
615
- }
616
- return { success: false, exitCode: 1 };
617
- }
618
- }
619
- };
620
-
621
- // Agent health subcommand
622
- const healthCommand: Command = {
623
- name: 'health',
624
- description: 'Show agent health and metrics',
625
- options: [
626
- {
627
- name: 'id',
628
- short: 'i',
629
- description: 'Agent ID (all if not specified)',
630
- type: 'string'
631
- },
632
- {
633
- name: 'detailed',
634
- short: 'd',
635
- description: 'Show detailed health metrics',
636
- type: 'boolean',
637
- default: false
638
- },
639
- {
640
- name: 'watch',
641
- short: 'w',
642
- description: 'Watch mode (refresh every 5s)',
643
- type: 'boolean',
644
- default: false
645
- }
646
- ],
647
- examples: [
648
- { command: 'claude-flow agent health', description: 'Show all agents health' },
649
- { command: 'claude-flow agent health -i agent-001 -d', description: 'Detailed health for specific agent' }
650
- ],
651
- action: async (ctx: CommandContext): Promise<CommandResult> => {
652
- const agentId = ctx.args[0] || ctx.flags.id as string;
653
- const detailed = ctx.flags.detailed as boolean;
654
-
655
- try {
656
- const result = await callMCPTool<{
657
- agents: Array<{
658
- id: string;
659
- type: string;
660
- health: 'healthy' | 'degraded' | 'unhealthy';
661
- uptime: number;
662
- memory: { used: number; limit: number };
663
- cpu: number;
664
- tasks: { active: number; queued: number; completed: number; failed: number };
665
- latency: { avg: number; p99: number };
666
- errors: { count: number; lastError?: string };
667
- }>;
668
- overall: {
669
- healthy: number;
670
- degraded: number;
671
- unhealthy: number;
672
- avgCpu: number;
673
- avgMemory: number;
674
- };
675
- }>('agent/health', {
676
- agentId,
677
- detailed,
678
- });
679
-
680
- if (ctx.flags.format === 'json') {
681
- output.printJson(result);
682
- return { success: true, data: result };
683
- }
684
-
685
- output.writeln();
686
- output.writeln(output.bold('Agent Health'));
687
- output.writeln();
688
-
689
- // Overall summary with null checks
690
- const overall = result.overall ?? { healthy: 0, degraded: 0, unhealthy: 0, avgCpu: 0, avgMemory: 0 };
691
- const avgCpu = overall.avgCpu ?? 0;
692
- const avgMemory = overall.avgMemory ?? 0;
693
- output.printBox(
694
- [
695
- `Healthy: ${output.success(String(overall.healthy ?? 0))}`,
696
- `Degraded: ${output.warning(String(overall.degraded ?? 0))}`,
697
- `Unhealthy: ${output.error(String(overall.unhealthy ?? 0))}`,
698
- `Avg CPU: ${avgCpu.toFixed(1)}%`,
699
- `Avg Memory: ${(avgMemory * 100).toFixed(1)}%`
700
- ].join(' | '),
701
- 'Overall Status'
702
- );
703
-
704
- const healthAgents = result.agents ?? [];
705
- output.writeln();
706
- output.printTable({
707
- columns: [
708
- { key: 'id', header: 'Agent ID', width: 18 },
709
- { key: 'type', header: 'Type', width: 12 },
710
- { key: 'health', header: 'Health', width: 10, format: formatHealthStatus },
711
- { key: 'cpu', header: 'CPU %', width: 8, align: 'right', format: (v) => `${Number(v ?? 0).toFixed(1)}%` },
712
- { key: 'memory', header: 'Memory', width: 10, align: 'right', format: (v: unknown) => {
713
- const mem = v as { used: number; limit: number } | undefined;
714
- if (!mem) return '0%';
715
- return `${(mem.used / mem.limit * 100).toFixed(0)}%`;
716
- }},
717
- { key: 'tasks', header: 'Tasks', width: 12, align: 'right', format: (v: unknown) => {
718
- const t = v as { active: number; completed: number } | undefined;
719
- if (!t) return '0/0';
720
- return `${t.active ?? 0}/${t.completed ?? 0}`;
721
- }}
722
- ],
723
- data: healthAgents
724
- });
725
-
726
- if (detailed && healthAgents.length > 0) {
727
- output.writeln();
728
- output.writeln(output.bold('Detailed Metrics'));
729
- for (const agent of healthAgents) {
730
- output.writeln();
731
- output.writeln(output.highlight(agent.id));
732
- const uptime = agent.uptime ?? 0;
733
- const latency = agent.latency ?? { avg: 0, p99: 0 };
734
- const tasks = agent.tasks ?? { completed: 0, failed: 0, queued: 0 };
735
- const errors = agent.errors ?? { count: 0 };
736
- output.printList([
737
- `Uptime: ${(uptime / 1000 / 60).toFixed(1)} min`,
738
- `Latency: avg ${(latency.avg ?? 0).toFixed(1)}ms, p99 ${(latency.p99 ?? 0).toFixed(1)}ms`,
739
- `Tasks: ${tasks.completed ?? 0} completed, ${tasks.failed ?? 0} failed, ${tasks.queued ?? 0} queued`,
740
- `Errors: ${errors.count ?? 0}${errors.lastError ? ` (${errors.lastError})` : ''}`
741
- ]);
742
- }
743
- }
744
-
745
- return { success: true, data: result };
746
- } catch (error) {
747
- if (error instanceof MCPClientError) {
748
- output.printError(`Health check error: ${error.message}`);
749
- } else {
750
- output.printError(`Unexpected error: ${String(error)}`);
751
- }
752
- return { success: false, exitCode: 1 };
753
- }
754
- }
755
- };
756
-
757
- // Agent logs subcommand
758
- const logsCommand: Command = {
759
- name: 'logs',
760
- description: 'Show agent activity logs',
761
- options: [
762
- {
763
- name: 'id',
764
- short: 'i',
765
- description: 'Agent ID',
766
- type: 'string'
767
- },
768
- {
769
- name: 'tail',
770
- short: 'n',
771
- description: 'Number of recent entries',
772
- type: 'number',
773
- default: 50
774
- },
775
- {
776
- name: 'level',
777
- short: 'l',
778
- description: 'Minimum log level',
779
- type: 'string',
780
- choices: ['debug', 'info', 'warn', 'error'],
781
- default: 'info'
782
- },
783
- {
784
- name: 'follow',
785
- short: 'f',
786
- description: 'Follow log output',
787
- type: 'boolean',
788
- default: false
789
- },
790
- {
791
- name: 'since',
792
- description: 'Show logs since (e.g., "1h", "30m")',
793
- type: 'string'
794
- }
795
- ],
796
- examples: [
797
- { command: 'claude-flow agent logs -i agent-001', description: 'Show agent logs' },
798
- { command: 'claude-flow agent logs -i agent-001 -f', description: 'Follow agent logs' },
799
- { command: 'claude-flow agent logs -l error --since 1h', description: 'Show errors from last hour' }
800
- ],
801
- action: async (ctx: CommandContext): Promise<CommandResult> => {
802
- const agentId = ctx.args[0] || ctx.flags.id as string;
803
- const tail = ctx.flags.tail as number;
804
- const level = ctx.flags.level as string;
805
-
806
- if (!agentId) {
807
- output.printError('Agent ID is required. Use --id or -i');
808
- return { success: false, exitCode: 1 };
809
- }
810
-
811
- try {
812
- const result = await callMCPTool<{
813
- agentId: string;
814
- entries: Array<{
815
- timestamp: string;
816
- level: 'debug' | 'info' | 'warn' | 'error';
817
- message: string;
818
- context?: Record<string, unknown>;
819
- }>;
820
- total: number;
821
- }>('agent/logs', {
822
- agentId,
823
- tail,
824
- level,
825
- since: ctx.flags.since,
826
- });
827
-
828
- if (ctx.flags.format === 'json') {
829
- output.printJson(result);
830
- return { success: true, data: result };
831
- }
832
-
833
- output.writeln();
834
- output.writeln(output.bold(`Logs for ${agentId}`));
835
- output.writeln(output.dim(`Showing ${result.entries.length} of ${result.total} entries`));
836
- output.writeln();
837
-
838
- for (const entry of result.entries) {
839
- const time = new Date(entry.timestamp).toLocaleTimeString();
840
- const levelStr = formatLogLevel(entry.level);
841
- output.writeln(`${output.dim(time)} ${levelStr} ${entry.message}`);
842
- if (entry.context && Object.keys(entry.context).length > 0) {
843
- output.writeln(output.dim(` ${JSON.stringify(entry.context)}`));
844
- }
845
- }
846
-
847
- return { success: true, data: result };
848
- } catch (error) {
849
- if (error instanceof MCPClientError) {
850
- output.printError(`Logs error: ${error.message}`);
851
- } else {
852
- output.printError(`Unexpected error: ${String(error)}`);
853
- }
854
- return { success: false, exitCode: 1 };
855
- }
856
- }
857
- };
858
-
859
- function formatHealthStatus(health: unknown): string {
860
- const h = String(health);
861
- switch (h) {
862
- case 'healthy':
863
- return output.success(h);
864
- case 'degraded':
865
- return output.warning(h);
866
- case 'unhealthy':
867
- return output.error(h);
868
- default:
869
- return h;
870
- }
871
- }
872
-
873
- function formatLogLevel(level: string): string {
874
- switch (level) {
875
- case 'debug':
876
- return output.dim('[DEBUG]');
877
- case 'info':
878
- return '[INFO] ';
879
- case 'warn':
880
- return output.warning('[WARN] ');
881
- case 'error':
882
- return output.error('[ERROR]');
883
- default:
884
- return `[${level.toUpperCase()}]`;
885
- }
886
- }
887
-
888
- // Main agent command
889
- export const agentCommand: Command = {
890
- name: 'agent',
891
- description: 'Agent management commands',
892
- subcommands: [spawnCommand, listCommand, statusCommand, stopCommand, metricsCommand, poolCommand, healthCommand, logsCommand],
893
- options: [],
894
- examples: [
895
- { command: 'claude-flow agent spawn -t coder', description: 'Spawn a coder agent' },
896
- { command: 'claude-flow agent list', description: 'List all agents' },
897
- { command: 'claude-flow agent status agent-001', description: 'Show agent status' }
898
- ],
899
- action: async (ctx: CommandContext): Promise<CommandResult> => {
900
- // Show help if no subcommand
901
- output.writeln();
902
- output.writeln(output.bold('Agent Management Commands'));
903
- output.writeln();
904
- output.writeln('Usage: claude-flow agent <subcommand> [options]');
905
- output.writeln();
906
- output.writeln('Subcommands:');
907
- output.printList([
908
- `${output.highlight('spawn')} - Spawn a new agent`,
909
- `${output.highlight('list')} - List all active agents`,
910
- `${output.highlight('status')} - Show detailed agent status`,
911
- `${output.highlight('stop')} - Stop a running agent`,
912
- `${output.highlight('metrics')} - Show agent metrics`
913
- ]);
914
- output.writeln();
915
- output.writeln('Run "claude-flow agent <subcommand> --help" for subcommand help');
916
-
917
- return { success: true };
918
- }
919
- };
920
-
921
- // Helper functions
922
- function getAgentCapabilities(type: string): string[] {
923
- const capabilities: Record<string, string[]> = {
924
- coder: ['code-generation', 'refactoring', 'debugging', 'testing'],
925
- researcher: ['web-search', 'data-analysis', 'summarization', 'citation'],
926
- tester: ['unit-testing', 'integration-testing', 'coverage-analysis', 'automation'],
927
- reviewer: ['code-review', 'security-audit', 'quality-check', 'documentation'],
928
- architect: ['system-design', 'pattern-analysis', 'scalability', 'documentation'],
929
- coordinator: ['task-orchestration', 'agent-management', 'workflow-control'],
930
- 'security-architect': ['threat-modeling', 'security-patterns', 'compliance', 'audit'],
931
- 'memory-specialist': ['vector-search', 'agentdb', 'caching', 'optimization'],
932
- 'performance-engineer': ['benchmarking', 'profiling', 'optimization', 'monitoring']
933
- };
934
-
935
- return capabilities[type] || ['general'];
936
- }
937
-
938
- function formatStatus(status: unknown): string {
939
- const statusStr = String(status);
940
- switch (statusStr) {
941
- case 'active':
942
- return output.success(statusStr);
943
- case 'idle':
944
- return output.warning(statusStr);
945
- case 'inactive':
946
- case 'stopped':
947
- return output.dim(statusStr);
948
- case 'error':
949
- return output.error(statusStr);
950
- default:
951
- return statusStr;
952
- }
953
- }
954
-
955
- export default agentCommand;