Skip to content

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

refactor([issue-749]): extract state, stream-parse, and process-stats layers from cos-runner

[._.]/ Adam Eivy0aebd6cc17b0
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index dafa1cecca..7fdf562176 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -10,16 +10,18 @@
import express from 'express';
import { spawn } from 'child_process';
-import { join, dirname, basename } from 'path';
-import { writeFile, readFile, rename } from 'fs/promises';
+import { join, basename } from 'path';
+import { writeFile, readFile } from 'fs/promises';
import { existsSync } from 'fs';
import http from 'http';
import { Server as SocketServer } from 'socket.io';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
+import { createStreamJsonParser } from './streamJsonParser.js';
+import { loadState, saveState } from './runnerState.js';
+import { getProcessStats, checkProcessRunning } from './processStats.js';
const ROOT_DIR = PATHS.root;
-const STATE_FILE = join(PATHS.cos, 'runner-state.json');
const AGENTS_DIR = PATHS.cosAgents;
const PORT = process.env.PORT || 5558;
@@ -54,191 +56,6 @@ function isAllowedCommand(command) {
return ALLOWED_COMMANDS.has(baseName);
}
-/**
- * Summarize tool input into a concise description for display.
- */
-function summarizeToolInput(toolName, input) {
- if (!input || typeof input !== 'object') return '';
- const shorten = (p) => {
- if (!p || typeof p !== 'string') return '';
- const parts = p.split('/').filter(Boolean);
- return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : p;
- };
- switch (toolName) {
- case 'Read':
- return shorten(input.file_path);
- case 'Edit':
- return shorten(input.file_path);
- case 'Write':
- return shorten(input.file_path);
- case 'Glob':
- return input.pattern || '';
- case 'Grep':
- return `"${(input.pattern || '').substring(0, 60)}"${input.path ? ` in ${shorten(input.path)}` : ''}`;
- case 'Bash': {
- const cmd = input.command || input.description || '';
- return cmd.substring(0, 80);
- }
- case 'Task':
- return input.description || '';
- case 'WebFetch':
- return shorten(input.url || '');
- case 'WebSearch':
- return `"${(input.query || '').substring(0, 60)}"`;
- case 'TodoWrite':
- return input.todos?.length ? `${input.todos.length} items` : '';
- case 'NotebookEdit':
- return shorten(input.notebook_path);
- case 'Skill':
- return input.skill || '';
- default:
- return '';
- }
-}
-
-function safeParse(str) {
- try { return JSON.parse(str); } catch { return null; }
-}
-
-/**
- * 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 = '';
- // Track text across all conversation turns so multi-step agents (e.g., task + /simplify)
- // preserve all summaries instead of only the final one
- const textSections = [];
- let currentTextSection = '';
- const activeTools = new Map();
-
- // Commit accumulated text as a section (called at result events and stream end).
- // The committed section represents an agent turn's final wrap-up.
- const commitSection = () => {
- const section = currentTextSection.trim();
- if (section) {
- textSections.push(section);
- currentTextSection = '';
- }
- };
-
- // At a tool-call boundary the accumulated text is interim narration ("Now let me…")
- // that gets superseded by whatever the agent says after the tool returns. Discard it
- // so only the final post-last-tool wrap-up survives into textSections.
- const discardSection = () => { currentTextSection = ''; };
-
- 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 = safeParse(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;
- currentTextSection += text;
- const textLines = textBuffer.split('\n');
- textBuffer = textLines.pop() || '';
- for (const tl of textLines) {
- lines.push(tl);
- }
- }
- // Accumulate tool input JSON deltas
- if (event?.type === 'content_block_delta' && event.delta?.type === 'input_json_delta') {
- const idx = event.index;
- const tool = activeTools.get(idx);
- if (tool) {
- tool.inputJson += event.delta.partial_json || '';
- }
- }
- if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
- const toolName = event.content_block.name || 'unknown';
- const idx = event.index;
- activeTools.set(idx, { name: toolName, inputJson: '' });
- lines.push(`🔧 Using ${toolName}...`);
- discardSection();
- }
- // Emit detailed summary when tool input is complete
- if (event?.type === 'content_block_stop') {
- const idx = event.index;
- const tool = activeTools.get(idx);
- if (tool) {
- if (tool.inputJson) {
- const input = safeParse(tool.inputJson);
- if (input) {
- const detail = summarizeToolInput(tool.name, input);
- if (detail) {
- lines.push(` → ${detail}`);
- }
- }
- }
- activeTools.delete(idx);
- }
- }
- }
-
- 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 = '';
- }
- commitSection();
- finalResult = parsed.result || '';
- }
- }
-
- return lines;
- };
-
- const flush = () => {
- const lines = [];
- if (textBuffer) {
- lines.push(textBuffer);
- textBuffer = '';
- }
- commitSection();
- return lines;
- };
-
- // Multi-section: return all text turns combined (e.g., task summary + simplify summary)
- // Single-section: return the CLI result field (cleaner, no tool call noise)
- const getFinalResult = () => {
- if (textSections.length > 1) {
- return textSections.join('\n\n');
- }
- return finalResult;
- };
-
- return { processChunk, flush, getFinalResult };
-}
-
// Active agent processes (in memory)
const activeAgents = new Map();
@@ -254,42 +71,6 @@ const io = new SocketServer(server, {
cors: { origin: '*' }
});
-const DEFAULT_STATE = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };
-let stateLock = Promise.resolve();
-
-/**
- * Write state atomically using temp file + rename to prevent partial-write corruption
- */
-async function atomicWrite(filePath, data) {
- const tmpPath = `${filePath}.tmp.${process.pid}`;
- await writeFile(tmpPath, data);
- await rename(tmpPath, filePath);
-}
-
-/**
- * Load runner state from disk
- */
-async function loadState() {
- if (!existsSync(STATE_FILE)) return { ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_STATE.stats } };
-
- const content = await readFile(STATE_FILE, 'utf-8');
- if (!content || !content.trim()) return { ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_STATE.stats } };
-
- return JSON.parse(content);
-}
-
-/**
- * Save runner state to disk (serialized with atomic writes to prevent corruption)
- */
-function saveState(state) {
- stateLock = stateLock.then(async () => {
- const dir = dirname(STATE_FILE);
- if (!existsSync(dir)) await ensureDir(dir);
- await atomicWrite(STATE_FILE, JSON.stringify(state, null, 2));
- });
- return stateLock;
-}
-
/**
* Emit event to connected portos-server instances
*/
@@ -319,47 +100,6 @@ app.get('/health', (req, res) => {
});
});
-/**
- * Get process stats (CPU, memory) for a PID
- */
-async function getProcessStats(pid) {
- // Security: Ensure PID is a valid integer to prevent command injection
- const safePid = parseInt(pid, 10);
- if (isNaN(safePid) || safePid <= 0) {
- return { active: false, pid, cpu: 0, memoryKb: 0, state: 'invalid' };
- }
-
- const { exec } = await import('child_process');
- const { promisify } = await import('util');
- const execAsync = promisify(exec);
-
- // Get process stats using ps command
- // %cpu = CPU percentage, rss = resident set size in KB
- const psCmd = process.platform === 'win32'
- ? `tasklist /FI "PID eq ${safePid}" /FO CSV /NH`
- : `ps -p ${safePid} -o pid=,pcpu=,rss=,state=`;
- const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));
- const line = result.stdout.trim();
-
- if (!line) {
- return { active: false, pid, cpu: 0, memoryKb: 0, state: 'dead' };
- }
-
- const parts = line.split(/\s+/).filter(Boolean);
- if (parts.length >= 3) {
- return {
- active: true,
- pid: parseInt(parts[0], 10),
- cpu: parseFloat(parts[1]) || 0,
- memoryKb: parseInt(parts[2], 10) || 0,
- memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
- state: parts[3] || 'unknown'
- };
- }
-
- return { active: true, pid, cpu: 0, memoryKb: 0, state: 'unknown' };
-}
-
/**
* Get list of active agents with process stats
*/
@@ -1054,24 +794,6 @@ async function cleanupOrphanedAgents() {
return orphaned;
}
-/**
- * Check if a process is running by PID
- */
-async function checkProcessRunning(pid) {
- // Security: Ensure PID is a valid integer to prevent command injection
- const safePid = parseInt(pid, 10);
- if (isNaN(safePid) || safePid <= 0) {
- return false;
- }
-
- const { exec } = await import('child_process');
- const { promisify } = await import('util');
- const execAsync = promisify(exec);
-
- const result = await execAsync(`ps -p ${safePid} -o pid=`, { windowsHide: true }).catch(() => ({ stdout: '' }));
- return result.stdout.trim() !== '';
-}
-
/**
* Start the server
*/
diff --git a/server/cos-runner/processStats.js b/server/cos-runner/processStats.js
new file mode 100644
index 0000000000..5b290ba8df
--- /dev/null
+++ b/server/cos-runner/processStats.js
@@ -0,0 +1,65 @@
+/**
+ * CoS Runner — Process inspection layer
+ *
+ * Reads live CPU/memory stats and liveness for spawned agent PIDs via `ps`
+ * (or `tasklist` on Windows). PID inputs are integer-validated before being
+ * interpolated into the command to prevent injection. Self-contained so the
+ * isolated `portos-cos` PM2 process stays standalone.
+ */
+
+import { exec } from 'child_process';
+import { promisify } from 'util';
+
+const execAsync = promisify(exec);
+
+/**
+ * Get process stats (CPU, memory) for a PID.
+ * Returns { active, pid, cpu, memoryKb, memoryMb?, state }.
+ */
+export async function getProcessStats(pid) {
+ // Security: Ensure PID is a valid integer to prevent command injection
+ const safePid = parseInt(pid, 10);
+ if (isNaN(safePid) || safePid <= 0) {
+ return { active: false, pid, cpu: 0, memoryKb: 0, state: 'invalid' };
+ }
+
+ // Get process stats using ps command
+ // %cpu = CPU percentage, rss = resident set size in KB
+ const psCmd = process.platform === 'win32'
+ ? `tasklist /FI "PID eq ${safePid}" /FO CSV /NH`
+ : `ps -p ${safePid} -o pid=,pcpu=,rss=,state=`;
+ const result = await execAsync(psCmd, { windowsHide: true }).catch(() => ({ stdout: '' }));
+ const line = result.stdout.trim();
+
+ if (!line) {
+ return { active: false, pid, cpu: 0, memoryKb: 0, state: 'dead' };
+ }
+
+ const parts = line.split(/\s+/).filter(Boolean);
+ if (parts.length >= 3) {
+ return {
+ active: true,
+ pid: parseInt(parts[0], 10),
+ cpu: parseFloat(parts[1]) || 0,
+ memoryKb: parseInt(parts[2], 10) || 0,
+ memoryMb: Math.round((parseInt(parts[2], 10) || 0) / 1024 * 10) / 10,
+ state: parts[3] || 'unknown'
+ };
+ }
+
+ return { active: true, pid, cpu: 0, memoryKb: 0, state: 'unknown' };
+}
+
+/**
+ * Check if a process is running by PID.
+ */
+export async function checkProcessRunning(pid) {
+ // Security: Ensure PID is a valid integer to prevent command injection
+ const safePid = parseInt(pid, 10);
+ if (isNaN(safePid) || safePid <= 0) {
+ return false;
+ }
+
+ const result = await execAsync(`ps -p ${safePid} -o pid=`, { windowsHide: true }).catch(() => ({ stdout: '' }));
+ return result.stdout.trim() !== '';
+}
diff --git a/server/cos-runner/processStats.test.js b/server/cos-runner/processStats.test.js
new file mode 100644
index 0000000000..7466d0dfb9
--- /dev/null
+++ b/server/cos-runner/processStats.test.js
@@ -0,0 +1,36 @@
+import { describe, it, expect } from 'vitest';
+import { getProcessStats, checkProcessRunning } from './processStats.js';
+
+describe('cos-runner processStats', () => {
+ describe('getProcessStats PID validation', () => {
+ it('rejects non-numeric PIDs without spawning a process', async () => {
+ const r = await getProcessStats('; rm -rf /');
+ expect(r).toEqual({ active: false, pid: '; rm -rf /', cpu: 0, memoryKb: 0, state: 'invalid' });
+ });
+ it('rejects zero and negative PIDs', async () => {
+ expect((await getProcessStats(0)).state).toBe('invalid');
+ expect((await getProcessStats(-5)).state).toBe('invalid');
+ });
+ it('reports the current process as active', async () => {
+ const r = await getProcessStats(process.pid);
+ expect(r.active).toBe(true);
+ expect(r.pid).toBe(process.pid);
+ });
+ it('reports a non-existent PID as dead', async () => {
+ // 2^31-1 is effectively never a live PID on these platforms
+ const r = await getProcessStats(2147483646);
+ expect(r.active).toBe(false);
+ expect(r.state).toBe('dead');
+ });
+ });
+
+ describe('checkProcessRunning', () => {
+ it('returns false for invalid PIDs', async () => {
+ expect(await checkProcessRunning('bad')).toBe(false);
+ expect(await checkProcessRunning(0)).toBe(false);
+ });
+ it('returns true for the current process', async () => {
+ expect(await checkProcessRunning(process.pid)).toBe(true);
+ });
+ });
+});
diff --git a/server/cos-runner/runnerState.js b/server/cos-runner/runnerState.js
new file mode 100644
index 0000000000..3f9f5846f4
--- /dev/null
+++ b/server/cos-runner/runnerState.js
@@ -0,0 +1,54 @@
+/**
+ * CoS Runner — State persistence layer
+ *
+ * Owns the on-disk runner-state.json: atomic writes, serialized saves, and
+ * loads. Kept self-contained (only fs + the shared fileUtils helper) so the
+ * isolated `portos-cos` PM2 process stays standalone.
+ */
+
+import { join, dirname } from 'path';
+import { writeFile, readFile, rename } from 'fs/promises';
+import { existsSync } from 'fs';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
+
+export const STATE_FILE = join(PATHS.cos, 'runner-state.json');
+
+export const DEFAULT_STATE = { agents: {}, stats: { spawned: 0, completed: 0, failed: 0 } };
+
+const freshState = () => ({ ...DEFAULT_STATE, agents: {}, stats: { ...DEFAULT_STATE.stats } });
+
+// Serializes saves so concurrent writes can't interleave and corrupt the file.
+let stateLock = Promise.resolve();
+
+/**
+ * Write state atomically using temp file + rename to prevent partial-write corruption
+ */
+export async function atomicWrite(filePath, data) {
+ const tmpPath = `${filePath}.tmp.${process.pid}`;
+ await writeFile(tmpPath, data);
+ await rename(tmpPath, filePath);
+}
+
+/**
+ * Load runner state from disk
+ */
+export async function loadState() {
+ if (!existsSync(STATE_FILE)) return freshState();
+
+ const content = await readFile(STATE_FILE, 'utf-8');
+ if (!content || !content.trim()) return freshState();
+
+ return JSON.parse(content);
+}
+
+/**
+ * Save runner state to disk (serialized with atomic writes to prevent corruption)
+ */
+export function saveState(state) {
+ stateLock = stateLock.then(async () => {
+ const dir = dirname(STATE_FILE);
+ if (!existsSync(dir)) await ensureDir(dir);
+ await atomicWrite(STATE_FILE, JSON.stringify(state, null, 2));
+ });
+ return stateLock;
+}
diff --git a/server/cos-runner/streamJsonParser.js b/server/cos-runner/streamJsonParser.js
new file mode 100644
index 0000000000..afef8742df
--- /dev/null
+++ b/server/cos-runner/streamJsonParser.js
@@ -0,0 +1,194 @@
+/**
+ * CoS Runner — Stream-JSON parsing layer
+ *
+ * Self-contained (no imports out to other PortOS modules beyond fs/path-free
+ * pure helpers) so the isolated `portos-cos` PM2 process stays standalone.
+ * NOTE: an equivalent parser also lives in server/services/agentCliSpawning.js
+ * for the in-process spawn path; the two are intentionally separate copies
+ * because cos-runner must not pull in the main server's dependency graph.
+ */
+
+/**
+ * Summarize tool input into a concise description for display.
+ */
+export function summarizeToolInput(toolName, input) {
+ if (!input || typeof input !== 'object') return '';
+ const shorten = (p) => {
+ if (!p || typeof p !== 'string') return '';
+ const parts = p.split('/').filter(Boolean);
+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : p;
+ };
+ switch (toolName) {
+ case 'Read':
+ return shorten(input.file_path);
+ case 'Edit':
+ return shorten(input.file_path);
+ case 'Write':
+ return shorten(input.file_path);
+ case 'Glob':
+ return input.pattern || '';
+ case 'Grep':
+ return `"${(input.pattern || '').substring(0, 60)}"${input.path ? ` in ${shorten(input.path)}` : ''}`;
+ case 'Bash': {
+ const cmd = input.command || input.description || '';
+ return cmd.substring(0, 80);
+ }
+ case 'Task':
+ return input.description || '';
+ case 'WebFetch':
+ return shorten(input.url || '');
+ case 'WebSearch':
+ return `"${(input.query || '').substring(0, 60)}"`;
+ case 'TodoWrite':
+ return input.todos?.length ? `${input.todos.length} items` : '';
+ case 'NotebookEdit':
+ return shorten(input.notebook_path);
+ case 'Skill':
+ return input.skill || '';
+ default:
+ return '';
+ }
+}
+
+export function safeParse(str) {
+ try { return JSON.parse(str); } catch { return null; }
+}
+
+/**
+ * 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.
+ */
+export function createStreamJsonParser() {
+ let lineBuffer = '';
+ let finalResult = '';
+ let textBuffer = '';
+ // Track text across all conversation turns so multi-step agents (e.g., task + /simplify)
+ // preserve all summaries instead of only the final one
+ const textSections = [];
+ let currentTextSection = '';
+ const activeTools = new Map();
+
+ // Commit accumulated text as a section (called at result events and stream end).
+ // The committed section represents an agent turn's final wrap-up.
+ const commitSection = () => {
+ const section = currentTextSection.trim();
+ if (section) {
+ textSections.push(section);
+ currentTextSection = '';
+ }
+ };
+
+ // At a tool-call boundary the accumulated text is interim narration ("Now let me…")
+ // that gets superseded by whatever the agent says after the tool returns. Discard it
+ // so only the final post-last-tool wrap-up survives into textSections.
+ const discardSection = () => { currentTextSection = ''; };
+
+ 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 = safeParse(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;
+ currentTextSection += text;
+ const textLines = textBuffer.split('\n');
+ textBuffer = textLines.pop() || '';
+ for (const tl of textLines) {
+ lines.push(tl);
+ }
+ }
+ // Accumulate tool input JSON deltas
+ if (event?.type === 'content_block_delta' && event.delta?.type === 'input_json_delta') {
+ const idx = event.index;
+ const tool = activeTools.get(idx);
+ if (tool) {
+ tool.inputJson += event.delta.partial_json || '';
+ }
+ }
+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
+ const toolName = event.content_block.name || 'unknown';
+ const idx = event.index;
+ activeTools.set(idx, { name: toolName, inputJson: '' });
+ lines.push(`🔧 Using ${toolName}...`);
+ discardSection();
+ }
+ // Emit detailed summary when tool input is complete
+ if (event?.type === 'content_block_stop') {
+ const idx = event.index;
+ const tool = activeTools.get(idx);
+ if (tool) {
+ if (tool.inputJson) {
+ const input = safeParse(tool.inputJson);
+ if (input) {
+ const detail = summarizeToolInput(tool.name, input);
+ if (detail) {
+ lines.push(` → ${detail}`);
+ }
+ }
+ }
+ activeTools.delete(idx);
+ }
+ }
+ }
+
+ 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 = '';
+ }
+ commitSection();
+ finalResult = parsed.result || '';
+ }
+ }
+
+ return lines;
+ };
+
+ const flush = () => {
+ const lines = [];
+ if (textBuffer) {
+ lines.push(textBuffer);
+ textBuffer = '';
+ }
+ commitSection();
+ return lines;
+ };
+
+ // Multi-section: return all text turns combined (e.g., task summary + simplify summary)
+ // Single-section: return the CLI result field (cleaner, no tool call noise)
+ const getFinalResult = () => {
+ if (textSections.length > 1) {
+ return textSections.join('\n\n');
+ }
+ return finalResult;
+ };
+
+ return { processChunk, flush, getFinalResult };
+}
diff --git a/server/cos-runner/streamJsonParser.test.js b/server/cos-runner/streamJsonParser.test.js
new file mode 100644
index 0000000000..d401e5aa08
--- /dev/null
+++ b/server/cos-runner/streamJsonParser.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect } from 'vitest';
+import { summarizeToolInput, safeParse, createStreamJsonParser } from './streamJsonParser.js';
+
+describe('cos-runner streamJsonParser', () => {
+ describe('safeParse', () => {
+ it('parses valid JSON', () => {
+ expect(safeParse('{"a":1}')).toEqual({ a: 1 });
+ });
+ it('returns null on invalid JSON', () => {
+ expect(safeParse('not json')).toBeNull();
+ expect(safeParse('')).toBeNull();
+ });
+ });
+
+ describe('summarizeToolInput', () => {
+ it('returns empty for non-object input', () => {
+ expect(summarizeToolInput('Read', null)).toBe('');
+ expect(summarizeToolInput('Read', 'str')).toBe('');
+ });
+ it('shortens long file paths to last two segments', () => {
+ expect(summarizeToolInput('Read', { file_path: '/a/b/c/d/e.js' })).toBe('…/d/e.js');
+ });
+ it('keeps short paths intact', () => {
+ expect(summarizeToolInput('Edit', { file_path: 'a/b.js' })).toBe('a/b.js');
+ });
+ it('summarizes Bash by command, truncated to 80 chars', () => {
+ const long = 'x'.repeat(100);
+ expect(summarizeToolInput('Bash', { command: long })).toBe('x'.repeat(80));
+ });
+ it('falls back to description for Bash without command', () => {
+ expect(summarizeToolInput('Bash', { description: 'list files' })).toBe('list files');
+ });
+ it('summarizes Grep with pattern and path', () => {
+ expect(summarizeToolInput('Grep', { pattern: 'foo', path: 'src' })).toBe('"foo" in src');
+ });
+ it('summarizes TodoWrite with item count', () => {
+ expect(summarizeToolInput('TodoWrite', { todos: [1, 2, 3] })).toBe('3 items');
+ });
+ it('returns empty for unknown tool', () => {
+ expect(summarizeToolInput('Mystery', { foo: 1 })).toBe('');
+ });
+ });
+
+ describe('createStreamJsonParser', () => {
+ const evt = (obj) => JSON.stringify(obj) + '\n';
+
+ it('extracts streamed text deltas as lines', () => {
+ const p = createStreamJsonParser();
+ const out = p.processChunk(
+ evt({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'hello\nworld' } } })
+ );
+ expect(out).toEqual(['hello']);
+ expect(p.flush()).toEqual(['world']);
+ });
+
+ it('emits a tool-use marker and detail summary', () => {
+ const p = createStreamJsonParser();
+ p.processChunk(evt({ type: 'stream_event', event: { type: 'content_block_start', index: 0, content_block: { type: 'tool_use', name: 'Read' } } }));
+ p.processChunk(evt({ type: 'stream_event', event: { type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"file_path":"/a/b/c/x.js"}' } } }));
+ const out = p.processChunk(evt({ type: 'stream_event', event: { type: 'content_block_stop', index: 0 } }));
+ expect(out).toEqual([' → …/c/x.js']);
+ });
+
+ it('returns the result field as final output for a single section', () => {
+ const p = createStreamJsonParser();
+ p.processChunk(evt({ type: 'result', result: 'final answer' }));
+ expect(p.getFinalResult()).toBe('final answer');
+ });
+
+ it('joins multiple text turns for multi-section runs', () => {
+ const p = createStreamJsonParser();
+ // turn 1
+ p.processChunk(evt({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'turn one' } } }));
+ p.processChunk(evt({ type: 'result', result: 'r1' }));
+ // turn 2
+ p.processChunk(evt({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'turn two' } } }));
+ p.processChunk(evt({ type: 'result', result: 'r2' }));
+ expect(p.getFinalResult()).toBe('turn one\n\nturn two');
+ });
+
+ it('ignores non-JSON noise lines', () => {
+ const p = createStreamJsonParser();
+ expect(p.processChunk('garbage stderr line\n')).toEqual([]);
+ });
+ });
+});