Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"node": "22.x"
},
"packageManager": "npm@11.5.1",
"version": "2.55.4",
"version": "2.55.5",
"dependencies": {
"@dreb/coding-agent": "*",
"@mariozechner/jiti": "^2.6.5",
Expand Down
2 changes: 1 addition & 1 deletion packages/agent/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dreb/agent-core",
"version": "2.55.4",
"version": "2.55.5",
"description": "General-purpose agent with transport abstraction, state management, and attachment support",
"type": "module",
"main": "./dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/ai/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dreb/ai",
"version": "2.55.4",
"version": "2.55.5",
"description": "Unified LLM API with automatic model discovery and provider configuration",
"type": "module",
"main": "./dist/index.js",
Expand Down
8 changes: 7 additions & 1 deletion packages/coding-agent/docs/rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -1794,6 +1794,12 @@ Example streaming a text response:
{"type":"message_update","message":{...},"assistantMessageEvent":{"type":"text_end","contentIndex":0,"content":"Hello world","partial":{...}}}
```

#### Dashboard-mode wire projection (`--ui dashboard`)

When the RPC server is launched with `--ui dashboard`, `message_update` events are projected **before serialization**: the cumulative top-level `message` field and the nested `assistantMessageEvent.partial` field are omitted from every frame. Both fields grow with the response, so carrying them on every delta makes the JSONL stream quadratic in response length; the dashboard reducer consumes only the delta fields (`type`, `contentIndex`, `delta`, `content`, `toolCall`), which are preserved unchanged.

The projection applies recursively to `message_update` events nested inside `background_agent_event` payloads. It does **not** apply to command responses — `get_dashboard_snapshot` still returns complete messages — and `message_end` always carries the full final message as the authoritative transcript record. RPC servers launched without `--ui dashboard` emit the full unprojected protocol shown above.

### tool_execution_start / tool_execution_update / tool_execution_end

Emitted when a tool begins, streams progress, and completes execution.
Expand Down Expand Up @@ -1961,7 +1967,7 @@ Chain completions omit ambiguous scalar model/thinking fields and instead includ
}
```

`background_agent_event` relays every JSONL event the child process emits (the same event union documented here, plus the initial session header), verbatim, tagged with the child's `agentId`. This is the live-transcript transport for observers like the dashboard — no session-file tailing needed. Streaming children emit `message_update` deltas at high frequency; consumers that fan events out further (e.g. over a network) should batch or throttle:
`background_agent_event` relays every JSONL event the child process emits (the same event union documented here, plus the initial session header), verbatim, tagged with the child's `agentId`. This is the live-transcript transport for observers like the dashboard — no session-file tailing needed. Streaming children emit `message_update` deltas at high frequency; consumers that fan events out further (e.g. over a network) should batch or throttle. Under `--ui dashboard`, the [wire projection](#dashboard-mode-wire-projection---ui-dashboard) described above applies recursively to nested `message_update` events, so relayed frames omit the cumulative `message` and `partial` fields just like top-level ones:

```json
{
Expand Down
2 changes: 1 addition & 1 deletion packages/coding-agent/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dreb/coding-agent",
"version": "2.55.4",
"version": "2.55.5",
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
"type": "module",
"drebConfig": {
Expand Down
8 changes: 8 additions & 0 deletions packages/coding-agent/src/core/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,14 @@ export class AgentSession {
return this.sessionManager.getSessionName();
}

/**
* UI surface this session was launched for (e.g. "tui", "rpc", "dashboard",
* "agent", "cli"), from the --ui flag or the mode-based default.
*/
get uiType(): string | undefined {
return this._uiType;
}

/** Scoped models for cycling (from --models flag) */
get scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> {
return this._scopedModels;
Expand Down
105 changes: 102 additions & 3 deletions packages/coding-agent/src/core/output-guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,114 @@ export function isStdoutTakenOver(): boolean {
return stdoutTakeoverState !== undefined;
}

export function writeRawStdout(text: string): void {
// ---------------------------------------------------------------------------
// Backpressure-aware bounded write queue
//
// stream.write() returns false when the stream's internal buffer is full
// (backpressure). Ignoring that signal during high-rate event streaming lets
// output queue up unboundedly inside the process, which is what produced the
// multi-thousand-event end-of-response bursts in issue 448. While the stream
// is backpressured we queue subsequent writes and flush them in order on
// "drain". The queue is byte-capped: a consumer that stalls beyond the cap
// means this process's primary output channel is dead or hopelessly behind,
// so we fail loudly instead of growing memory without bound.
// ---------------------------------------------------------------------------

/** Maximum aggregate bytes allowed for ordinary queued writes before aborting. */
export const MAX_QUEUED_STDOUT_BYTES = 16 * 1024 * 1024; // 16 MiB

const FATAL_DIAGNOSTIC_FLUSH_TIMEOUT_MS = 1_000;

const stdoutQueue: string[] = [];
let stdoutQueuedBytes = 0;
let stdoutBackpressured = false;
let stdoutDrainListening = false;
let stdoutDrainWaiters: Array<() => void> = [];

function writeToStdout(text: string): boolean {
if (stdoutTakeoverState) {
stdoutTakeoverState.rawStdoutWrite(text);
return stdoutTakeoverState.rawStdoutWrite(text);
}
return process.stdout.write(text);
}

function requestDrainFlush(): void {
if (stdoutDrainListening) return;
stdoutDrainListening = true;
process.stdout.once("drain", () => {
stdoutDrainListening = false;
flushStdoutQueue();
});
}

function flushStdoutQueue(): void {
stdoutBackpressured = false;
while (stdoutQueue.length > 0) {
const next = stdoutQueue.shift() as string;
stdoutQueuedBytes -= Buffer.byteLength(next);
// A false return means the stream accepted the chunk but its buffer is
// full again — stop writing and wait for the next drain.
if (!writeToStdout(next)) {
stdoutBackpressured = true;
requestDrainFlush();
return;
}
}
if (stdoutDrainWaiters.length > 0) {
const waiters = stdoutDrainWaiters;
stdoutDrainWaiters = [];
for (const resolve of waiters) resolve();
}
}

function enqueueStdout(text: string): void {
const bytes = Buffer.byteLength(text);
// Bound accumulated ordinary backlog, but allow one legitimate protocol frame
// larger than the cap (for example, a complete dashboard snapshot). Once that
// oversized frame is queued, any subsequent write still fails the cap check.
const exceedsAggregateCap = stdoutQueuedBytes + bytes > MAX_QUEUED_STDOUT_BYTES;
const isSingleOversizedFrame = bytes > MAX_QUEUED_STDOUT_BYTES && stdoutQueuedBytes <= MAX_QUEUED_STDOUT_BYTES;
if (exceedsAggregateCap && !isSingleOversizedFrame) {
const diagnostic =
`Fatal: stdout write queue exceeded ${MAX_QUEUED_STDOUT_BYTES} bytes while the stream was ` +
"backpressured. The consumer of this process's stdout is not reading; refusing " +
"unbounded memory growth. Aborting.\n";
let exiting = false;
const exit = (): void => {
if (exiting) return;
exiting = true;
clearTimeout(forceExit);
process.exit(1);
};
const forceExit = setTimeout(exit, FATAL_DIAGNOSTIC_FLUSH_TIMEOUT_MS);
forceExit.unref();
process.stderr.write(diagnostic, exit);
return;
}
stdoutQueue.push(text);
stdoutQueuedBytes += bytes;
}

export function writeRawStdout(text: string): void {
// Queue behind any backpressured/queued writes to preserve ordering.
if (stdoutBackpressured || stdoutQueue.length > 0) {
enqueueStdout(text);
return;
}
process.stdout.write(text);
if (!writeToStdout(text)) {
stdoutBackpressured = true;
requestDrainFlush();
}
}

export async function flushRawStdout(): Promise<void> {
// Wait for any queued output to drain so flushes observe true end-of-stream.
if (stdoutBackpressured || stdoutQueue.length > 0) {
await new Promise<void>((resolve) => {
stdoutDrainWaiters.push(resolve);
});
}

if (stdoutTakeoverState) {
await new Promise<void>((resolve, reject) => {
stdoutTakeoverState?.rawStdoutWrite("", (err) => {
Expand Down
55 changes: 55 additions & 0 deletions packages/coding-agent/src/modes/rpc/rpc-event-projection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Dashboard-mode RPC event projection.
*
* `message_update` events carry two cumulative copies of the growing assistant
* message: the top-level `message` field and `assistantMessageEvent.partial`.
* Serializing both for every token makes the child->parent JSONL pipe quadratic
* in response length and floods the stdout queue (see issue 448).
*
* The dashboard never reads those fields: its browser reducer consumes only
* the delta fields (`delta`, `content`, `toolCall`, `contentIndex`), and its
* authoritative transcript comes from `message_end` plus `get_dashboard_snapshot`
* RPC responses. The dashboard's own EventHub already strips the same fields at
* the browser SSE boundary (projectDashboardEvent); this module applies the same
* removal one boundary earlier, before JSONL serialization in runRpcMode.
*
* Only the quadratic `message_update` fields are removed here. Broader bounding
* (agent_end messages, tool_execution_update args, retry discardedPartial,
* images) remains the EventHub's browser-facing concern.
*/

function omit(event: Record<string, unknown>, ...keys: string[]): Record<string, unknown> {
const copy = { ...event };
for (const key of keys) delete copy[key];
return copy;
}

function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}

/**
* Project a single agent session event for dashboard-mode RPC transport.
*
* Unknown event types are returned exactly as received (same reference) so
* extensions and future event types remain forward-safe. Projected events are
* shallow copies — the input event is never mutated, because other session
* subscribers (and the session's own state) share the same object.
*/
export function projectDashboardRpcEvent(event: Record<string, unknown>): Record<string, unknown> {
switch (event.type) {
case "message_update": {
const projected = omit(event, "message");
const streamEvent = event.assistantMessageEvent;
return isPlainObject(streamEvent)
? { ...projected, assistantMessageEvent: omit(streamEvent, "partial") }
: projected;
}
case "background_agent_event": {
const child = event.event;
return isPlainObject(child) ? { ...event, event: projectDashboardRpcEvent(child) } : event;
}
default:
return event;
}
}
12 changes: 11 additions & 1 deletion packages/coding-agent/src/modes/rpc/rpc-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import {
} from "../../core/tools/subagent.js";
import { type Theme, theme } from "../interactive/theme/theme.js";
import { attachJsonlLineReader, serializeJsonLine } from "./jsonl.js";
import { projectDashboardRpcEvent } from "./rpc-event-projection.js";
import type {
RpcAgentTypeInfo,
RpcBackgroundAgentInfo,
Expand Down Expand Up @@ -1806,6 +1807,15 @@ export async function runRpcMode(session: AgentSession, modelFallbackMessage?: s
})
: undefined;

// Dashboard-launched runtimes (--ui dashboard) get message_update events
// projected before serialization: the cumulative `message` and
// `assistantMessageEvent.partial` fields are quadratic in response length on
// the JSONL pipe, and no dashboard consumer reads them (deltas, message_end,
// and get_dashboard_snapshot responses carry the authoritative data). Generic
// RPC consumers keep the full protocol unchanged. Only the event stream is
// projected — command responses (output() calls below) always stay complete.
const projectEvents = session.uiType === "dashboard";

// Output all agent events as JSON
session.subscribe((event) => {
if (tabTitleGenerator && !session.sessionName) {
Expand All @@ -1819,7 +1829,7 @@ export async function runRpcMode(session: AgentSession, modelFallbackMessage?: s
tabTitleGenerator.onMessageEnd(event.message);
}
}
output(event);
output(projectEvents ? projectDashboardRpcEvent(event as unknown as Record<string, unknown>) : event);
});

// Handle a single command
Expand Down
Loading
Loading