Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add live output streaming for Claude CLI agents
Adam Eivy00a19a0bca86
diff --git a/.changelog/v0.11.x.md b/.changelog/v0.11.x.mdindex c4b27ccc9a..9703e78324 100644--- a/.changelog/v0.11.x.md+++ b/.changelog/v0.11.x.md@@ -69,3 +69,15 @@ This release focuses on security improvements, bug fixes for the AI runner syste- `server/services/brainStorage.js` - Added `classifying` to inbox log counts- `client/src/components/brain/tabs/InboxTab.jsx` - Socket.IO listener for classification results, classifying section UI- `client/src/components/brain/constants.js` - Added `classifying` status color++### Autofixer App Replaced with PortOS Default+- Replaced the standalone Autofixer app with PortOS default app in sample data to avoid confusion++## 🔧 Improvements++### Live Output Streaming for Claude CLI Agents+- **Real-time Feedback**: Claude CLI agents now stream output in real-time as they work, matching the live output experience previously only available with Codex+- **Stream-JSON Parsing**: Uses Claude CLI's `--output-format stream-json --verbose --include-partial-messages` flags to receive incremental text deltas as they're generated+- **Tool Use Visibility**: Shows tool invocations (e.g., "🔧 Using Edit...") in the live output so users can see what the agent is doing+- **Both Spawn Modes**: Works in both direct spawn mode and via the standalone CoS Runner (PM2 process)+- **Clean Output Files**: The final output file contains the clean result text, while the raw JSON stream is preserved for error analysisdiff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex 79c499cd84..fd7345078e 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -54,6 +54,87 @@ function isAllowedCommand(command) {return ALLOWED_COMMANDS.has(baseName);}+/**+ * Create a Claude stream-json parser that extracts human-readable text from JSON stream events.+ * Returns a stateful parser with a `processChunk(data)` method that returns extracted text lines.+ */+function createStreamJsonParser() {+ let lineBuffer = '';+ let finalResult = '';+ let textBuffer = '';++ const processChunk = (rawData) => {+ const lines = [];+ lineBuffer += rawData;++ const parts = lineBuffer.split('\n');+ lineBuffer = parts.pop() || '';++ for (const part of parts) {+ const trimmed = part.trim();+ if (!trimmed || !trimmed.startsWith('{')) continue;++ let parsed;+ parsed = JSON.parse(trimmed);+ if (!parsed) continue;++ if (parsed.type === 'stream_event') {+ const event = parsed.event;+ if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta') {+ const text = event.delta.text;+ textBuffer += text;+ const textLines = textBuffer.split('\n');+ textBuffer = textLines.pop() || '';+ for (const tl of textLines) {+ lines.push(tl);+ }+ }+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {+ const toolName = event.content_block.name || 'unknown';+ lines.push(`🔧 Using ${toolName}...`);+ }+ }++ if (parsed.type === 'assistant') {+ const content = parsed.message?.content;+ if (Array.isArray(content)) {+ for (const block of content) {+ if (block.type === 'tool_result' && typeof block.content === 'string') {+ const firstLine = block.content.split('\n')[0]?.substring(0, 200);+ if (firstLine) {+ lines.push(` ↳ ${firstLine}`);+ }+ }+ }+ }+ }++ if (parsed.type === 'result') {+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ finalResult = parsed.result || '';+ }+ }++ return lines;+ };++ const flush = () => {+ const lines = [];+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ return lines;+ };++ const getFinalResult = () => finalResult;++ return { processChunk, flush, getFinalResult };+}+// Active agent processes (in memory)const activeAgents = new Map();@@ -270,7 +351,10 @@ app.post('/spawn', async (req, res) => {command = claudePath;spawnArgs = ['--dangerously-skip-permissions',- '--print'+ '--print',+ '--output-format', 'stream-json',+ '--verbose',+ '--include-partial-messages'];if (model) {spawnArgs.push('--model', model);@@ -290,13 +374,19 @@ app.post('/spawn', async (req, res) => {env: { ...process.env, ...envVars }});+ // Detect if stream-json format is active (Claude CLI with streaming)+ const isStreamJson = spawnArgs.includes('stream-json');+ const streamParser = isStreamJson ? createStreamJsonParser() : null;+// Store in memoryactiveAgents.set(agentId, {process: claudeProcess,taskId,pid: claudeProcess.pid,startedAt: Date.now(),- outputBuffer: ''+ outputBuffer: '',+ rawStreamBuffer: '',+ streamParser});// Send prompt via stdin@@ -307,10 +397,22 @@ app.post('/spawn', async (req, res) => {claudeProcess.stdout.on('data', (data) => {const text = data.toString();const agent = activeAgents.get(agentId);- if (agent) {- agent.outputBuffer += text;++ if (agent?.streamParser) {+ // Parse stream-json and emit extracted text lines+ agent.rawStreamBuffer += text;+ const lines = agent.streamParser.processChunk(text);+ for (const line of lines) {+ agent.outputBuffer += line + '\n';+ emitToServer('agent:output', { agentId, text: line + '\n' });+ }+ } else {+ // Non-stream providers: emit raw stdout as before+ if (agent) {+ agent.outputBuffer += text;+ }+ emitToServer('agent:output', { agentId, text });}- emitToServer('agent:output', { agentId, text });});// Handle stderr@@ -334,6 +436,21 @@ app.post('/spawn', async (req, res) => {claudeProcess.on('close', async (code) => {const agent = activeAgents.get(agentId);const duration = Date.now() - (agent?.startedAt || Date.now());++ // Flush remaining stream parser data+ if (agent?.streamParser) {+ const remaining = agent.streamParser.flush();+ for (const line of remaining) {+ agent.outputBuffer += line + '\n';+ emitToServer('agent:output', { agentId, text: line + '\n' });+ }+ // Use the parsed final result for the output file if available+ const finalResult = agent.streamParser.getFinalResult();+ if (finalResult) {+ agent.outputBuffer = finalResult;+ }+ }+const output = agent?.outputBuffer || '';console.log(`${code === 0 ? '✅' : '❌'} Agent ${agentId} exited with code ${code}`);diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 0e0d22ad9b..5ad97cf77a 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -1463,8 +1463,11 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providawait updateAgent(agentId, { pid: claudeProcess.pid });let outputBuffer = '';+ let rawStreamBuffer = ''; // Raw stdout for stream-json (used for error analysis)let hasStartedWorking = false;const outputFile = join(agentDir, 'output.txt');+ const isStreamJson = cliConfig.streamFormat === 'stream-json';+ const streamParser = isStreamJson ? createStreamJsonParser() : null;// If no output after 3 seconds, transition from initializing to working to show progressconst initializationTimeout = setTimeout(async () => {@@ -1477,7 +1480,6 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providclaudeProcess.stdout.on('data', async (data) => {const text = data.toString();- outputBuffer += text;if (!hasStartedWorking) {hasStartedWorking = true;@@ -1485,8 +1487,21 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providemitLog('info', `Agent ${agentId} working...`, { agentId, phase: 'working' });}- await writeFile(outputFile, outputBuffer).catch(() => {});- await appendAgentOutput(agentId, text);+ if (streamParser) {+ // Parse stream-json and emit extracted text lines+ rawStreamBuffer += text;+ const lines = streamParser.processChunk(text);+ for (const line of lines) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);+ }+ await writeFile(outputFile, outputBuffer).catch(() => {});+ } else {+ // Non-stream providers: emit raw stdout as before+ outputBuffer += text;+ await writeFile(outputFile, outputBuffer).catch(() => {});+ await appendAgentOutput(agentId, text);+ }});claudeProcess.stderr.on('data', async (data) => {@@ -1524,6 +1539,20 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providconst agentData = activeAgents.get(agentId);const duration = Date.now() - (agentData?.startedAt || Date.now());+ // Flush remaining stream parser data+ if (streamParser) {+ const remaining = streamParser.flush();+ for (const line of remaining) {+ outputBuffer += line + '\n';+ await appendAgentOutput(agentId, line);+ }+ // Use the parsed final result for the output file if available+ const finalResult = streamParser.getFinalResult();+ if (finalResult) {+ outputBuffer = finalResult;+ }+ }+// Release execution laneif (agentData?.laneName) {release(agentId);@@ -1541,7 +1570,9 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providawait writeFile(outputFile, outputBuffer).catch(() => {});- const errorAnalysis = success ? null : analyzeAgentFailure(outputBuffer, task, model);+ // Use raw stream buffer for error analysis (contains full JSON with error details)+ const analysisBuffer = rawStreamBuffer || outputBuffer;+ const errorAnalysis = success ? null : analyzeAgentFailure(analysisBuffer, task, model);await completeAgent(agentId, {success,@@ -1606,6 +1637,102 @@ async function spawnDirectly(agentId, task, prompt, workspacePath, model, providreturn agentId;}+/**+ * Create a Claude stream-json parser that extracts human-readable text from JSON stream events.+ * Returns a stateful parser with a `processChunk(data)` method that returns extracted text lines.+ * The parser handles:+ * - content_block_delta: incremental text tokens as they stream+ * - tool_use events: shows tool calls for visibility (e.g. "🔧 Using Edit on file.js")+ * - result: final result text (used for output file)+ */+function createStreamJsonParser() {+ let lineBuffer = '';+ let finalResult = '';+ let textBuffer = '';++ const processChunk = (rawData) => {+ const lines = [];+ lineBuffer += rawData;++ // Split on newlines - each JSON object is on its own line+ const parts = lineBuffer.split('\n');+ // Keep the last incomplete line in the buffer+ lineBuffer = parts.pop() || '';++ for (const part of parts) {+ const trimmed = part.trim();+ if (!trimmed) continue;++ let parsed;+ // Skip non-JSON lines (stderr mixed in, etc.)+ if (!trimmed.startsWith('{')) continue;+ parsed = JSON.parse(trimmed);+ if (!parsed) continue;++ // Extract text from streaming deltas+ if (parsed.type === 'stream_event') {+ const event = parsed.event;+ if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta') {+ const text = event.delta.text;+ textBuffer += text;+ // Emit complete lines for readability, accumulate partial+ const textLines = textBuffer.split('\n');+ textBuffer = textLines.pop() || '';+ for (const tl of textLines) {+ lines.push(tl);+ }+ }+ // Show tool use starts for visibility+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {+ const toolName = event.content_block.name || 'unknown';+ lines.push(`🔧 Using ${toolName}...`);+ }+ }++ // Extract tool results from assistant messages+ if (parsed.type === 'assistant') {+ const content = parsed.message?.content;+ if (Array.isArray(content)) {+ for (const block of content) {+ if (block.type === 'tool_result' && typeof block.content === 'string') {+ // Summarize tool results (first line only to avoid noise)+ const firstLine = block.content.split('\n')[0]?.substring(0, 200);+ if (firstLine) {+ lines.push(` ↳ ${firstLine}`);+ }+ }+ }+ }+ }++ // Capture final result text for output file+ if (parsed.type === 'result') {+ // Flush any remaining text buffer+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ finalResult = parsed.result || '';+ }+ }++ return lines;+ };++ const flush = () => {+ const lines = [];+ if (textBuffer) {+ lines.push(textBuffer);+ textBuffer = '';+ }+ return lines;+ };++ const getFinalResult = () => finalResult;++ return { processChunk, flush, getFinalResult };+}+/*** Build spawn command and arguments for a CLI provider* Returns { command, args, stdinMode } based on provider type@@ -1643,6 +1770,9 @@ function buildCliSpawnConfig(provider, model) {const args = ['--dangerously-skip-permissions', // Unrestricted mode'--print', // Print output and exit+ '--output-format', 'stream-json', // Stream JSON events for live output+ '--verbose', // Required for stream-json+ '--include-partial-messages', // Include incremental text deltas];if (model) {args.push('--model', model);@@ -1651,7 +1781,8 @@ function buildCliSpawnConfig(provider, model) {return {command: process.env.CLAUDE_PATH || 'claude',args,- stdinMode: 'prompt'+ stdinMode: 'prompt',+ streamFormat: 'stream-json'};}@@ -1666,6 +1797,9 @@ function buildSpawnArgs(config, model) {const args = ['--dangerously-skip-permissions', // Unrestricted mode'--print', // Print output and exit+ '--output-format', 'stream-json', // Stream JSON events for live output+ '--verbose', // Required for stream-json+ '--include-partial-messages', // Include incremental text deltas];// Add model selection if specified