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
deduplicate stream-JSON parser into server/lib/streamJsonParser.js
Stefano Maffeis2418d82d0274
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex e15fe979d3..4ec3a16dc5 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -27,7 +27,7 @@ import { diagnosePtySpawnFailure, probePtyRuntime, PTY_WORKSPACE_MISSING_PREFIXimport { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';-import { createStreamJsonParser } from './streamJsonParser.js';+import { createStreamJsonParser } from '../lib/streamJsonParser.js';import { loadState, saveState, withState } from './runnerState.js';import { getProcessStats, checkProcessRunning } from './processStats.js';import { usableAgentPid, runnerAgentLivenessFields } from '../lib/runnerAgentLiveness.js';diff --git a/server/lib/README.md b/server/lib/README.mdindex b2bd6158a1..06fbb27aaa 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -418,6 +418,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `clientApiPaths.js` | Static scan of the paths `client/src/services/api*.js` requests, for the client↔server route-parity guard (`apiRouteParity.test.js`). `scanClientApiPaths({ repoRoot | sources })` constant-folds the first argument of every `request(…)` — and of every `fetch(`${API_BASE}…`)` the streaming/blob wrappers use instead — from string and template literals, module-local path helpers, ternaries and `...helper(path, …)` spreads into normalized `/api/...` paths (dynamic segments → `:p`), and REPORTS what it cannot fold instead of dropping it. `findUnmountedClientPaths(clientPaths, serverPaths)` diffs those against the `apiRouteGraph.js` inventory, honoring Express 5 `*wildcard` segments. Pure. || `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). || `jsonExtract.js` | Pull JSON blocks out of LLM responses. `extractNonPlaceholderJson(raw, { field })` skips echoed schema placeholders and distinguishes placeholder-only from parse failures. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). |+| `streamJsonParser.js` | Stream-JSON parser for Claude CLI `--output-format stream-json`. `createStreamJsonParser()` returns a stateful parser with `processChunk`/`flush`/`getFinalResult` that extracts human-readable lines from streaming NDJSON events (text deltas, tool-use markers, tool input summaries, intermediate assistant results). Also exports `summarizeToolInput(toolName, input)` for concise tool-call descriptions and `safeParse(str)` as a plain `JSON.parse` try/catch. Shared by `cos-runner/index.js` and `services/agentCliSpawning.js`. || `taskParser.js` | Parse `TASKS.md` format. || `taskGenerationOverrides.js` | `applyTaskGenerationOverrides(provider, metadata)` — the per-RUN `temperature` / `thinking` / `effort` a task form or schedule entry pins, layered onto a COPY of the provider record (the saved record is shared by every other run; the child-env composer turns the copy into OpenCode’s dynamic `agent.build` config downstream). Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings — so each override applies only when it validates, and an empty temperature field is absent rather than `0`, which would otherwise pin greedy decoding on a task whose author just cleared the box. || `cosTaskPrompt.js` | The CoS task prompt/note split (#4153) — `metadata.prompt` is the full agent-facing payload, `metadata.context` the one-line human note. `isPromptPayload(value)` is the single discriminator (a newline means it's a prompt, not a note), shared by the store's write path and the on-disk migration so they can't classify the same task differently. `getTaskPrompt(task)` prefers `metadata.prompt` and falls back to a legacy `metadata.context`; `getTaskContextNote(task)` returns the note only on an already-split task; `taskContextBlock(task)` renders both as one block so prompt templates (including customized ones) never see the split; `splitTaskPromptFields(metadata)` routes a multi-line `context` to `prompt` at CREATE time only. Pure, dependency-free. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e1dbc31956..67e0d4bbfd 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -392,6 +392,7 @@ export * from './vectorMath.js';export * from './clientApiPaths.js';export * from './htmlToText.js';export * from './jsonExtract.js';+export * from './streamJsonParser.js';export * from './taskParser.js';export * from './taskGenerationOverrides.js';export * from './cosTaskPrompt.js';diff --git a/server/cos-runner/streamJsonParser.js b/server/lib/streamJsonParser.jssimilarity index 95%rename from server/cos-runner/streamJsonParser.jsrename to server/lib/streamJsonParser.jsindex ff325ae3dc..5f37e65488 100644--- a/server/cos-runner/streamJsonParser.js+++ b/server/lib/streamJsonParser.js@@ -1,11 +1,8 @@/**- * CoS Runner — Stream-JSON parsing layer+ * Stream-JSON parsing layer shared by cos-runner and agentCliSpawning.** Self-contained — no imports, pure functions only — 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.*//**diff --git a/server/cos-runner/streamJsonParser.test.js b/server/lib/streamJsonParser.test.jssimilarity index 52%rename from server/cos-runner/streamJsonParser.test.jsrename to server/lib/streamJsonParser.test.jsindex d401e5aa08..1a82130052 100644--- a/server/cos-runner/streamJsonParser.test.js+++ b/server/lib/streamJsonParser.test.js@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest';import { summarizeToolInput, safeParse, createStreamJsonParser } from './streamJsonParser.js';-describe('cos-runner streamJsonParser', () => {+describe('lib/streamJsonParser', () => {describe('safeParse', () => {it('parses valid JSON', () => {expect(safeParse('{"a":1}')).toEqual({ a: 1 });@@ -82,5 +82,90 @@ describe('cos-runner streamJsonParser', () => {const p = createStreamJsonParser();expect(p.processChunk('garbage stderr line\n')).toEqual([]);});++ describe('getFinalResult', () => {+ // Helper used by getFinalResult tests: feed a sequence of stream-json events then flush+ function runStream(parser, events) {+ for (const ev of events) {+ parser.processChunk(JSON.stringify(ev) + '\n');+ }+ parser.flush();+ }++ const textDelta = (text) => ({+ type: 'stream_event',+ event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }+ });++ const toolStart = (index, name) => ({+ type: 'stream_event',+ event: { type: 'content_block_start', index, content_block: { type: 'tool_use', name } }+ });++ const toolStop = (index) => ({+ type: 'stream_event',+ event: { type: 'content_block_stop', index }+ });++ const resultEvent = (result) => ({ type: 'result', result });++ it('returns only the final wrap-up — interim narrations between tool calls are discarded', () => {+ const parser = createStreamJsonParser();+ runStream(parser, [+ textDelta('Now I have all the info I need. Let me make the changes:\n'),+ toolStart(1, 'Read'),+ toolStop(1),+ textDelta('Now let me run the relevant tests to verify nothing broke:\n'),+ toolStart(2, 'Bash'),+ toolStop(2),+ textDelta('Changes look clean. Now let me update the changelog and commit:\n'),+ toolStart(3, 'Edit'),+ toolStop(3),+ textDelta('## Summary\n\nAdded a `/do:replan` button to the Agent Operations section.'),+ resultEvent('## Summary\n\nAdded a `/do:replan` button to the Agent Operations section.')+ ]);++ const finalResult = parser.getFinalResult();+ expect(finalResult).toContain('## Summary');+ expect(finalResult).toContain('Added a `/do:replan` button');+ expect(finalResult).not.toContain('Now I have all the info');+ expect(finalResult).not.toContain('Now let me run the relevant tests');+ expect(finalResult).not.toContain('Changes look clean');+ });++ it('preserves both summaries across multiple result events (e.g., task + /simplify)', () => {+ const parser = createStreamJsonParser();+ runStream(parser, [+ textDelta('Investigating the bug.\n'),+ toolStart(1, 'Read'),+ toolStop(1),+ textDelta('Task summary: fixed the bug.'),+ resultEvent('Task summary: fixed the bug.'),+ textDelta('Now running /simplify.\n'),+ toolStart(2, 'Read'),+ toolStop(2),+ textDelta('Simplify summary: code is clean.'),+ resultEvent('Simplify summary: code is clean.')+ ]);++ const finalResult = parser.getFinalResult();+ expect(finalResult).toContain('Task summary: fixed the bug.');+ expect(finalResult).toContain('Simplify summary: code is clean.');+ expect(finalResult).not.toContain('Investigating the bug');+ expect(finalResult).not.toContain('Now running /simplify');+ });++ it('returns the CLI result field for a single-turn task with no interim narration', () => {+ const parser = createStreamJsonParser();+ runStream(parser, [+ toolStart(1, 'Read'),+ toolStop(1),+ textDelta('Done. All tests pass.'),+ resultEvent('Done. All tests pass.')+ ]);++ expect(parser.getFinalResult()).toBe('Done. All tests pass.');+ });+ });});});diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 0fc45be59e..70a9f86385 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -25,7 +25,7 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';import { finalizeAgentRunCommon } from './agentRunFinalize.js';import { activeAgents, pausedAgents, consumePausedAgentExit, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';-import { safeJSONParse, PATHS, writeFileGuarded } from '../lib/fileUtils.js';+import { PATHS, writeFileGuarded } from '../lib/fileUtils.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { isKnownCliStderrNoise } from '../lib/cliStderrNoise.js';import { createStreamingAnsiStripper } from '../lib/ansiStrip.js';@@ -48,208 +48,10 @@ import { isHostShuttingDown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.jsimport { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';import { isPublicReviewRestrictedProfile } from '../lib/agentExecutionProfiles.js';+import { createStreamJsonParser, summarizeToolInput, safeParse } from '../lib/streamJsonParser.js';const AGENTS_DIR = PATHS.cosAgents;-/**- * Summarize tool input into a concise description for display.- * Extracts the most relevant parameter from each tool type.- */-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 const safeParse = (str) => safeJSONParse(str, 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.- * The parser handles:- * - content_block_delta: incremental text tokens as they stream- * - tool_use events: shows tool calls with input details (e.g. "🔧 Read …/services/api.js")- * - input_json_delta: accumulates tool input JSON for detailed summaries- * - content_block_stop: emits detailed tool summary when input is complete- * - result: final result text (used for output file)- */-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 = '';- // Track active tool blocks by index for input accumulation- const activeTools = new Map(); // index -> { name, inputJson }-- // 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;-- // 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;-- // Skip non-JSON lines (stderr mixed in, etc.)- if (!trimmed.startsWith('{')) continue;- const parsed = safeParse(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;- currentTextSection += text;- // Emit complete lines for readability, accumulate partial- 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 || '';- }- }- // Track tool use start - record name and begin accumulating input- 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();- }- // When tool input is complete, emit a detailed summary line- 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);- }- }- }-- // 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') {- 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') {- 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 };-}-/*** Build spawn command and arguments for a CLI provider.* Returns { command, args, stdinMode } based on provider type.diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex c2d10c870f..6fb4159924 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -123,7 +123,7 @@ vi.mock('../lib/privateSecuritySandbox.js', () => ({preparePrivateSecuritySpawn: vi.fn(),}));-import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';+import { buildCliSpawnConfig, spawnDirectly } from './agentCliSpawning.js';import { runSpawnerCompletionCleanup } from './agentCompletionCleanup.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';@@ -134,91 +134,6 @@ import { existsSync } from 'fs';import { spawn } from '../lib/childProcess.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';-// Helper: feed the parser a sequence of stream-json lines-function runStream(parser, events) {- for (const ev of events) {- parser.processChunk(JSON.stringify(ev) + '\n');- }- parser.flush();-}--const textDelta = (text) => ({- type: 'stream_event',- event: { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text } }-});--const toolStart = (index, name) => ({- type: 'stream_event',- event: { type: 'content_block_start', index, content_block: { type: 'tool_use', name } }-});--const toolStop = (index) => ({- type: 'stream_event',- event: { type: 'content_block_stop', index }-});--const resultEvent = (result) => ({ type: 'result', result });--describe('createStreamJsonParser.getFinalResult', () => {- it('returns only the final wrap-up — interim narrations between tool calls are discarded', () => {- const parser = createStreamJsonParser();- runStream(parser, [- textDelta('Now I have all the info I need. Let me make the changes:\n'),- toolStart(1, 'Read'),- toolStop(1),- textDelta('Now let me run the relevant tests to verify nothing broke:\n'),- toolStart(2, 'Bash'),- toolStop(2),- textDelta('Changes look clean. Now let me update the changelog and commit:\n'),- toolStart(3, 'Edit'),- toolStop(3),- textDelta('## Summary\n\nAdded a `/do:replan` button to the Agent Operations section.'),- resultEvent('## Summary\n\nAdded a `/do:replan` button to the Agent Operations section.')- ]);-- const finalResult = parser.getFinalResult();- expect(finalResult).toContain('## Summary');- expect(finalResult).toContain('Added a `/do:replan` button');- expect(finalResult).not.toContain('Now I have all the info');- expect(finalResult).not.toContain('Now let me run the relevant tests');- expect(finalResult).not.toContain('Changes look clean');- });-- it('preserves both summaries across multiple result events (e.g., task + /simplify)', () => {- const parser = createStreamJsonParser();- runStream(parser, [- textDelta('Investigating the bug.\n'),- toolStart(1, 'Read'),- toolStop(1),- textDelta('Task summary: fixed the bug.'),- resultEvent('Task summary: fixed the bug.'),- textDelta('Now running /simplify.\n'),- toolStart(2, 'Read'),- toolStop(2),- textDelta('Simplify summary: code is clean.'),- resultEvent('Simplify summary: code is clean.')- ]);-- const finalResult = parser.getFinalResult();- expect(finalResult).toContain('Task summary: fixed the bug.');- expect(finalResult).toContain('Simplify summary: code is clean.');- expect(finalResult).not.toContain('Investigating the bug');- expect(finalResult).not.toContain('Now running /simplify');- });-- it('returns the CLI result field for a single-turn task with no interim narration', () => {- const parser = createStreamJsonParser();- runStream(parser, [- toolStart(1, 'Read'),- toolStop(1),- textDelta('Done. All tests pass.'),- resultEvent('Done. All tests pass.')- ]);-- expect(parser.getFinalResult()).toBe('Done. All tests pass.');- });-});-describe('buildCliSpawnConfig', () => {it('omits --model for Codex configured-default sentinel but bypasses sandbox/approvals', () => {const config = buildCliSpawnConfig({ id: 'codex', command: 'codex' }, 'codex-configured-default');