Skip to content

Let the terminal host own a chat agent (groundwork, nothing uses it yet) - #47229

Merged
brennanb2025 merged 84 commits into
mainfrom
brennanb2025/chat-relay-core
Nov 27, 2026
Merged

brennanb2025 merged 84 commits into
mainfrom
brennanb2025/chat-relay-core

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Today a chat agent (Claude, Codex, ACP) is a child of the Orca app, so when Orca quits or updates, the agent stops mid-task. Terminals don't have this problem: the background terminal host keeps them running. This PR teaches that same background host how to keep a chat agent running, hold on to what it says while nobody is watching, and hand it all back when Orca comes back. Nothing uses it yet, so nothing changes for anyone today.

Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​602 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​602
Prod 47 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3295 $\color{#cf222e}{\Huge{\mathbf{−}}}$​157 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3138

What Changed

Before: the terminal host only owns terminals. Chat agents are always started and owned by the app.

After: the terminal host (daemon protocol v63) can also own a chat agent, but only when an app asks, and no app asks yet. Users see no difference.

How it works:

  • New requests relaySpawn, relayAttach, relayWrite, relayAck, relayClose, relayList, relayDetach. The set is frozen, and the host says it supports them in its hello identity (providerRelay), so newer apps can keep talking to this version.
  • Same process ownership as today. The host starts the agent with the existing spawnManagedProviderProcess(..., { allowHost: false }), so the native owner pipe, close ladder, group reap and exit proof are reused. Only the owner moves from the app to the host. The agent's ownership journal now lives under <daemon runtime dir>/chat-relay/provider-processes, so a host that dies has its leftover agent groups swept by the next host, the same way the app sweeps its own.
  • Spool. Every stdout line gets an increasing seq. Lines pass through as raw bytes with line framing only. While a client is attached they stay in memory (up to about 1 MiB unacked) and are trimmed on relayAck. While detached they are appended to chat-relay/<relayId>.ndjson (folder 0700, file 0600). It is never flushed to disk with fsync: only the daemon that wrote the spool ever reads it, and when that daemon ends its agents end too and the next daemon deletes the file, so a flush would protect nothing, up to 16 MiB. At either cap the host stops reading the agent's stdout, so the agent waits; it is never ended for size. Detached back-pressure counts only unacked bytes. The file is deleted once fully acked, or when the relay is dropped. On reattach, replay starts after the last acked seq; it is read in 64 KiB pieces and waits whenever the app's socket is full.
  • Long lines. An unfinished line past 4 MiB moves to a private scratch file next to the spool, and is rebuilt whole when its newline arrives. If the disk fails, the line stays in memory instead. One line may be at most 256 MiB. Past that, or when a line can't be read back or delivered, the daemon ends the agent, and relayExit carries error: line-too-large, line-unreadable or line-undeliverable. A line is never skipped, because a lost JSON-RPC message would hang the chat. A rebuilt line over 64 MiB is logged. Relay cleanup at shutdown waits for disk work at most 3 s.
  • Pending-request table, kept apart from the spool: agent requests that still need an answer (JSON-RPC server requests, Claude control_requests, ACP permission requests), plus the highest client request id and the first initialize result. A spool ack never removes them. On reattach they are re-sent first as relayPending events, split like data events so no single reply line has to carry them, and the attach reply lists their seqs. An answer, a control_cancel_request or Codex's serverRequest/resolved removes one. Past 256 held requests (or 8M characters), the host stops reading the agent's stdout until answers come in; nothing is ever dropped. Only lines that can be a request or an answer (a cheap substring test) are parsed.
  • Relays count as live everywhere a host may be stopped or replaced: the host's own idle check and shutdownIfIdle; the app's checks for stale bundles, severed images, macOS TCC/resolver problems and failed health checks (getAliveDaemonSessionCount, getDaemonLiveSessionCount); the Linux severed-host restart warning; idle retirement (adapter, router and orcad census); and Manage Sessions restart (killedRelayCount). They read one helper, countLiveDaemonSessions (live PTYs + liveRelays from listSessions). A relay counts while its agent runs, and after it ends until its output is acked. An ended relay nobody comes back to is dropped after 24 h, so it can't hold a host forever. Older hosts don't send the field, so they count as before.
  • No new chats on stale code. relaySpawn is refused (refused: 'stale-bundle') when the app's version or entry path doesn't match the host's, so a stale host kept alive for its relays never starts new chats. Windows doesn't advertise the capability yet (it needs a Job Object first).
  • Lazy. The agent-spawn code, the relay folder and the journal sweep load on the first relaySpawn only. A host that never relays starts up and runs exactly as before.
  • Small moves to stay under the line budget, with no behavior change: resolveProviderExecPath → provider-exec-path.ts, the RPC shutdown handlers → daemon-shutdown-requests.ts, PTY stream wiring → daemon-session-streams.ts.

Why

This is the first step toward chat agents that keep working through an app restart or update, the way terminals already do. The host-side core lands first and on its own: with no caller it can't change behavior, and each later step (app reattach for Codex, then ACP, Claude, the update path) builds on a host that is already shipped and counted correctly. Reusing the existing provider owner means no new kill or orphan logic.

Linked Issue

Tracked in #46100 (step 1 of 5; the issue stays open until the last step lands)

Visual Proof

N/A: this adds no UI and has no caller, so nothing visible changes.

Testing

  • I manually tested these changes locally (macOS, arm64). A script drives the host's relay requests directly against a real host process, the real native provider owner and a fake JSONL agent:
    • With no caller, listSessions.liveRelays is 0 and relayList is empty.
    • The agent keeps running after its client disconnects: same agent, background-shell and subagent PIDs, and cwd and env preserved.
    • An in-flight sleep 3; echo done tool call finishes while detached, and its result is replayed.
    • Replay resumes at the last acked seq + 1, with no gap and no duplicate.
    • The held permission request is re-delivered from the pending table.
    • While a relay runs, the live count includes it.
    • Over 10 attach/detach cycles the host's fds stay at 50 and RSS stays within a few MB.
    • After kill -9 of the host, the agent, its background shell and its subagent are gone within 1.3 s (process-tree check by marker).
    • The next host removes the dead host's spool on its first relaySpawn (cleanup is lazy, like everything else in the relay).
    • SIGTERM of the host ends its relays and deletes their spools.
  • Automated tests added: spool seq/ack round trip across detach/reattach, plus back-pressure at the cap without losing lines; the pending table surviving a spool ack and reattach; and the live count including relays.
  • Every added test fails without this change and avoids the test anti-patterns.

Platforms: macOS (local). Linux and Windows: CI; see Risk.

Performance

No change for anyone today. Nothing calls the relay, and its spawn code loads only on the first relaySpawn. Host cold load, interleaved over 25 runs: main median 571 ms, this branch 575 ms (on a heavily loaded Mac). Per running host, listSessions gains one counter read. Once a later step enables the relay, its costs are one copy per line, a substring test per line and a parse only for lines that can be a request or an answer. That later step must measure and report its own costs. Measured relay throughput was 11–84 MB/s (the machine was under heavy load); fds stayed flat over 10 cycles.

Risk

Protocol bump to v63: new terminals start on a fresh host after updating, and old hosts keep their terminals through the existing previous-protocol path (62 is now attachable). That is the same thing every host-side change does. The rest is dormant code. The riskiest part is that relays now count in stop/replace decisions, but with no caller that count is always 0. The PTY-side changes are pure moves.

Back out with a plain revert. A host already running v63 stays until its terminals end, and it does no relay work.

Level: Low

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

  • Security: relay requests need the authenticated control socket of a full client pair. The launch spec is validated (absolute cwd; the owner executable is an absolute path named orca-provider-exec; no NULs). Spool files are private.
  • Windows: no capability advertised, and relaySpawn is refused.
  • Remote/orcad: the same host code; nothing calls it.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… daemon

Adds the v63 relay RPCs (spawn, attach, write, ack, close, list, detach), a
seq-numbered stdout spool with back-pressure, a pending-request table kept apart
from the spool, and a daemon-side ownership journal. Live relays count in every
daemon stop and replace decision. Nothing calls the relay yet.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: #47229 at de0fde472a58f1f3309c77ce58bff637bc5ce197

Scope. Diff vs origin/main, including the follow-up fixes (c8fc7b600a0, 980b7a18033, 2336d695568, e472f14b23f, 6a35b8a9870). Evidence comes from reading the source only. Nothing was measured at runtime (no timing, heap or bench:* runs), so impact is stated as work counts and bounds.

Verdict. As merged, the relay is dormant: nothing calls relaySpawn, so the daemon has no new idle wakeups and no new per-event work. Two items still block the PR that turns the relay on:

  1. P1, fixable now. When an agent exits while its stdout is paused for too many unanswered requests, the read side is never resumed (details below).
  2. fsync. Kept as designed; waiting on Brennan's decision.

Open findings

P1: an exit while the pending table is full leaves stdout paused forever. src/main/daemon/provider-relay/provider-relay.ts:81-92 (introduced by 6a35b8a9870)

  • Trigger: the agent exits while pending.full is true (256 unanswered requests or 8M chars).
  • What happens: onExit calls this.pending.clear() (line 83) but not updateReading(), so stdout stays paused.
    • A paused readable never emits 'end'. stdoutEnded therefore never becomes true, finished is never reached, and relayExit is never sent to an attached client.
    • The pipe fd and the relay stay alive. A detached relay is dropped only by the 24 h expiry. An attached one is never dropped.
    • liveCount stays above 0, so the daemon never goes idle (daemon-server.ts:253, daemon-shutdown-requests.ts:21).
  • Fix: call this.updateReading() right after this.pending.clear() in onExit.
  • Check that proves it: fill the table to 256, exit the child, and assert that 'end' fires and relayExit is delivered.

Waiting on Brennan: fsync of the detached spool. provider-relay-spool.ts:166 (on detach) and :229-235 (1 s timer). Kept as designed.

  • Trigger: a detached relay that is producing output.
  • Population: every detached, producing relay. 100 such agents means up to 100 fsyncs/s.
  • Bound: one fsync per 1 s window while writes happen, plus one per detach. The timer is unref'd and never re-arms on its own, so idle relays cost nothing.
  • Why it is in question: only the live daemon that created a spool reads it, and the spools of dead daemons are deleted (provider-relay-host.ts:297). The flush therefore buys no recovery the design actually uses.

Liveness risk (not a perf item): with 6a35b8a9870 a full pending table pauses the agent instead of dropping old requests. A request the agent counts as open but the client never answers through relayWrite would add up and eventually stall that agent. This covers requests resolved out of band or cancelled by an agent-side notification other than control_cancel_request. Worth confirming against the Codex and Claude protocols before enabling.

Work inventory (trigger → population → bound)

Work Trigger Population Bound / disposition
Daemon startup imports daemon boot 1 Only the small relay classes load at boot. Spawn and ownership-journal code is imported on the first relaySpawn (provider-relay-host.ts:288-289). daemon-fd-closing-exec now imports the smaller provider-exec-path, so the boot graph is slightly lighter.
First-spawn prep first relaySpawn per daemon 1 mkdir, lstat ×2, and one readdir of chat-relay/ that unlinks dead daemons' spools (:292). Runs once.
Relay request check every daemon request all daemon RPCs One Set lookup (provider-relay-requests.ts:21).
listSessions liveRelays each listSessions relays relays.size, O(1) (provider-relay-host.ts:83). The severed-restart prompt now makes one listSessions (e472f14b23f).
Idle re-check relay exit, relay removed relays onLiveCountChanged runs on exit and on remove() (:127, :237), so the daemon retires after the last relay goes.
Stdout line split each stdout chunk live relays One indexOf scan per chunk. Partial lines are joined once with Buffer.concat and decoded once. A partial line counts toward no cap, by design: pausing would deadlock any line longer than the cap. It is bounded by the agent's own line length, the same as the app reader today.
Pending prefilter and parse each agent line live relays Up to 3 includes scans. JSON.parse runs only on prefilter hits, and for the first 256 lines while initialize is unanswered. Cost is linear in output.
Pending table agent request or client answer live relays O(1) add and remove. Pauses stdout at 256 requests or 8M chars (provider-relay-pending-requests.ts:25,69). records() copies the table once per attach and does not sort it.
Pause / resume decision each line and each client write live relays updateReading() is O(1) (provider-relay.ts:222).
Live delivery each line while attached attached relays One frame per line, split into 1 MiB pieces. Bytes in flight are bounded by the 1 MiB unacked window; stdout pauses at the cap and resumes at half (spool.ts:198).
Ack trimming each relayAck attached relays Advances a head index. Acked lines are released when everything is acked, when acked bytes reach cap/2, or by the 1024-record rule (spool.ts:112-113). Average O(1) per ack; at most about cap/2 of acked text stays held.
Detached spool write each line while detached detached relays One JSON.stringify per line. Appends are batched into one queued write. Stdout pauses at 16 MiB of file (queued bytes included) and resumes at 8 MiB.
Replay on attach each relayAttach relays with a spool The file is read in 64 KiB utf8 chunks; parts with no newline are joined once (spool.ts:247-259). The read waits for socket drain between chunks and stops if the attach goes stale. Work is linear in file size, at most 16 MiB per relay.
Spool fd detached output relays with an unacked file One fd per relay. It closes once the relay has ended while detached, and again after a trailing line is flushed post-exit. Each relay also holds 3 pipes. RLIMIT_NOFILE was measured by the author at 1048576 on macOS.
Ended-relay expiry an ended relay that nobody attaches to ended relays One 24 h unref'd timer per relay, cleared on attach, remove and dispose. relayClose on an ended relay drops it at once.
Shutdown / dispose shutdown RPC, daemon stop relays Disposed in parallel with the terminals via Promise.all. Each relay ends its agent's stdin, removes its spool, and waits for queued IO (at most one coalesced write).

Regression classes touched

  • Fixed-cadence poll / new idle wakeups: two timers were checked. The fsync timer fires only while detached writes happen and is one-shot. The expiry timer fires once, is unref'd, and exists only per ended relay. No idle wakeups/s are added.
  • Hot-path rescans: there were two quadratic cases, the ack slice and the replay split. Both are fixed and now linear.
  • Per-entity state outlives the entity: the expiry map, the spool fd and the pending table are all released when their relay goes. The one open item is the exit-while-paused P1 above.
  • Unbounded queues: the pending table, the attached memory and the detached file are capped and push back on the agent. Replay honors drain.
  • Eager startup imports: spawn code is lazy; disproved.
  • Update published when nothing changed / whole snapshot: relayList and liveRelays are sent only on request, never pushed.

The six scan questions

  1. Work paid before a skip gate: checked. The parse sits behind a substring prefilter, and replay skips acked seqs.
  2. Ownership multiplying work: checked. One spool, one pending table and one expiry timer per relay; no fan-out.
  3. Which thread pays: everything runs async on the daemon event loop. Replay yields on drain between chunks. No sync fs is added, apart from the existing existsSync on a failed spawn.
  4. Growth and progress: checked. Every buffer is capped or linear. Expiry guarantees ended relays go away.
  5. Execution host: relays are disabled on win32 (supported), so Windows behaves as before. Not assessed on Linux or over SSH at runtime.
  6. Does obsolete work stop: checked. A stale attach stops its replay, and dispose and expiry release resources, except for the exit-while-paused P1.

Not covered: no runtime measurement; no app-side caller exists yet to price at fleet scale; the Linux fd and pipe behavior was not run.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-audited origin/main...70e67dc. Failed detached-spool writes are not fully fixed: thrown open/write errors are retained, but FileHandle.write result bytesWritten is ignored in provider-relay-spool.ts:250; a short write is treated as complete and its missing suffix is not retained, so a reconnect can silently lose agent output. Unterminated stdout memory is not fixed: provider-relay-line-reader.ts:162-169 reads and concatenates the complete spilled line before delivery; a very large no-newline record still creates whole-line buffers and a string at newline or EOF, so it can exhaust daemon memory. Pending replay back-pressure is not fully fixed: the new wait is after sendLine, but sendLine emits every 1 MiB piece first at provider-relay.ts:132-134 and 271-279, so one oversized held request can still fill a slow stream socket buffer. NOT SAFE: 70e67dc needs short-write handling plus streaming or capped long-line and per-frame drain behavior.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-audited origin/main...83182b7. Short writes: fixed. The spool now uses appendFile, retains the queued records on failure, cuts a torn spill tail to the last confirmed size, and skips file-backed sequence numbers during memory fallback replay so each record is delivered once. Long-line rebuild: pending Brennan’s ruling as directed; it now logs a rebuild over 64 MiB and reports a repeatedly unreadable spill rather than returning a corrupted line. Pending-request replay back-pressure: fixed. Each 1 MiB held-request frame waits for drain, and a waiting replay stops as soon as another client takes over. SAFE: 83182b7 resolves the audited findings, with the separately tracked long-line policy still pending.

…pill read counts as lost, undecodable lines are reported, dispose waits for disk at most 2s, and a removed relay is never kept by a timer
…n't be decoded or recorded is reported lost without dropping later lines; a disposed reader delivers nothing; a failing disk caps a held line at 256 MiB
…s line cap holds at its newline, a dropped line's spill file is removed, and a failed rebuild reports the line lost
…er-cap line skips its spill read, writes queued before a spool removal never land, a late spill write after dispose cleans up, and replay joins only the record that ends
…very record, a removal frees an attach waiting on file work, and a spool drained without an ack lets the host remove a finished relay
…the exit, a reattach waits only for writes and not a later compaction, and superseded attaches share one wait and read nothing
…ueued batch, and a superseded attach returns even while its file read is stalled
…ver waits on the replacement client's socket
…, waiting attaches hold no callback on it, and a retired file frees them
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Codex delta audit: 817447f..d54dfe6 (keepFrom): SAFE

The same auditor audited the keepFrom work commit by commit for 16 rounds, using Node's real ReadStream over mocked filesystem calls. Every finding was fixed in code, except one wait that the auditor agreed is acceptable. Round 16 at eab3130 says VERDICT: SAFE. d54dfe6 only adds a type to that change's close wait.

  • Reader lifetime is bounded. Over 50 takeovers with read-ahead or close callbacks stalled, superseded attaches returned at once. The successor opened only after the old descriptor closed, so a spool never had more than one replay descriptor open.
  • Cancelled waiters are released. Over 100,000 cancelled attaches, the waiter set never held more than one entry and returned to zero each time. The 25.6 MB retained in the previous round did not reproduce.
  • A retired file unblocks the successor. Acking the last indexed record let the waiting attach return while the stale read was still blocked.
  • Replay order holds. A record split across a multibyte character replayed intact, followed in order by the disk tail, the memory tail and live output.

Earlier rounds found and fixed these:

  • cleanup could remove a relay before a replacement client got its exit;
  • superseded attaches could keep waiters and reread the file;
  • write waits retained memory;
  • stale readers could pile up or wait on the replacement client's socket;
  • a takeover could release kept lines;
  • the file could grow without bound, which compaction now bounds;
  • queued write bytes weren't counted in pressure;
  • stale acks were acted on;
  • a retired file could poison the next one, through a torn row or a failed compaction.

The auditor accepted one remaining wait. A write queued behind a stalled compaction rename still waits for it, because the compaction, the unlink and the new file's first open must stay ordered on one path.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: 817447f..d54dfe6 (keepFrom): clean

A fresh reviewer read the source; nothing was timed, so the costs below are counts.

  • Per line and per ack: while keeping, each line is JSON-encoded once and merged into the pending write. The pressure check adds at most two binary searches, so the cost per line stays flat. The waste check before compaction is O(1), and spilling memory happens once.
  • Compaction: it streams in 64 KB chunks, one at a time, and runs only once acked bytes on disk reach the 16 MiB file cap. Each pass reads at most about twice the cap, which averages out against at least 16 MiB of new writes.
  • Attach: one file reader runs at a time, and waiters are freed when superseded, when the file is retired or on dispose. Waits don't pile up.
  • Idle: the change adds no timers, polls or emits.
  • New footprint: while a client keeps lines, an attached relay holds its spool file open, up to about 32 MB (16 MiB of waste plus 16 MiB kept). This grows with agent count, not with history. Plain acks don't change.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: d54dfe6, subscribe and version-bump surfaces: clean

A fresh reviewer read the source for the two surfaces perf-surface-detect flags on this PR. It ran nothing.

subscribe

  • Per relay: provider-relay.ts:83–100 registers 5 listeners in the relay's constructor: stdout data, end and error, stdin error, and onExit. Attach, detach, ack and append add none. The listeners last as long as the child's stdio.
  • Per spawn: provider-relay-host.ts:129 registers one child.on('error') at spawn.
  • Per replay: provider-relay-spool-replay.ts:87 adds one stream.once('close') per replay stream, and only while that stream is open. Only one file reader runs at a time, so each relay has at most one, and takeovers don't add more.

version-bump

  • When it bumps: epoch++ (provider-relay-spool-file.ts:190) runs only in remove(). That is called when every line in the file is acked, when the file is lost, or on dispose. An ack bumps it only when it acks the whole file.
  • What a bump costs: O(writes not yet started). Each is emptied once, and repeated removals share one close and unlink.
  • What a bump invalidates: queued writes and compaction check the epoch and return in O(1). Nothing is recomputed.

brennanb2025 added a commit that referenced this pull request Nov 24, 2026
…eeping a long line on disk costs no escaping scan on the daemon thread
…decoded from invalid UTF-8 is larger than the bytes it was read as
…re dropped at the spool file cap, so a client knows its replay starts mid-item
… queue and index, so short raw rows can't pile up under the cap
…rough the new client's own acks never reports a gap it didn't have
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Codex delta audit: d54dfe6..fc211bb (raw spool rows, truncatedThrough): SAFE

The same auditor ran three rounds, using Node's real ReadStream over mocked filesystem calls. Round 3 at fc211bb says VERDICT: SAFE.

  • Framing: the line reader is the only source of spool lines. Normal splitting, spill stitching, spill-write failure and stdout-end flushing all keep line boundaries, so no line reaches the spool with a newline. Replay and compaction agree on seq prefixes split across chunks, and both drop an unterminated last row. A failed append replays its records from memory, in order.
  • Round 1 finding, fixed: short raw rows let far more records pile up under the same cap during a stalled write. Every file row is now also charged the 64-byte per-record cost memory already uses, and compaction debits it for the rows it drops. A blank-line flood now pauses at about 238k records and 32 MB of heap, down from 1.99M records and 273 MB. Compaction accounting matched the rows left across five rewrites, including an append and an ack during a blocked rename.
  • Round 2 finding, fixed: truncatedThrough could tell a client about a gap it didn't have, when its own ack released kept lines during its replay. The value is now read before the replay. The same attach now omits it. Later attaches report it below the dropped seq and omit it at or above it. Ordinary acks never set it.
  • Takeover: a takeover during the pending-request preamble rejected the superseded attach without replay data. The replacement got its records in order, with no false marker.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: d54dfe6..fc211bb (raw spool rows): clean

This change is the fix for the perf P1. While keepFrom was set, every held line went through JSON.stringify on the daemon thread. Rows are now raw <seq> <line>\n. The numbers below are from one in-process harness on the same machine (the second of two runs), feeding JSON-RPC-shaped lines full of quotes and backslashes through ProviderRelaySpool while attached and keeping.

Case Append, before → after Replay read-back, before → after
4 MB tool result 6.0 ms → 0.4 ms 7.4 ms → 1.7 ms
48 MB line 73.6 ms → 4.3 ms 90.8 ms → 25.8 ms
20,000 × 1 KB deltas 41 ms → 4.0 ms 38 ms → 6.9 ms
  • What's left on the append path: Buffer.byteLength of the row, about 0.09 ms/MB. It stays because a line decoded from invalid UTF-8 is larger than the bytes it was read as.
  • The write itself: it is already batched on the file's write chain, not in append. Its largest event-loop stall was 2.5 ms for the 48 MB line (monitorEventLoopDelay), so no further move off the thread is needed.
  • Heap: each file row is now also charged a 64-byte per-record cost. Under a stalled disk, a blank-line flood pauses at about 238k records and 32 MB of heap, down from 1.99M and 273 MB with raw rows charged by bytes alone.
  • Surfaces: perf-surface-detect flags none in this change. The PR-wide subscribe and version-bump surfaces are as scanned at d54dfe6. This change only moves the replay's stream.once('close') behind SpoolReaderSlot, still one reader per relay, and epoch++ is untouched.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan: c0dd925 (spawn and list replies name the answering daemon start)

Verdict: clean for 0f64d8703a7..c0dd9250b1e only. Confirmed checkout head c0dd9250b1eca96e104c03b88bfc52b001f74565. Read the requested skill and its perf, Git, platform, and session-reliability references. No files edited.

No findings added by this change, and no pre-existing amplification identified in the supporting paths inspected. Earlier PR changes remain covered by the prior scans.

New or changed work Trigger and population Bound and evidence
Pass identity into relay host Once per daemon construction Two property assignments referencing the existing nonce; no additional UUID generation, imports, I/O, or startup awaits.
Optional protocol fields Type checking Erased types; zero runtime work.
Construct identity object Every authenticated relay request, including write/ack At most two trivial getter reads and one single-property object per request, independent of relay count, payload size, and history. Non-relay and unauthenticated requests return before this work. requests:21–34
Decorate spawn result Once per spawn settlement One added Promise continuation; success shallow-copies two existing fields and identity. Failure/refusal results pass through. One callback and captured identity object per already-pending spawn; no independent queue or retry. requests:36
Decorate list result Once per list request One shallow wrapper copy. The relay array is reused; the existing inventory traversal still runs exactly once. At 100/1,000 relays, one list still visits 100/1,000 entries, with constant added decoration. requests:62
Serialize identity Each successful spawn/list reply Existing single NDJSON serialization and socket write. Normal 36-character UUID adds 56 bytes per reply, once per response rather than per relay. Null identity adds none.

For a workload of 100 agents each acknowledging once per second, the added request-side work is 100 small objects and at most 200 getter reads/second; at 10×, 1,000 objects and 2,000 reads/second. There are no collection walks behind those reads. A burst of 100/1,000 successful spawn/list replies adds 5.6/56 KB total. These are source-derived counts, not timing measurements.

The touched regression classes were checked:

  • Work before skip gates: matched the identity allocation before the request switch; constant scalar work, with request/authentication admission already enforced.
  • Whole-snapshot publication / hot-path rescans: disproved amplification; decoration neither copies the array nor repeats the existing listing.
  • Abandoned work / retention: one continuation per existing spawn; no added timer, listener, registry, retry, or accumulating history.
  • Eager startup work: no new runtime import, initialization call, or asynchronous dependency.

All six scan questions were assessed:

Question Disposition
Unused work before gates Reviewed; bounded allocation described above.
Ownership multiplies work Reviewed; one host identity, no new owners or consumers.
Thread/storage cost Daemon event loop pays constant decoration and added serialization bytes; no added filesystem, SQL, or subprocess work.
Growth/progress Added cost is constant per request; existing inventory complexity unchanged.
Execution host Platform-neutral metadata; Windows relay restriction unchanged. No added remote round trips.
Obsolete work stops No new background activity. Added steady-idle wakeups: 0 → 0 per daemon.

Evidence is source inspection and comparison, plus git diff --check. No tests, benchmarks, Electron, or live Windows/Linux/SSH/WSL runs were performed; no latency, CPU, or heap measurements are claimed. The verdict covers the added work and its checked bounds.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status at c0dd925

What changed since the last review (fc211bb): one commit of this PR's own, c0dd925, plus a merge of main. Spawn and list replies from the terminal daemon now also say which daemon start answered them, in a new optional daemonInstance field set to that start's hello launchNonce. The stacked Codex PR (#47783) uses it to tie each kept chat to the exact daemon start running it. Users see no change; older apps ignore the field, and newer apps treat a reply without it as coming from an older daemon.

Verified on this delta:

  • Regression audit (Codex, scoped to 0f64d87..c0dd925): SAFE. No must-fix, should-fix or nit findings.
    • Covered: callers, protocol compatibility in both directions, restart and reconnect, Windows/Linux/macOS, SSH, quit and data loss, and performance.
  • Performance scan: clean (comment above). The new work per relay request is constant metadata, with no I/O, timers or retained collections.
  • Claude review: READY TO MERGE, no P0 or P1.

Deferred:

QA: the flows QA'd at fc211bb are unchanged by this delta (it only adds a reply field), so that QA stands.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan at c0dd925: all detected surfaces (subscribe, version-bump, daemon-provider-relay)

Reviewed c0dd925 using the specified perf-scan instructions and applicable references. Verdict: clean for the requested scope. No confirmed amplification found, either added by this PR or pre-existing on main.

The supplied core-c0dd925.diff exactly matches git diff 0f64d8703a7 c0dd9250b1e.

The latest change adds this work:

Change Trigger and population Work and bound
Pass the daemon identity through server construction, relay factory and host Once per daemon start Retains the existing nonce string; no new UUID generation, I/O, import or startup await.
Add optional protocol fields Type checking only No runtime work.
Construct instance in provider-relay-requests.ts:34 Each authenticated relay request, including writes and acks One temporary object and at most two constant-time getter reads. No collection traversal or retained registration.
Decorate successful spawn replies Once per successful spawn One promise continuation and shallow result copy. Refusals and failures retain their existing result.
Decorate list replies Once per requested listing One shallow wrapper copy; the existing relay array is reused. The identity appears once per response, rather than once per relay.

For the normal 36-character UUID nonce, serialization adds 56 bytes per successful spawn or list response. At an illustrative 12 callers each listing every three seconds, that is 224 additional bytes/s; scaling callers alone to 120 gives 2,240 bytes/s. These are calculated payload counts, not measured traffic. I found no in-tree recurring relayList caller. The change adds zero steady-idle wakeups/s on daemon, Electron main or renderer.

I re-confirmed the earlier coverage by comparing Git blob identities:

  • Unchanged: provider-relay-spool-row.ts, provider-relay-spool-file.ts, provider-relay-spool-compaction.ts, provider-relay-spool-replay.ts, provider-relay-spool-reader-slot.ts, provider-relay-spool.ts, provider-relay.ts.
  • Changed: provider-relay-host.ts, solely by the optional identity option and getter.

The existing work in those paths remains bounded as follows:

Path/work Trigger and population Bound and progress
Row encoding and appending Each output line, for its owning relay Required line bytes are encoded once. One file write runs at a time; queued writes coalesce up to 8 Mi characters, with queued bytes and callback overhead charged to pressure.
Buffering and acknowledgements Output and acks, per relay Backpressure thresholds remain 1 MiB in memory and 16 MiB for detached/kept output, with half-cap resume hysteresis. These are pressure thresholds, not hard allocation ceilings: the current input and individual large lines can overshoot them. The upstream line limit remains 256 MiB.
Compaction An ack leaves at least one file-cap of retired data One compaction per spool at a time; 64 KiB streaming reads and batched writes. Cost follows that spool’s file bytes, without scanning other relays or chat history.
Attach/replay Attach or takeover, per relay One open spool reader per relay; 64 KiB read chunks, socket-drain waits, generation checks and cancellable waiters. Long rows collect pieces and join once. Replay verification visits the relevant indexed records.
Listing Explicit relayList, across retained relays One metadata projection per retained relay; no transcript or spool reads. At 100/1,000 retained relays, one listing projects 100/1,000 entries.
Preparation and cleanup First spawn; exit, close or disposal Preparation is shared through one promise. Dead-owner cleanup visits directory entries once per successful preparation, with no polling loop. Ended relays have at most one 24-hour expiry timer each. Shutdown’s cleanup wait remains bounded at three seconds.

These relay mechanisms were already present at the previous clean scan; the latest change neither bypasses their gates nor changes their populations or cadence.

The touched regression classes were checked:

Class Disposition
Snapshot publication/fanout Disproved: listing was already request-driven; the new field adds no traversal, publication or subscriber.
Streaming reprocessing / repeated-prefix reads Disproved: latest change adds neither; existing replay retains chunked reads and single joins.
Whole-file rewrites Checked: compaction retains its waste threshold and single-flight guard.
Queue/resource growth and abandoned work Checked: pressure accounting, reader serialization, cancelled waits and attachment release remain intact.
New idle wakeups / bypassed gates No matching change.
Eager startup work No new runtime import or preparation call.

All six scan questions were addressed: admission remains before relay handling; ownership stays per daemon and relay; added work runs on the daemon request path; growth follows required output or requested inventory; no new host-dependent operation appears; and takeover/disposal retain cancellation and resource-release paths. Windows relay admission remains disabled.

Evidence is source inspection, exact diff/blob comparisons and serialized-byte calculation. No application, tests or benchmarks were run, so there are no timing, CPU or heap claims. Live macOS/Linux, SSH/WSL transport and adverse-disk behavior were not exercised. No files were edited; the working tree remains clean.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA screenshots at c0dd925

The stacked Codex PR #47783 ran its QA on top of this exact core head, since c0dd925 is its base. That run (round 25, Omarchy Linux, hidden Electron copy, isolated profile) exercises this PR's daemon relay end to end. In each case, a Codex chat's agent kept running under the terminal daemon through a graceful quit and relaunch, and the app reattached to it: the same Codex process before and after, the relay listed by the daemon start that answered, and no stale-session rows. 7 of 7 cases passed.

A turn still running after relaunch (S1 run 1):

S1 after relaunch

That turn finishing in the same process:

S1 done

An approval held across the quit, asked again after relaunch (S6 A):

S6 A after relaunch

S6 A after allow

s1-1-after-relaunch

s1-1-after-done

s6-a-after-relaunch

s6-a-after-allow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant