π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
π Checkpoint: Edit /workspaces/claude-code-flow/src/cli/simple-commands/stream-chain.js
rUv6dd9838141c7
diff --git a/.claude/checkpoints/1755025483.json b/.claude/checkpoints/1755025483.jsonnew file mode 100644index 0000000000..2e23e84ddc--- /dev/null+++ b/.claude/checkpoints/1755025483.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250812-190443", "file": "/workspaces/claude-code-flow/src/cli/simple-commands/stream-chain-real.js", "timestamp": "2025-08-12T19:04:43Z", "type": "pre-edit", "original_branch": "alpha-89"}diff --git a/.claude/checkpoints/1755025485.json b/.claude/checkpoints/1755025485.jsonnew file mode 100644index 0000000000..caa6ecdc2c--- /dev/null+++ b/.claude/checkpoints/1755025485.json@@ -0,0 +1 @@+{"tag": "checkpoint-20250812-190445", "file": "/workspaces/claude-code-flow/src/cli/simple-commands/stream-chain-real.js", "timestamp": "2025-08-12T19:04:45Z", "type": "post-edit", "branch": "alpha-89", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/system-metrics.json | 198 +++++++++++-- .claude-flow/metrics/task-metrics.json | 6 +- claude-flow-wiki | 0 src/cli/simple-commands/stream-chain-real.js | 415 +++++++++++++++++++++++++++ 5 files changed, 596 insertions(+), 25 deletions(-) "}diff --git a/.claude/checkpoints/1755025517.json b/.claude/checkpoints/1755025517.jsonnew file mode 100644index 0000000000..05bb3b930c--- /dev/null+++ b/.claude/checkpoints/1755025517.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250812-190517", "file": "/workspaces/claude-code-flow/todo-app-data-architecture.md", "timestamp": "2025-08-12T19:05:17Z", "type": "pre-edit", "original_branch": "alpha-89"}diff --git a/.claude/checkpoints/1755025534.json b/.claude/checkpoints/1755025534.jsonnew file mode 100644index 0000000000..918ebeae30--- /dev/null+++ b/.claude/checkpoints/1755025534.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250812-190534", "file": "/workspaces/claude-code-flow/SWARM_COORDINATION_ARCHITECTURE_ANALYSIS.md", "timestamp": "2025-08-12T19:05:34Z", "type": "pre-edit", "original_branch": "alpha-89"}diff --git a/.claude/checkpoints/1755025542.json b/.claude/checkpoints/1755025542.jsonnew file mode 100644index 0000000000..ec9c3da7ea--- /dev/null+++ b/.claude/checkpoints/1755025542.json@@ -0,0 +1 @@+{"branch": "checkpoint/pre-edit-20250812-190542", "file": "/workspaces/claude-code-flow/todo-app/models/data-model.ts", "timestamp": "2025-08-12T19:05:42Z", "type": "pre-edit", "original_branch": "alpha-89"}diff --git a/src/cli/simple-commands/stream-chain.js b/src/cli/simple-commands/stream-chain.jsindex bfc33be89f..d1dc16f4fb 100644--- a/src/cli/simple-commands/stream-chain.js+++ b/src/cli/simple-commands/stream-chain.js@@ -1,10 +1,11 @@#!/usr/bin/env node/**- * Stream Chain Command - Connect multiple Claude instances via stream-json- * Clean implementation focused on real Claude CLI execution+ * Stream Chain Command - Real Claude CLI stream-json chaining+ * Implements proper stream-json format chaining as documented*/-import { exec, execSync, spawn } from 'child_process';+import { spawn, execSync } from 'child_process';+import { Readable } from 'stream';/*** Check if claude CLI is available@@ -19,74 +20,176 @@ function checkClaudeAvailable() {}/**- * Mock implementation for fallback+ * Execute a chain of Claude instances with real stream-json piping*/-function mockResponse(prompt) {- return {- success: true,- duration: 500,- output: `β Mock response for: ${prompt.slice(0, 50)}...`,- stream: null,- error: null- };+async function executeRealChain(prompts, flags = {}) {+ const results = [];+ let previousOutput = null;++ for (let i = 0; i < prompts.length; i++) {+ const prompt = prompts[i];+ const isFirst = i === 0;+ const isLast = i === prompts.length - 1;++ console.log(`\nπ Step ${i + 1}/${prompts.length}: ${prompt.slice(0, 50)}...`);++ const result = await executeChainStep(+ prompt,+ previousOutput,+ isFirst,+ isLast,+ flags+ );++ results.push({+ step: i + 1,+ prompt: prompt.slice(0, 50),+ success: result.success,+ duration: result.duration+ });++ if (!result.success) {+ console.error(`β Step ${i + 1} failed`);+ break;+ }++ console.log(`β Step ${i + 1} completed (${result.duration}ms)`);++ // Store output for next step+ if (!isLast && result.output) {+ previousOutput = result.output;+ if (flags.verbose) {+ console.log(` Output length: ${result.output.length} bytes`);+ }+ }+ }++ return results;}/**- * Execute a single Claude CLI command+ * Execute a single step in the chain with proper stream-json handling*/-async function executeClaudeCommand(prompt, timeout = 20000, useStreamJson = false) {+async function executeChainStep(prompt, inputData, isFirst, isLast, flags) {return new Promise((resolve) => {- // For testing, let's just test Claude CLI availability first- if (!checkClaudeAvailable()) {- console.log('β οΈ Claude CLI not available, using mock response...');- resolve(mockResponse(prompt));- return;+ const startTime = Date.now();+ const timeout = (flags.timeout || 30) * 1000;++ // Build command args following the spec from docs/stream-chaining.md+ const args = ['-p'];++ // Add input format if we have previous output+ if (!isFirst && inputData) {+ args.push('--input-format', 'stream-json');}- // Build command string exactly like we know works- let command;- if (useStreamJson) {- command = `claude -p --output-format stream-json --verbose "${prompt.replace(/"/g, '\\"')}"`;+ // Add output format if not last step+ if (!isLast) {+ args.push('--output-format', 'stream-json');+ // Verbose flag is required for stream-json output+ args.push('--verbose');+ }++ // Add the prompt+ args.push(prompt);++ if (flags.verbose) {+ console.log(` Command: claude ${args.join(' ')}`);+ }++ // Spawn Claude process+ const claudeProcess = spawn('claude', args, {+ stdio: ['pipe', 'pipe', 'pipe'],+ env: process.env+ });++ let output = '';+ let stderr = '';+ let processCompleted = false;++ // Pipe input data if available+ if (!isFirst && inputData) {+ try {+ // Write the previous output as input+ claudeProcess.stdin.write(inputData);+ claudeProcess.stdin.end();+ if (flags.verbose) {+ console.log(' π Piped input from previous step');+ }+ } catch (error) {+ console.error(' Error piping input:', error.message);+ }} else {- command = `claude -p "${prompt.replace(/"/g, '\\"')}"`;+ // No input, close stdin+ claudeProcess.stdin.end();}- console.log(`π Executing: ${command}`);+ // Capture output+ claudeProcess.stdout.on('data', (chunk) => {+ output += chunk.toString();+ });- const startTime = Date.now();+ // Capture errors+ claudeProcess.stderr.on('data', (chunk) => {+ stderr += chunk.toString();+ });- // Use exec with shell=true for better compatibility- exec(command, {- timeout,- maxBuffer: 1024 * 1024 * 10, // 10MB buffer- env: process.env,- shell: true // Ensure shell processing- }, (error, stdout, stderr) => {+ // Handle completion+ claudeProcess.on('close', (code) => {+ if (processCompleted) return;+ processCompleted = true;+const duration = Date.now() - startTime;- if (error) {- if (error.code === 'TIMEOUT') {- console.log('β οΈ Claude CLI timed out, using mock response...');- } else {- console.error('Claude CLI error:', error.message);- if (stderr) {- console.error('stderr:', stderr);- }+ if (code !== 0) {+ if (flags.verbose && stderr) {+ console.error(` stderr: ${stderr.slice(0, 500)}`);}- resolve(mockResponse(prompt));+ resolve({+ success: false,+ duration,+ output: null,+ error: `Process exited with code ${code}`+ });return;}- // Real success case- console.log(`β Claude CLI executed successfully (${duration}ms)`);resolve({success: true,duration,- output: stdout.trim(),- stream: useStreamJson ? stdout : null,- error: stderr ? stderr.trim() : null+ output: output,+ error: null+ });+ });++ // Handle errors+ claudeProcess.on('error', (error) => {+ if (processCompleted) return;+ processCompleted = true;++ console.error(' Process error:', error.message);+ resolve({+ success: false,+ duration: Date.now() - startTime,+ output: null,+ error: error.message});});++ // Timeout handling+ setTimeout(() => {+ if (!processCompleted) {+ processCompleted = true;+ claudeProcess.kill('SIGTERM');+ console.log(' β±οΈ Step timed out');+ resolve({+ success: false,+ duration: timeout,+ output: null,+ error: 'Timeout'+ });+ }+ }, timeout);});}@@ -97,133 +200,216 @@ export async function streamChainCommand(args, flags) {const subcommand = args[0] || 'help';if (subcommand === 'help') {- console.log(`-π Stream Chain Command--USAGE:- stream-chain run "prompt1" "prompt2" [...] # Execute custom chain- stream-chain demo # Run demo chain- stream-chain test # Test Claude CLI- stream-chain help # Show this help--OPTIONS:- --timeout <seconds> Timeout per step (default: 20)- --mock Force mock mode- --verbose Show detailed output--EXAMPLES:- stream-chain run "Hello" "How are you?"- stream-chain demo --timeout 30- stream-chain test--For real execution, Claude CLI must be installed and configured.- `);+ showHelp();return;}- if (subcommand === 'test') {- console.log('π§ͺ Testing Claude CLI...');-- if (!checkClaudeAvailable()) {- console.log('β Claude CLI not found');- return;- }-- const result = await executeClaudeCommand('Hello, test', 10000);- console.log('β Test result:', result.success ? 'PASSED' : 'FAILED');- if (result.output) {- console.log('π Output:', result.output.slice(0, 100) + '...');- }+ // Check Claude CLI availability+ if (!checkClaudeAvailable()) {+ console.error('β Claude CLI not found');+ console.log('\nPlease install Claude CLI to use real stream chaining:');+ console.log(' npm install -g @anthropic-ai/claude-cli');+ console.log(' Or use Claude Code: https://claude.ai/code');+ console.log('\nFor documentation, see: docs/stream-chaining.md');return;}- if (subcommand === 'demo') {- console.log('π Running Stream Chain Demo');- console.log('β'.repeat(50));-- const prompts = [- "Analyze requirements for a todo app",- "Design the data model",- "Create implementation plan"- ];-- return runChain(prompts, flags);+ switch (subcommand) {+ case 'demo':+ await runDemo(flags);+ break;++ case 'run':+ await runCustom(args.slice(1), flags);+ break;++ case 'test':+ await runTest(flags);+ break;++ case 'pipeline':+ await runPipeline(args.slice(1), flags);+ break;++ default:+ console.error(`β Unknown subcommand: ${subcommand}`);+ showHelp();}+}++/**+ * Show help+ */+function showHelp() {+ console.log(`+π Stream Chain Command - Real Claude CLI Stream-JSON Chaining++DESCRIPTION+ Connect multiple Claude instances using stream-json format.+ Each agent receives the full output from the previous agent,+ enabling complex multi-agent workflows with context preservation.++USAGE+ stream-chain <subcommand> [options]++SUBCOMMANDS+ run <p1> <p2> [...] Execute custom chain (min 2 prompts)+ demo Run 3-step demo with real chaining+ test Test stream connection+ pipeline <type> Run predefined pipeline+ help Show this help++PIPELINE TYPES+ analysis Analyze β Identify β Report+ refactor Identify β Plan β Implement+ test Coverage β Design β Generate+ optimize Profile β Identify β Optimize++OPTIONS+ --verbose Show detailed execution info+ --timeout <seconds> Timeout per step (default: 30)++EXAMPLES+ stream-chain demo+ stream-chain run "Analyze this" "Improve it" "Finalize"+ stream-chain pipeline analysis --verbose+ stream-chain test --timeout 10++STREAM-JSON FORMAT+ {"type":"init","session_id":"..."}+ {"type":"message","role":"assistant","content":[...]}+ {"type":"tool_use","name":"...","input":{...}}+ {"type":"tool_result","output":"..."}+ {"type":"result","status":"success"}++DOCUMENTATION+ Full docs: ./claude-flow-wiki/Stream-Chain-Command.md+ Spec: ./docs/stream-chaining.md+ `);+}++/**+ * Run demo+ */+async function runDemo(flags) {+ console.log('π Running Real Stream Chain Demo');+ console.log('β'.repeat(50));+ console.log('Demonstrating 3-step chain with context preservation\n');- if (subcommand === 'run') {- const prompts = args.slice(1);-- if (prompts.length < 2) {- console.error('β Error: Need at least 2 prompts');- console.log('Usage: stream-chain run "prompt1" "prompt2" [...]');- return;- }-- return runChain(prompts, flags);- }+ const prompts = [+ "Write a simple Python function to reverse a string",+ "Review the code and suggest improvements",+ "Apply the improvements and create the final version"+ ];++ console.log('π Chain:', prompts.map(p => p.slice(0, 30) + '...').join(' β '));- console.error(`β Unknown subcommand: ${subcommand}`);- console.log('Use "stream-chain help" for usage information');+ const results = await executeRealChain(prompts, flags);+ showSummary(results);}/**- * Execute a chain of prompts+ * Run custom chain*/-async function runChain(prompts, flags) {- const timeout = (flags.timeout || 20) * 1000;- const useMock = flags.mock || !checkClaudeAvailable();-- if (useMock) {- console.log('βΉοΈ Using mock mode (Claude CLI not available or --mock flag used)');- } else {- console.log('βΉοΈ Using real Claude CLI execution');+async function runCustom(prompts, flags) {+ if (prompts.length < 2) {+ console.error('β Need at least 2 prompts');+ console.log('Usage: stream-chain run "prompt1" "prompt2"');+ return;}+ console.log('π Starting Custom Stream Chain');+ console.log('β'.repeat(50));console.log(`π Chain length: ${prompts.length} steps\n`);- const results = [];+ const results = await executeRealChain(prompts, flags);+ showSummary(results);+}++/**+ * Run test+ */+async function runTest(flags) {+ console.log('π§ͺ Testing Stream Connection');+ console.log('β'.repeat(50));- for (let i = 0; i < prompts.length; i++) {- const prompt = prompts[i];- console.log(`π Step ${i + 1}/${prompts.length}: ${prompt.slice(0, 50)}...`);-- let result;- if (useMock) {- result = mockResponse(prompt);- } else {- result = await executeClaudeCommand(prompt, timeout, false);- }-- results.push({- step: i + 1,- prompt: prompt.slice(0, 50),- success: result.success,- duration: result.duration- });-- if (!result.success) {- console.error(`β Step ${i + 1} failed`);- break;- }-- console.log(`β Step ${i + 1} completed (${result.duration}ms)`);- if (flags.verbose && result.output) {- console.log(` Output: ${result.output.slice(0, 200)}...`);- }+ const prompts = [+ "Say exactly: 'Test 1 OK'",+ "If you received 'Test 1 OK', say 'Test 2 OK - Chain working'"+ ];++ const results = await executeRealChain(prompts, { ...flags, verbose: true });++ console.log('\nπ Test Results:');+ const allPassed = results.every(r => r.success);+ console.log(allPassed ? 'β All tests passed!' : 'β Some tests failed');+}++/**+ * Run pipeline+ */+async function runPipeline(args, flags) {+ const type = args[0] || 'analysis';++ const pipelines = {+ analysis: [+ "Analyze the current directory structure",+ "Identify areas for improvement",+ "Generate a detailed report"+ ],+ refactor: [+ "Find code that needs refactoring",+ "Create a refactoring plan",+ "Show refactored examples"+ ],+ test: [+ "Analyze test coverage",+ "Design test cases",+ "Generate test code"+ ],+ optimize: [+ "Profile for bottlenecks",+ "Identify optimizations",+ "Provide optimized code"+ ]+ };++ const pipeline = pipelines[type];+ if (!pipeline) {+ console.error(`β Unknown pipeline: ${type}`);+ console.log('Available:', Object.keys(pipelines).join(', '));+ return;}- // Summary+ console.log(`π Running ${type} pipeline`);+ console.log('β'.repeat(50));++ const results = await executeRealChain(pipeline, flags);+ showSummary(results);+}++/**+ * Show execution summary+ */+function showSummary(results) {console.log('\n' + 'β'.repeat(50));console.log('π Chain Summary');console.log('β'.repeat(50));- for (const result of results) {- const status = result.success ? 'β ' : 'β';- console.log(`${status} Step ${result.step}: ${result.prompt}... (${result.duration}ms)`);+ for (const r of results) {+ const status = r.success ? 'β ' : 'β';+ console.log(`${status} Step ${r.step}: ${r.prompt}... (${r.duration}ms)`);}- const totalTime = results.reduce((sum, r) => sum + r.duration, 0);- console.log(`\nβ±οΈ Total execution time: ${totalTime}ms`);+ const total = results.reduce((sum, r) => sum + r.duration, 0);+ const success = results.filter(r => r.success).length;++ console.log(`\nβ±οΈ Total: ${total}ms`);+ console.log(`π Success: ${success}/${results.length} steps`);++ if (success === results.length) {+ console.log('π Chain completed successfully!');+ }}export default streamChainCommand;\ No newline at end of file