claude-flow 1.0.21 → 1.0.22

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/README.md CHANGED
@@ -138,6 +138,8 @@ Comprehensive documentation is available to help you get the most out of Claude-
138
138
  - **[Terminal Management](./docs/08-terminal-management.md)** - Terminal pooling and sessions
139
139
  - **[Troubleshooting](./docs/09-troubleshooting.md)** - Common issues and solutions
140
140
  - **[Advanced Usage](./docs/10-advanced-usage.md)** - Power user features
141
+ - **[Claude Spawning](./docs/11-claude-spawning.md)** - Spawning Claude instances
142
+ - **[Swarm Mode](./docs/12-swarm.md)** - Self-orchestrating agent swarms šŸ
141
143
  - **[CLI Reference](./docs/cli-reference.md)** - Complete command documentation
142
144
 
143
145
  ## šŸ’” **Quick Start Guide**
@@ -189,7 +191,33 @@ npx claude-flow claude spawn "fix payment bug" --tools "View,Edit,Bash" --no-per
189
191
  npx claude-flow claude batch examples/claude-workflow.json --dry-run
190
192
  ```
191
193
 
192
- ### 6. **Monitor System Status**
194
+ ### 6. **Claude Swarm Mode** šŸ šŸ†•
195
+ ```bash
196
+ # Create self-orchestrating agent swarms
197
+ npx claude-flow swarm "Build a complete e-commerce platform"
198
+
199
+ # Research-focused swarm
200
+ npx claude-flow swarm "Research cloud architecture best practices" \
201
+ --strategy research --research --max-agents 8
202
+
203
+ # Development swarm with review
204
+ npx claude-flow swarm "Refactor authentication system" \
205
+ --strategy development --review --parallel
206
+
207
+ # Complex project with coordinator
208
+ npx claude-flow swarm "Migrate monolithic app to microservices" \
209
+ --coordinator --max-depth 4 --timeout 120
210
+
211
+ # Preview swarm configuration
212
+ npx claude-flow swarm "Create mobile app" --dry-run --verbose
213
+
214
+ # Run with visual monitoring (recommended for visibility)
215
+ ./bin/claude-flow-swarm-monitor "Build REST API" --strategy development
216
+ ```
217
+
218
+ **Note**: Swarm mode currently spawns a single orchestrator that simulates multiple agents. For true multi-instance spawning, see [SWARM_VISIBILITY.md](./SWARM_VISIBILITY.md).
219
+
220
+ ### 7. **Monitor System Status**
193
221
  ```bash
194
222
  # Check system health
195
223
  npx claude-flow status
@@ -477,7 +505,7 @@ claude-flow task workflow example-workflow.json
477
505
  ## Development
478
506
 
479
507
  ### Prerequisites
480
- - Deno 1.38+ or Node.js 16+
508
+ - Deno 1.38+ or Node.js 16+ (Install Deno: https://deno.land/#installation)
481
509
  - Git
482
510
 
483
511
  ### Setup
package/bin/claude-flow CHANGED
Binary file
@@ -0,0 +1,19 @@
1
+ #!/bin/bash
2
+ # Claude-Flow Swarm Mode Wrapper
3
+ # This script wraps the swarm demo to work with the installed Deno
4
+
5
+ # Find deno in the path
6
+ DENO_PATH=$(which deno 2>/dev/null || echo "/home/codespace/.deno/bin/deno")
7
+
8
+ if [ ! -x "$DENO_PATH" ]; then
9
+ echo "Error: Deno is not installed or not in PATH"
10
+ echo "Please install Deno first: https://deno.land/#installation"
11
+ exit 1
12
+ fi
13
+
14
+ # Get the directory of this script
15
+ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
16
+ SWARM_DEMO="$SCRIPT_DIR/../swarm-demo.ts"
17
+
18
+ # Run the swarm demo with all arguments
19
+ exec "$DENO_PATH" run --allow-all "$SWARM_DEMO" "$@"
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "claude-flow",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
4
4
  "description": "Advanced AI agent orchestration system for Claude Code",
5
5
  "main": "src/cli/main.ts",
6
6
  "bin": {
7
- "claude-flow": "./bin/claude-flow"
7
+ "claude-flow": "./bin/claude-flow",
8
+ "claude-flow-swarm": "./bin/claude-flow-swarm"
8
9
  },
9
10
  "scripts": {
10
11
  "postinstall": "node scripts/install.js",
@@ -36,7 +37,9 @@
36
37
  },
37
38
  "files": [
38
39
  "bin/claude-flow",
40
+ "bin/claude-flow-swarm",
39
41
  "src/",
42
+ "swarm-demo.ts",
40
43
  "scripts/install.js",
41
44
  "README.md",
42
45
  "LICENSE",
@@ -86,7 +86,7 @@ class CLI {
86
86
  string: this.getStringFlags(),
87
87
  alias: this.getAliases(),
88
88
  default: this.getDefaults(),
89
- stopEarly: true,
89
+ stopEarly: false,
90
90
  unknown: () => true,
91
91
  });
92
92
 
@@ -7,6 +7,7 @@ import { MemoryManager } from "../../memory/manager.ts";
7
7
  import { EventBus } from "../../core/event-bus.ts";
8
8
  import { Logger } from "../../core/logger.ts";
9
9
  import { JsonPersistenceManager } from "../../core/json-persistence.ts";
10
+ import { swarmAction } from "./swarm.ts";
10
11
 
11
12
  let orchestrator: Orchestrator | null = null;
12
13
  let configManager: ConfigManager | null = null;
@@ -993,6 +994,84 @@ export function setupCommands(cli: CLI): void {
993
994
  },
994
995
  });
995
996
 
997
+ // Swarm command
998
+ cli.command({
999
+ name: "swarm",
1000
+ description: "Create self-orchestrating Claude agent swarms",
1001
+ options: [
1002
+ {
1003
+ name: "strategy",
1004
+ short: "s",
1005
+ description: "Orchestration strategy (auto, research, development, analysis)",
1006
+ type: "string",
1007
+ default: "auto",
1008
+ },
1009
+ {
1010
+ name: "max-agents",
1011
+ description: "Maximum number of agents to spawn",
1012
+ type: "number",
1013
+ default: 5,
1014
+ },
1015
+ {
1016
+ name: "max-depth",
1017
+ description: "Maximum delegation depth",
1018
+ type: "number",
1019
+ default: 3,
1020
+ },
1021
+ {
1022
+ name: "research",
1023
+ description: "Enable research capabilities for all agents",
1024
+ type: "boolean",
1025
+ },
1026
+ {
1027
+ name: "parallel",
1028
+ description: "Enable parallel execution",
1029
+ type: "boolean",
1030
+ },
1031
+ {
1032
+ name: "memory-namespace",
1033
+ description: "Shared memory namespace",
1034
+ type: "string",
1035
+ default: "swarm",
1036
+ },
1037
+ {
1038
+ name: "timeout",
1039
+ description: "Swarm timeout in minutes",
1040
+ type: "number",
1041
+ default: 60,
1042
+ },
1043
+ {
1044
+ name: "review",
1045
+ description: "Enable peer review between agents",
1046
+ type: "boolean",
1047
+ },
1048
+ {
1049
+ name: "coordinator",
1050
+ description: "Spawn dedicated coordinator agent",
1051
+ type: "boolean",
1052
+ },
1053
+ {
1054
+ name: "config",
1055
+ short: "c",
1056
+ description: "MCP config file",
1057
+ type: "string",
1058
+ },
1059
+ {
1060
+ name: "verbose",
1061
+ short: "v",
1062
+ description: "Enable verbose output",
1063
+ type: "boolean",
1064
+ },
1065
+ {
1066
+ name: "dry-run",
1067
+ short: "d",
1068
+ description: "Preview swarm configuration",
1069
+ type: "boolean",
1070
+ },
1071
+ ],
1072
+ action: swarmAction,
1073
+ });
1074
+
996
1075
  // Help command
