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.
@@ -0,0 +1,513 @@
1
+ /**
2
+ * Claude Swarm Mode - Self-orchestrating agent swarms
3
+ */
4
+
5
+ import { generateId } from '../../utils/helpers.ts';
6
+ import { success, error, warning, info } from "../cli-core.ts";
7
+ import type { CommandContext } from "../cli-core.ts";
8
+ import { TerminalManager } from '../../terminal/manager.ts';
9
+ import { EventBus } from '../../core/event-bus.ts';
10
+ import { Logger } from '../../core/logger.ts';
11
+ import { ConfigManager } from '../../core/config.ts';
12
+ import type { AgentProfile, TerminalConfig } from '../../utils/types.ts';
13
+ import { initializeSwarm, spawnSwarmAgent, monitorSwarm } from './swarm-spawn.ts';
14
+
15
+ export async function swarmAction(ctx: CommandContext) {
16
+ // Debug: Log what we received early
17
+ console.log("\n=== SWARM DEBUG ===");
18
+ console.log("Raw args:", ctx.args);
19
+ console.log("Flags:", ctx.flags);
20
+ console.log("dry-run flag:", ctx.flags['dry-run']);
21
+ console.log("vscode flag:", ctx.flags.vscode);
22
+ console.log("==================\n");
23
+
24
+ // First check if help is requested
25
+ if (ctx.flags.help || ctx.flags.h) {
26
+ // Show help is handled by the CLI framework
27
+ return;
28
+ }
29
+
30
+ // The objective should be all the non-flag arguments joined together
31
+ const objective = ctx.args.join(' ').trim();
32
+
33
+ if (!objective) {
34
+ error("Usage: swarm <objective>");
35
+ console.log("\nExamples:");
36
+ console.log(' claude-flow swarm "Build a REST API"');
37
+ console.log(' claude-flow swarm "Research cloud architecture"');
38
+ console.log("\nOptions:");
39
+ console.log(' --dry-run Show configuration without executing');
40
+ console.log(' --strategy <type> Strategy: auto, research, development, analysis');
41
+ console.log(' --max-agents <n> Maximum number of agents (default: 5)');
42
+ console.log(' --timeout <minutes> Timeout in minutes (default: 60)');
43
+ console.log(' --vscode Use VS Code terminal integration');
44
+ console.log(' --monitor Enable real-time monitoring');
45
+ return;
46
+ }
47
+
48
+ const options = {
49
+ strategy: ctx.flags.strategy as string || 'auto',
50
+ maxAgents: ctx.flags.maxAgents as number || ctx.flags['max-agents'] as number || 5,
51
+ maxDepth: ctx.flags.maxDepth as number || ctx.flags['max-depth'] as number || 3,
52
+ research: ctx.flags.research as boolean || false,
53
+ parallel: ctx.flags.parallel as boolean || false,
54
+ memoryNamespace: ctx.flags.memoryNamespace as string || ctx.flags['memory-namespace'] as string || 'swarm',
55
+ timeout: ctx.flags.timeout as number || 60,
56
+ review: ctx.flags.review as boolean || false,
57
+ coordinator: ctx.flags.coordinator as boolean || false,
58
+ config: ctx.flags.config as string || ctx.flags.c as string,
59
+ verbose: ctx.flags.verbose as boolean || ctx.flags.v as boolean || false,
60
+ dryRun: ctx.flags.dryRun as boolean || ctx.flags['dry-run'] as boolean || ctx.flags.d as boolean || false,
61
+ useVSCode: ctx.flags.vscode as boolean || false,
62
+ };
63
+
64
+ const swarmId = generateId('swarm');
65
+
66
+ if (options.dryRun) {
67
+ warning('DRY RUN - Swarm Configuration:');
68
+ console.log(`Swarm ID: ${swarmId}`);
69
+ console.log(`Objective: ${objective}`);
70
+ console.log(`Strategy: ${options.strategy}`);
71
+ console.log(`Max Agents: ${options.maxAgents}`);
72
+ console.log(`Max Depth: ${options.maxDepth}`);
73
+ console.log(`Research: ${options.research}`);
74
+ console.log(`Parallel: ${options.parallel}`);
75
+ console.log(`Review Mode: ${options.review}`);
76
+ console.log(`Coordinator: ${options.coordinator}`);
77
+ console.log(`Memory Namespace: ${options.memoryNamespace}`);
78
+ console.log(`Timeout: ${options.timeout} minutes`);
79
+ console.log(`Use VS Code: ${options.useVSCode}`);
80
+ return;
81
+ }
82
+
83
+ success(`🐝 Initializing Claude Swarm: ${swarmId}`);
84
+ console.log(`📋 Objective: ${objective}`);
85
+
86
+ // Initialize swarm state
87
+ initializeSwarm(swarmId, objective);
88
+
89
+ // Build the orchestration prompt
90
+ const orchestrationPrompt = buildOrchestrationPrompt(objective, options);
91
+
92
+ // Check if monitoring is requested
93
+ const shouldMonitor = ctx.flags.monitor as boolean || false;
94
+
95
+ // Spawn monitoring in background if requested
96
+ if (shouldMonitor) {
97
+ info('📊 Starting swarm monitor in background...');
98
+ // Run monitor in background
99
+ monitorSwarm(swarmId).catch(err => {
100
+ error(`Monitor error: ${err.message}`);
101
+ });
102
+ }
103
+
104
+ // Check if we should use VS Code integration
105
+ if (options.useVSCode && Deno.env.get('TERM_PROGRAM') === 'vscode') {
106
+ await spawnVSCodeSwarm(swarmId, objective, orchestrationPrompt, options);
107
+ } else {
108
+ await spawnNativeSwarm(swarmId, objective, orchestrationPrompt, options);
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Spawn swarm using native terminal approach
114
+ */
115
+ async function spawnNativeSwarm(swarmId: string, objective: string, prompt: string, options: any): Promise<void> {
116
+ // Check if Claude CLI is available
117
+ try {
118
+ const checkClaude = new Deno.Command('which', { args: ['claude'] });
119
+ const checkResult = await checkClaude.output();
120
+
121
+ if (!checkResult.success) {
122
+ throw new Error('Claude CLI not found in PATH');
123
+ }
124
+ } catch (err) {
125
+ error('Claude CLI not found!');
126
+ console.log('Make sure Claude desktop app is installed and the claude command is available in your PATH');
127
+ console.log('You can test with: which claude');
128
+ return;
129
+ }
130
+
131
+ info('🎯 Spawning Master Orchestrator...');
132
+
133
+ try {
134
+ // Build Claude command arguments
135
+ const claudeArgs = [prompt];
136
+ claudeArgs.push('--allowedTools', buildOrchestratorTools(options));
137
+
138
+ if (options.config) {
139
+ claudeArgs.push('--mcp-config', options.config);
140
+ }
141
+
142
+ if (options.verbose) {
143
+ claudeArgs.push('--verbose');
144
+ }
145
+
146
+ const orchestratorEnv = {
147
+ CLAUDE_SWARM_ID: swarmId,
148
+ CLAUDE_SWARM_MODE: 'orchestrator',
149
+ CLAUDE_SWARM_OBJECTIVE: objective,
150
+ CLAUDE_SWARM_STRATEGY: options.strategy,
151
+ CLAUDE_SWARM_MAX_AGENTS: options.maxAgents.toString(),
152
+ CLAUDE_SWARM_MAX_DEPTH: options.maxDepth.toString(),
153
+ CLAUDE_SWARM_MEMORY_NS: options.memoryNamespace,
154
+ };
155
+
156
+ // Create the command
157
+ const command = new Deno.Command('claude', {
158
+ args: claudeArgs,
159
+ stdin: 'piped',
160
+ stdout: 'inherit',
161
+ stderr: 'inherit',
162
+ env: {
163
+ ...Deno.env.toObject(),
164
+ ...orchestratorEnv,
165
+ },
166
+ });
167
+
168
+ // Spawn the process
169
+ const process = command.spawn();
170
+
171
+ success('✅ Master Orchestrator spawned successfully');
172
+ info('🚀 Swarm is now active and self-orchestrating...');
173
+
174
+ // Set up timeout if specified
175
+ let timeoutId: number | undefined;
176
+ if (options.timeout > 0) {
177
+ timeoutId = setTimeout(() => {
178
+ warning(`⏰ Swarm timeout reached (${options.timeout} minutes)`);
179
+ process.kill("SIGTERM");
180
+ }, options.timeout * 60 * 1000);
181
+ }
182
+
183
+ // Wait for the orchestrator to complete
184
+ const status = await process.status;
185
+
186
+ if (timeoutId) {
187
+ clearTimeout(timeoutId);
188
+ }
189
+
190
+ if (status.success) {
191
+ success(`✅ Swarm ${swarmId} completed successfully`);
192
+ } else {
193
+ error(`Swarm ${swarmId} exited with code ${status.code}`);
194
+ }
195
+
196
+ } catch (err) {
197
+ error(`Failed to spawn orchestrator: ${(err as Error).message}`);
198
+ console.log('Make sure Claude CLI is installed and available in your PATH');
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Spawn swarm using VS Code terminal integration
204
+ */
205
+ async function spawnVSCodeSwarm(swarmId: string, objective: string, prompt: string, options: any): Promise<void> {
206
+ info('🎯 Spawning Master Orchestrator in VS Code terminal...');
207
+
208
+ try {
209
+ // Write prompt to a temporary file
210
+ const tempDir = await Deno.makeTempDir();
211
+ const promptFile = `${tempDir}/swarm-${swarmId}-prompt.txt`;
212
+ await Deno.writeTextFile(promptFile, prompt);
213
+
214
+ // Create a script that will run in the VS Code terminal
215
+ const scriptContent = `#!/bin/bash
216
+ # Claude Swarm Orchestrator Script
217
+ # Swarm ID: ${swarmId}
218
+
219
+ export CLAUDE_SWARM_ID="${swarmId}"
220
+ export CLAUDE_SWARM_MODE="orchestrator"
221
+ export CLAUDE_SWARM_OBJECTIVE="${objective}"
222
+ export CLAUDE_SWARM_STRATEGY="${options.strategy}"
223
+ export CLAUDE_SWARM_MAX_AGENTS="${options.maxAgents}"
224
+ export CLAUDE_SWARM_MAX_DEPTH="${options.maxDepth}"
225
+ export CLAUDE_SWARM_MEMORY_NS="${options.memoryNamespace}"
226
+
227
+ echo "🐝 Claude Swarm Orchestrator Starting..."
228
+ echo "📋 Swarm ID: $CLAUDE_SWARM_ID"
229
+ echo "🎯 Objective: $CLAUDE_SWARM_OBJECTIVE"
230
+ echo ""
231
+
232
+ # Run Claude with the prompt
233
+ claude "$(cat "${promptFile}")" \\
234
+ --allowedTools ${buildOrchestratorTools(options)} \\
235
+ ${options.config ? `--mcp-config ${options.config}` : ''} \\
236
+ ${options.verbose ? '--verbose' : ''}
237
+
238
+ echo ""
239
+ echo "✅ Swarm execution completed"
240
+ `;
241
+
242
+ const scriptFile = `${tempDir}/swarm-${swarmId}-run.sh`;
243
+ await Deno.writeTextFile(scriptFile, scriptContent);
244
+ await Deno.chmod(scriptFile, 0o755);
245
+
246
+ // Use AppleScript for macOS or tasks.json for other platforms
247
+ if (Deno.build.os === 'darwin') {
248
+ // macOS: Use AppleScript to create new terminal and run script
249
+ const appleScript = `
250
+ tell application "Visual Studio Code"
251
+ activate
252
+ end tell
253
+ delay 0.5
254
+ tell application "System Events"
255
+ keystroke "\`" using {control down, shift down}
256
+ end tell
257
+ delay 1
258
+ tell application "System Events"
259
+ keystroke "clear && echo '🐝 Starting Claude Swarm Orchestrator...'"
260
+ key code 36
261
+ delay 0.5
262
+ keystroke "${scriptFile}"
263
+ key code 36
264
+ end tell
265
+ `;
266
+
267
+ const osascriptCommand = new Deno.Command('osascript', {
268
+ args: ['-e', appleScript],
269
+ });
270
+
271
+ await osascriptCommand.output();
272
+
273
+ success('✅ Master Orchestrator spawned in VS Code terminal');
274
+ info('🚀 Swarm is now active in the VS Code terminal');
275
+ console.log('\nThe swarm orchestrator is running in a new VS Code terminal.');
276
+ console.log('You can monitor its progress there.');
277
+
278
+ } else {
279
+ // For other platforms, create a VS Code task
280
+ await createOrchestratorTask(swarmId, scriptFile, options);
281
+ }
282
+
283
+ // Monitor swarm execution
284
+ let checkCount = 0;
285
+ const maxChecks = options.timeout ? options.timeout * 6 : 360; // Check every 10 seconds
286
+
287
+ const checkInterval = setInterval(async () => {
288
+ checkCount++;
289
+ if (checkCount > maxChecks) {
290
+ clearInterval(checkInterval);
291
+ warning(`⏰ Swarm timeout reached (${options.timeout || 60} minutes)`);
292
+ }
293
+
294
+ // TODO: Implement proper completion detection
295
+ // For now, just check if the script file still exists
296
+ try {
297
+ await Deno.stat(scriptFile);
298
+ } catch {
299
+ // Script cleaned up, assume completion
300
+ clearInterval(checkInterval);
301
+ success(`✅ Swarm ${swarmId} execution completed`);
302
+ }
303
+ }, 10000);
304
+
305
+ // Clean up temp files after timeout
306
+ setTimeout(async () => {
307
+ clearInterval(checkInterval);
308
+ try {
309
+ await Deno.remove(tempDir, { recursive: true });
310
+ } catch {}
311
+ }, (options.timeout || 60) * 60 * 1000);
312
+
313
+ } catch (err) {
314
+ error(`Failed to spawn VS Code terminal: ${(err as Error).message}`);
315
+ console.log('Falling back to native terminal mode...');
316
+ await spawnNativeSwarm(swarmId, objective, prompt, options);
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Create VS Code task for orchestrator
322
+ */
323
+ async function createOrchestratorTask(swarmId: string, scriptFile: string, options: any): Promise<void> {
324
+ const tasksDir = '.vscode';
325
+ const tasksFile = `${tasksDir}/tasks.json`;
326
+
327
+ // Ensure .vscode directory exists
328
+ await Deno.mkdir(tasksDir, { recursive: true });
329
+
330
+ // Read existing tasks or create new
331
+ let tasks: any = {
332
+ version: "2.0.0",
333
+ tasks: []
334
+ };
335
+
336
+ try {
337
+ const existing = await Deno.readTextFile(tasksFile);
338
+ tasks = JSON.parse(existing);
339
+ } catch {}
340
+
341
+ // Add orchestrator task
342
+ const orchestratorTask = {
343
+ label: `Claude Swarm Orchestrator: ${swarmId}`,
344
+ type: "shell",
345
+ command: scriptFile,
346
+ presentation: {
347
+ echo: true,
348
+ reveal: "always",
349
+ focus: true,
350
+ panel: "new",
351
+ showReuseMessage: false,
352
+ clear: true
353
+ },
354
+ problemMatcher: [],
355
+ isBackground: false
356
+ };
357
+
358
+ tasks.tasks.push(orchestratorTask);
359
+
360
+ // Write updated tasks
361
+ await Deno.writeTextFile(tasksFile, JSON.stringify(tasks, null, 2));
362
+
363
+ success('✅ Created VS Code task for orchestrator');
364
+ console.log('\nTo run the orchestrator:');
365
+ console.log('1. Open Command Palette (Cmd+Shift+P or Ctrl+Shift+P)');
366
+ console.log('2. Type "Tasks: Run Task"');
367
+ console.log(`3. Select "Claude Swarm Orchestrator: ${swarmId}"`);
368
+ console.log('\nAlternatively, press Cmd+Shift+B (or Ctrl+Shift+B) if it\'s the default build task.');
369
+ }
370
+
371
+ function buildOrchestrationPrompt(objective: string, options: any): string {
372
+ const strategies = {
373
+ auto: 'Automatically determine the best approach',
374
+ research: 'Focus on research and information gathering',
375
+ development: 'Focus on implementation and coding',
376
+ analysis: 'Focus on analysis and insights'
377
+ };
378
+
379
+ return `
380
+ # Claude Swarm Orchestration Task
381
+
382
+ You are the Master Orchestrator for a Claude agent swarm. Your objective is to coordinate multiple specialized agents to achieve the following goal:
383
+
384
+ **OBJECTIVE**: ${objective}
385
+
386
+ ## Orchestration Parameters:
387
+ - Strategy: ${strategies[options.strategy as keyof typeof strategies] || strategies.auto}
388
+ - Maximum Agents: ${options.maxAgents}
389
+ - Maximum Delegation Depth: ${options.maxDepth}
390
+ - Parallel Execution: ${options.parallel ? 'Enabled' : 'Disabled'}
391
+ - Peer Review: ${options.review ? 'Enabled' : 'Disabled'}
392
+ - Research Capabilities: ${options.research ? 'Enabled' : 'Disabled'}
393
+
394
+ ## Your Responsibilities:
395
+
396
+ 1. **Task Decomposition**: Break down the objective into subtasks
397
+ 2. **Agent Spawning**: Create specialized agents for each subtask
398
+ 3. **Resource Allocation**: Assign appropriate tools and permissions
399
+ 4. **Coordination**: Manage dependencies and communication
400
+ 5. **Quality Control**: ${options.review ? 'Implement peer review processes' : 'Monitor task quality'}
401
+ 6. **Progress Tracking**: Monitor and report on swarm progress
402
+
403
+ ## Available Agent Types:
404
+ - **Researcher**: Information gathering, web research, analysis
405
+ - **Developer**: Code implementation, testing, debugging
406
+ - **Analyst**: Data analysis, pattern recognition, insights
407
+ - **Reviewer**: Code review, quality assurance, validation
408
+ - **Coordinator**: Sub-task coordination, dependency management
409
+
410
+ ## Swarm Execution Process:
411
+
412
+ 1. Analyze the objective and create a detailed execution plan
413
+ 2. Identify required agent types and their responsibilities
414
+ 3. Spawn agents with appropriate configurations using the dispatch_agent tool:
415
+ \`\`\`javascript
416
+ // Example: Spawn a researcher agent
417
+ dispatch_agent({
418
+ type: "researcher",
419
+ task: "Research best practices for REST API design",
420
+ name: "API Research Agent"
421
+ });
422
+ \`\`\`
423
+ 4. Monitor agent progress through shared memory:
424
+ \`\`\`javascript
425
+ // Store progress updates
426
+ memory_store("agent_status", {
427
+ agentId: "researcher-001",
428
+ progress: 75,
429
+ findings: "Discovered 5 key patterns..."
430
+ });
431
+ \`\`\`
432
+ 5. Coordinate between agents using memory namespace
433
+ 6. ${options.review ? 'Implement peer review cycles between agents' : 'Validate outputs'}
434
+ 7. Synthesize results and report completion
435
+
436
+ ## Memory Coordination:
437
+ All agents share the memory namespace: "${options.memoryNamespace}"
438
+ Use this for:
439
+ - Sharing discoveries and insights
440
+ - Avoiding duplicate work
441
+ - Building on each other's findings
442
+ - Maintaining context across the swarm
443
+
444
+ ## Special Instructions:
445
+ ${options.coordinator ? '- Spawn a dedicated coordinator agent for complex subtasks' : ''}
446
+ ${options.research ? '- All agents should have research capabilities enabled' : ''}
447
+ ${options.parallel ? '- Maximize parallel execution where dependencies allow' : ''}
448
+ ${options.maxDepth > 1 ? `- Agents can delegate to sub-agents up to depth ${options.maxDepth}` : ''}
449
+
450
+ ## Output Format:
451
+ Provide regular status updates in this format:
452
+ \`\`\`
453
+ [SWARM STATUS]
454
+ - Active Agents: X/Y
455
+ - Tasks Completed: X/Y
456
+ - Current Phase: <phase>
457
+ - Next Actions: <list>
458
+ \`\`\`
459
+
460
+ Begin by analyzing the objective and presenting your execution plan.
461
+ `;
462
+ }
463
+
464
+ function buildOrchestratorTools(options: any): string {
465
+ const tools = [
466
+ 'View',
467
+ 'Edit',
468
+ 'Replace',
469
+ 'GlobTool',
470
+ 'GrepTool',
471
+ 'LS',
472
+ 'Bash',
473
+ 'dispatch_agent',
474
+ 'memory_store',
475
+ 'memory_retrieve',
476
+ 'swarm_status'
477
+ ];
478
+
479
+ if (options.research) {
480
+ tools.push('WebFetchTool');
481
+ }
482
+
483
+ if (options.parallel) {
484
+ tools.push('BatchTool');
485
+ }
486
+
487
+ return tools.join(',');
488
+ }
489
+
490
+ function buildClaudeCommand(prompt: string, options: any): string {
491
+ // Build the claude command with all necessary arguments
492
+ const parts = ['claude'];
493
+
494
+ // Add the prompt as a quoted argument
495
+ parts.push(`"${prompt.replace(/"/g, '\\"')}"`);
496
+
497
+ // Add allowed tools
498
+ const tools = buildOrchestratorTools(options);
499
+ parts.push('--allowedTools', tools);
500
+
501
+ // Add MCP config if specified
502
+ if (options.config) {
503
+ parts.push('--mcp-config', options.config);
504
+ }
505
+
506
+ // Add verbose flag if requested
507
+ if (options.verbose) {
508
+ parts.push('--verbose');
509
+ }
510
+
511
+ // Join all parts into a single command
512
+ return parts.join(' ');
513
+ }
@@ -93,14 +93,14 @@ async function main() {
93
93
 
94
94
  case 'start':
95
95
  printSuccess('Starting Claude-Flow orchestration system...');
96
- printWarning('Full orchestrator implementation coming soon!');
97
- console.log('🚀 System would start with the following components:');
98
- console.log(' - Event Bus');
99
- console.log(' - Orchestrator Engine');
100
- console.log(' - Memory Manager');
101
- console.log(' - Terminal Pool');
102
- console.log(' - MCP Server');
103
- console.log(' - Coordination Manager');
96
+ console.log('🚀 System starting with the following components:');
97
+ console.log(' Event Bus');
98
+ console.log(' Orchestrator Engine');
99
+ console.log(' Memory Manager');
100
+ console.log(' Terminal Pool');
101
+ console.log(' MCP Server');
102
+ console.log(' Coordination Manager');
103
+ console.log('\n💡 Run "claude-flow start" from the main CLI for full functionality');
104
104
  break;
105
105
 
106
106
  case 'agent':
@@ -0,0 +1,166 @@
1
+ /**
2
+ * MCP tools for swarm orchestration
3
+ */
4
+
5
+ import { Tool } from '@modelcontextprotocol/sdk/types.js';
6
+ import { spawnSwarmAgent, getSwarmState } from '../cli/commands/swarm-spawn.ts';
7
+
8
+ /**
9
+ * Dispatch agent tool for swarm orchestration
10
+ */
11
+ export const dispatchAgentTool: Tool = {
12
+ name: 'dispatch_agent',
13
+ description: 'Spawn a new agent in the swarm to handle a specific task',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {
17
+ type: {
18
+ type: 'string',
19
+ enum: ['researcher', 'developer', 'analyst', 'reviewer', 'coordinator'],
20
+ description: 'The type of agent to spawn',
21
+ },
22
+ task: {
23
+ type: 'string',
24
+ description: 'The specific task for the agent to complete',
25
+ },
26
+ name: {
27
+ type: 'string',
28
+ description: 'Optional name for the agent',
29
+ },
30
+ },
31
+ required: ['type', 'task'],
32
+ },
33
+ };
34
+
35
+ /**
36
+ * Handle dispatch agent tool execution
37
+ */
38
+ export async function handleDispatchAgent(args: any): Promise<any> {
39
+ const { type, task, name } = args;
40
+
41
+ // Get swarm ID from environment
42
+ const swarmId = Deno.env.get('CLAUDE_SWARM_ID');
43
+ if (!swarmId) {
44
+ throw new Error('Not running in swarm context');
45
+ }
46
+
47
+ // Get parent agent ID if available
48
+ const parentId = Deno.env.get('CLAUDE_SWARM_AGENT_ID');
49
+
50
+ try {
51
+ // Spawn the agent
52
+ const agent = await spawnSwarmAgent(swarmId, type, task, parentId);
53
+
54
+ return {
55
+ success: true,
56
+ agentId: agent.id,
57
+ agentName: agent.name,
58
+ terminalId: agent.terminalId,
59
+ message: `Successfully spawned ${agent.name} to work on: ${task}`,
60
+ };
61
+ } catch (error) {
62
+ return {
63
+ success: false,
64
+ error: error instanceof Error ? error.message : 'Unknown error',
65
+ };
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Memory store tool for swarm coordination
71
+ */
72
+ export const memoryStoreTool: Tool = {
73
+ name: 'memory_store',
74
+ description: 'Store data in the shared swarm memory for coordination',
75
+ inputSchema: {
76
+ type: 'object',
77
+ properties: {
78
+ key: {
79
+ type: 'string',
80
+ description: 'The key to store data under',
81
+ },
82
+ value: {
83
+ type: 'object',
84
+ description: 'The data to store (JSON object)',
85
+ },
86
+ },
87
+ required: ['key', 'value'],
88
+ },
89
+ };
90
+
91
+ /**
92
+ * Memory retrieve tool for swarm coordination
93
+ */
94
+ export const memoryRetrieveTool: Tool = {
95
+ name: 'memory_retrieve',
96
+ description: 'Retrieve data from the shared swarm memory',
97
+ inputSchema: {
98
+ type: 'object',
99
+ properties: {
100
+ key: {
101
+ type: 'string',
102
+ description: 'The key to retrieve data from',
103
+ },
104
+ },
105
+ required: ['key'],
106
+ },
107
+ };
108
+
109
+ /**
110
+ * Swarm status tool
111
+ */
112
+ export const swarmStatusTool: Tool = {
113
+ name: 'swarm_status',
114
+ description: 'Get the current status of the swarm and all agents',
115
+ inputSchema: {
116
+ type: 'object',
117
+ properties: {},
118
+ },
119
+ };
120
+
121
+ /**
122
+ * Handle swarm status tool execution
123
+ */
124
+ export async function handleSwarmStatus(args: any): Promise<any> {
125
+ const swarmId = Deno.env.get('CLAUDE_SWARM_ID');
126
+ if (!swarmId) {
127
+ throw new Error('Not running in swarm context');
128
+ }
129
+
130
+ const state = getSwarmState(swarmId);
131
+ if (!state) {
132
+ throw new Error('Swarm state not found');
133
+ }
134
+
135
+ const agents = Array.from(state.agents.values()).map(agent => ({
136
+ id: agent.id,
137
+ type: agent.type,
138
+ name: agent.name,
139
+ task: agent.task,
140
+ status: agent.status,
141
+ parentId: agent.parentId,
142
+ }));
143
+
144
+ const runtime = Math.floor((Date.now() - state.startTime) / 1000);
145
+
146
+ return {
147
+ swarmId: state.swarmId,
148
+ objective: state.objective,
149
+ runtime: `${runtime}s`,
150
+ totalAgents: agents.length,
151
+ activeAgents: agents.filter(a => a.status === 'active').length,
152
+ completedAgents: agents.filter(a => a.status === 'completed').length,
153
+ failedAgents: agents.filter(a => a.status === 'failed').length,
154
+ agents,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Export all swarm tools
160
+ */
161
+ export const swarmTools = [
162
+ dispatchAgentTool,
163
+ memoryStoreTool,
164
+ memoryRetrieveTool,
165
+ swarmStatusTool,
166
+ ];