997
1076
  cli.command({
998
1077
  name: "help",
@@ -1027,6 +1106,34 @@ export function setupCommands(cli: CLI): void {
1027
1106
  console.log(` ${blue("claude-flow claude batch")} workflow.json --dry-run`);
1028
1107
  console.log();
1029
1108
  console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/11-claude-spawning.md");
1109
+ } else if (command === "swarm") {
1110
+ console.log(bold(blue("Claude Swarm Mode")));
1111
+ console.log();
1112
+ console.log("Create self-orchestrating Claude agent swarms to tackle complex objectives.");
1113
+ console.log();
1114
+ console.log(bold("Usage:"));
1115
+ console.log(" claude-flow swarm <objective> [options]");
1116
+ console.log();
1117
+ console.log(bold("Options:"));
1118
+ console.log(" -s, --strategy <s> Orchestration strategy (auto, research, development, analysis)");
1119
+ console.log(" --max-agents <n> Maximum number of agents (default: 5)");
1120
+ console.log(" --max-depth <n> Maximum delegation depth (default: 3)");
1121
+ console.log(" --research Enable research capabilities for all agents");
1122
+ console.log(" --parallel Enable parallel execution");
1123
+ console.log(" --memory-namespace <ns> Shared memory namespace (default: swarm)");
1124
+ console.log(" --timeout <minutes> Swarm timeout in minutes (default: 60)");
1125
+ console.log(" --review Enable peer review between agents");
1126
+ console.log(" --coordinator Spawn dedicated coordinator agent");
1127
+ console.log(" -c, --config <file> MCP config file");
1128
+ console.log(" -v, --verbose Enable verbose output");
1129
+ console.log(" -d, --dry-run Preview swarm configuration");
1130
+ console.log();
1131
+ console.log(bold("Examples:"));
1132
+ console.log(` ${blue("claude-flow swarm")} "Build a REST API"`);
1133
+ console.log(` ${blue("claude-flow swarm")} "Research cloud architecture" --strategy research --research`);
1134
+ console.log(` ${blue("claude-flow swarm")} "Migrate app to microservices" --coordinator --review`);
1135
+ console.log();
1136
+ console.log("For more information, see: https://github.com/ruvnet/claude-code-flow/docs/12-swarm.md");
1030
1137
  } else {
1031
1138
  // Show general help
1032
1139
  cli.showHelp();
@@ -0,0 +1,353 @@
1
+ /**
2
+ * Swarm agent spawning utilities
3
+ */
4
+
5
+ import { generateId } from '../../utils/helpers.ts';
6
+ import { info, success, error, warning } from '../cli-core.ts';
7
+
8
+ export interface SwarmAgent {
9
+ id: string;
10
+ type: 'researcher' | 'developer' | 'analyst' | 'reviewer' | 'coordinator';
11
+ name: string;
12
+ task: string;
13
+ parentId?: string;
14
+ terminalId?: string;
15
+ status: 'pending' | 'active' | 'completed' | 'failed';
16
+ }
17
+
18
+ export interface SwarmState {
19
+ swarmId: string;
20
+ objective: string;
21
+ agents: Map<string, SwarmAgent>;
22
+ tasks: Map<string, any>;
23
+ startTime: number;
24
+ }
25
+
26
+ // Global swarm state registry
27
+ const swarmStates = new Map<string, SwarmState>();
28
+
29
+ /**
30
+ * Initialize a new swarm
31
+ */
32
+ export function initializeSwarm(swarmId: string, objective: string): SwarmState {
33
+ const state: SwarmState = {
34
+ swarmId,
35
+ objective,
36
+ agents: new Map(),
37
+ tasks: new Map(),
38
+ startTime: Date.now(),
39
+ };
40
+
41
+ swarmStates.set(swarmId, state);
42
+ return state;
43
+ }
44
+
45
+ /**
46
+ * Get swarm state
47
+ */
48
+ export function getSwarmState(swarmId: string): SwarmState | undefined {
49
+ return swarmStates.get(swarmId);
50
+ }
51
+
52
+ /**
53
+ * Spawn a new agent in a terminal
54
+ */
55
+ export async function spawnSwarmAgent(
56
+ swarmId: string,
57
+ agentType: SwarmAgent['type'],
58
+ task: string,
59
+ parentId?: string
60
+ ): Promise<SwarmAgent> {
61
+ const state = getSwarmState(swarmId);
62
+ if (!state) {
63
+ throw new Error(`Swarm ${swarmId} not found`);
64
+ }
65
+
66
+ const agentId = generateId(`${agentType}-agent`);
67
+ const agent: SwarmAgent = {
68
+ id: agentId,
69
+ type: agentType,
70
+ name: `${agentType.charAt(0).toUpperCase() + agentType.slice(1)} Agent ${agentId.slice(-6)}`,
71
+ task,
72
+ parentId,
73
+ status: 'pending',
74
+ };
75
+
76
+ state.agents.set(agentId, agent);
77
+
78
+ info(`šŸ¤– Spawning ${agent.name}...`);
79
+
80
+ try {
81
+ // Create agent prompt
82
+ const agentPrompt = buildAgentPrompt(agent, state);
83
+
84
+ // Check if we're in VS Code
85
+ if (Deno.env.get('TERM_PROGRAM') === 'vscode') {
86
+ await spawnVSCodeAgent(swarmId, agent, agentPrompt);
87
+ } else {
88
+ await spawnNativeAgent(swarmId, agent, agentPrompt);
89
+ }
90
+
91
+ agent.status = 'active';
92
+ success(`āœ… ${agent.name} spawned successfully`);
93
+
94
+ } catch (err) {
95
+ agent.status = 'failed';
96
+ error(`Failed to spawn ${agent.name}: ${(err as Error).message}`);
97
+ }
98
+
99
+ return agent;
100
+ }
101
+
102
+ /**
103
+ * Build agent-specific prompt
104
+ */
105
+ function buildAgentPrompt(agent: SwarmAgent, state: SwarmState): string {
106
+ const roleDescriptions = {
107
+ researcher: 'gather information, analyze sources, and provide insights',
108
+ developer: 'implement code, create features, and fix bugs',
109
+ analyst: 'analyze data, identify patterns, and provide recommendations',
110
+ reviewer: 'review code and outputs, ensure quality, and provide feedback',
111
+ coordinator: 'coordinate subtasks, manage dependencies, and track progress',
112
+ };
113
+
114
+ return `
115
+ # Claude Swarm Agent Task
116
+
117
+ You are a **${agent.name}** in a collaborative swarm working on:
118
+ **${state.objective}**
119
+
120
+ ## Your Role:
121
+ As a ${agent.type}, your primary responsibility is to ${roleDescriptions[agent.type]}.
122
+
123
+ ## Your Specific Task:
124
+ ${agent.task}
125
+
126
+ ## Swarm Context:
127
+ - Swarm ID: ${state.swarmId}
128
+ - Parent Agent: ${agent.parentId || 'Master Orchestrator'}
129
+ - Memory Namespace: swarm-${state.swarmId}
130
+
131
+ ## Collaboration Guidelines:
132
+ 1. Store all discoveries and outputs in the shared memory namespace
133
+ 2. Check memory for existing work before starting new tasks
134
+ 3. Coordinate with other agents via memory updates
135
+ 4. Report progress regularly
136
+ 5. Request help or spawn sub-agents if needed
137
+
138
+ ## Available Commands:
139
+ - \`claude-flow memory store <key> <value>\` - Store findings
140
+ - \`claude-flow memory retrieve <key>\` - Get shared data
141
+ - \`claude-flow task create <type> "<description>"\` - Create subtasks
142
+ - \`claude-flow agent spawn <type> --task "<task>"\` - Spawn sub-agents
143
+
144
+ ## Output Format:
145
+ Provide regular status updates:
146
+ \`\`\`
147
+ [AGENT STATUS]
148
+ - Agent: ${agent.id}
149
+ - Progress: <percentage>
150
+ - Current Activity: <description>
151
+ - Findings: <summary>
152
+ \`\`\`
153
+
154
+ Begin working on your task now.
155
+ `;
156
+ }
157
+
158
+ /**
159
+ * Spawn agent in VS Code terminal
160
+ */
161
+ async function spawnVSCodeAgent(swarmId: string, agent: SwarmAgent, prompt: string): Promise<void> {
162
+ // Write prompt to temp file
163
+ const tempDir = await Deno.makeTempDir();
164
+ const promptFile = `${tempDir}/agent-${agent.id}-prompt.txt`;
165
+ await Deno.writeTextFile(promptFile, prompt);
166
+
167
+ // Create agent script
168
+ const scriptContent = `#!/bin/bash
169
+ # Claude Swarm Agent: ${agent.name}
170
+ # Task: ${agent.task}
171
+
172
+ export CLAUDE_SWARM_ID="${swarmId}"
173
+ export CLAUDE_SWARM_AGENT_ID="${agent.id}"
174
+ export CLAUDE_SWARM_AGENT_TYPE="${agent.type}"
175
+ export CLAUDE_SWARM_MEMORY_NS="swarm-${swarmId}"
176
+
177
+ echo "šŸ¤– ${agent.name} Starting..."
178
+ echo "šŸ“‹ Task: ${agent.task}"
179
+ echo ""
180
+
181
+ # Run Claude with the agent prompt
182
+ claude "$(cat "${promptFile}")" \\
183
+ --allowedTools View,Edit,Replace,GlobTool,GrepTool,LS,Bash,WebFetchTool \\
184
+ --verbose
185
+
186
+ echo ""
187
+ echo "āœ… Agent task completed"
188
+ `;
189
+
190
+ const scriptFile = `${tempDir}/agent-${agent.id}-run.sh`;
191
+ await Deno.writeTextFile(scriptFile, scriptContent);
192
+ await Deno.chmod(scriptFile, 0o755);
193
+
194
+ // Use AppleScript to create new terminal tab in VS Code
195
+ if (Deno.build.os === 'darwin') {
196
+ // macOS: Use AppleScript to simulate keyboard shortcut
197
+ const appleScript = `
198
+ tell application "Visual Studio Code"
199
+ activate
200
+ end tell
201
+ delay 0.5
202
+ tell application "System Events"
203
+ keystroke "\`" using {control down, shift down}
204
+ end tell
205
+ delay 0.5
206
+ tell application "System Events"
207
+ keystroke "${scriptFile}"
208
+ key code 36
209
+ end tell
210
+ `;
211
+
212
+ const osascriptCommand = new Deno.Command('osascript', {
213
+ args: ['-e', appleScript],
214
+ });
215
+
216
+ await osascriptCommand.output();
217
+ } else {
218
+ // For other platforms, fall back to creating a tasks.json file
219
+ await createVSCodeTask(swarmId, agent, scriptFile);
220
+ }
221
+
222
+ // Clean up after delay
223
+ setTimeout(async () => {
224
+ try {
225
+ await Deno.remove(tempDir, { recursive: true });
226
+ } catch {}
227
+ }, 60000);
228
+ }
229
+
230
+ /**
231
+ * Create VS Code task for agent
232
+ */
233
+ async function createVSCodeTask(swarmId: string, agent: SwarmAgent, scriptFile: string): Promise<void> {
234
+ const tasksDir = '.vscode';
235
+ const tasksFile = `${tasksDir}/tasks.json`;
236
+
237
+ // Ensure .vscode directory exists
238
+ await Deno.mkdir(tasksDir, { recursive: true });
239
+
240
+ // Read existing tasks or create new
241
+ let tasks: any = {
242
+ version: "2.0.0",
243
+ tasks: []
244
+ };
245
+
246
+ try {
247
+ const existing = await Deno.readTextFile(tasksFile);
248
+ tasks = JSON.parse(existing);
249
+ } catch {}
250
+
251
+ // Add new task for agent
252
+ const agentTask = {
253
+ label: `Swarm Agent: ${agent.name}`,
254
+ type: "shell",
255
+ command: scriptFile,
256
+ presentation: {
257
+ echo: true,
258
+ reveal: "always",
259
+ focus: false,
260
+ panel: "new",
261
+ showReuseMessage: false,
262
+ clear: false
263
+ },
264
+ problemMatcher: [],
265
+ isBackground: true,
266
+ runOptions: {
267
+ runOn: "default"
268
+ }
269
+ };
270
+
271
+ tasks.tasks.push(agentTask);
272
+
273
+ // Write updated tasks
274
+ await Deno.writeTextFile(tasksFile, JSON.stringify(tasks, null, 2));
275
+
276
+ // Execute the task
277
+ const runTaskCommand = new Deno.Command('code', {
278
+ args: ['--command', `workbench.action.tasks.runTask`, '--', `Swarm Agent: ${agent.name}`],
279
+ });
280
+
281
+ await runTaskCommand.output();
282
+ }
283
+
284
+ /**
285
+ * Spawn agent in native terminal
286
+ */
287
+ async function spawnNativeAgent(swarmId: string, agent: SwarmAgent, prompt: string): Promise<void> {
288
+ // For native terminals, we'll use the system's terminal emulator
289
+ const terminalCommands = {
290
+ darwin: ['osascript', '-e', `tell application "Terminal" to do script "claude '${prompt.replace(/'/g, "'\\''")}'"`],
291
+ linux: ['gnome-terminal', '--', 'claude', prompt],
292
+ windows: ['cmd', '/c', 'start', 'claude', prompt],
293
+ };
294
+
295
+ const platform = Deno.build.os;
296
+ const command = terminalCommands[platform as keyof typeof terminalCommands];
297
+
298
+ if (!command) {
299
+ throw new Error(`Unsupported platform: ${platform}`);
300
+ }
301
+
302
+ const process = new Deno.Command(command[0], {
303
+ args: command.slice(1),
304
+ });
305
+
306
+ await process.output();
307
+ }
308
+
309
+ /**
310
+ * Monitor swarm progress
311
+ */
312
+ export async function monitorSwarm(swarmId: string): Promise<void> {
313
+ const state = getSwarmState(swarmId);
314
+ if (!state) {
315
+ error(`Swarm ${swarmId} not found`);
316
+ return;
317
+ }
318
+
319
+ console.log('\nšŸ“Š Swarm Status Monitor');
320
+ console.log('='.repeat(50));
321
+
322
+ const updateInterval = setInterval(() => {
323
+ const runtime = Math.floor((Date.now() - state.startTime) / 1000);
324
+ const activeAgents = Array.from(state.agents.values()).filter(a => a.status === 'active').length;
325
+ const completedAgents = Array.from(state.agents.values()).filter(a => a.status === 'completed').length;
326
+
327
+ console.clear();
328
+ console.log(`šŸ Swarm ${swarmId}`);
329
+ console.log(`šŸ“‹ Objective: ${state.objective}`);
330
+ console.log(`ā±ļø Runtime: ${runtime}s`);
331
+ console.log(`šŸ¤– Agents: ${activeAgents} active, ${completedAgents} completed`);
332
+ console.log('\nAgent Status:');
333
+
334
+ for (const agent of state.agents.values()) {
335
+ const statusEmoji = {
336
+ pending: 'ā³',
337
+ active: '🟢',
338
+ completed: 'āœ…',
339
+ failed: 'āŒ',
340
+ };
341
+
342
+ console.log(` ${statusEmoji[agent.status]} ${agent.name}: ${agent.task.substring(0, 50)}...`);
343
+ }
344
+
345
+ }, 2000);
346
+
347
+ // Stop monitoring after timeout or manual interrupt
348
+ process.on('SIGINT', () => {
349
+ clearInterval(updateInterval);
350
+ console.log('\n\nšŸ‘‹ Swarm monitoring stopped');
351
+ process.exit(0);
352
+ });
353
+ }