Repository navigation
Let the terminal host own a chat agent (groundwork, nothing uses it yet) - #47229
Conversation
… 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.
…e relay spawn failure
…ing table, expire ended relays
… size; one expiry timer per ended relay
…unt relays before a severed-host restart
…essions for the severed-restart count
… held requests; restore the lockfile
Perf scan: #47229 at
|
| 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
sliceand the replaysplit. 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:
relayListandliveRelaysare sent only on request, never pushed.
The six scan questions
- Work paid before a skip gate: checked. The parse sits behind a substring prefilter, and replay skips acked seqs.
- Ownership multiplying work: checked. One spool, one pending table and one expiry timer per relay; no fan-out.
- 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
existsSyncon a failed spawn. - Growth and progress: checked. Every buffer is capped or linear. Expiry guarantees ended relays go away.
- Execution host: relays are disabled on win32 (
supported), so Windows behaves as before. Not assessed on Linux or over SSH at runtime. - 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.
…dout end, Codex-resolved requests, unacked-only file pressure, relays in idle-retirement counts
…nding replay waits for drain
…itch it back whole
|
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. |
…ce after a torn write; spill reads retry, torn spill tails are cut, and dispose waits for spill work
|
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. |
…memory; dispose settles a pending end
…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
…and ends when the attach is superseded
…ueued batch, and a superseded attach returns even while its file read is stalled
…ver waits on the replacement client's socket
…g a stalled read can't stack open readers
…, waiting attaches hold no callback on it, and a retired file frees them
Codex delta audit:
|
Perf scan:
|
Perf scan:
|
…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
Codex delta audit:
|
Perf scan:
|
| 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.byteLengthof 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-detectflags none in this change. The PR-widesubscribeandversion-bumpsurfaces are as scanned atd54dfe6. This change only moves the replay'sstream.once('close')behindSpoolReaderSlot, still one reader per relay, andepoch++is untouched.
…chNonce) that answers them
Perf scan: c0dd925 (spawn and list replies name the answering daemon start)Verdict: clean for 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.
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:
All six scan questions were assessed:
Evidence is source inspection and comparison, plus |
Review status at c0dd925What 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 Verified on this delta:
Deferred:
QA: the flows QA'd at fc211bb are unchanged by this delta (it only adds a reply field), so that QA stands. |
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 The latest change adds this work:
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 I re-confirmed the earlier coverage by comparing Git blob identities:
The existing work in those paths remains bounded as follows:
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:
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. |
QA screenshots at c0dd925The 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): That turn finishing in the same process: An approval held across the quit, asked again after relaunch (S6 A): |








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.
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:
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.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.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 onrelayAck. While detached they are appended tochat-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.relayExitcarrieserror:line-too-large,line-unreadableorline-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.control_requests, ACP permission requests), plus the highest client request id and the firstinitializeresult. A spool ack never removes them. On reattach they are re-sent first asrelayPendingevents, split like data events so no single reply line has to carry them, and the attach reply lists their seqs. An answer, acontrol_cancel_requestor Codex'sserverRequest/resolvedremoves 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.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 +liveRelaysfromlistSessions). 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.relaySpawnis 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).relaySpawnonly. A host that never relays starts up and runs exactly as before.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
listSessions.liveRelaysis 0 andrelayListis empty.sleep 3; echo donetool call finishes while detached, and its result is replayed.kill -9of the host, the agent, its background shell and its subagent are gone within 1.3 s (process-tree check by marker).relaySpawn(cleanup is lazy, like everything else in the relay).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,listSessionsgains 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
Notes
Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance
orca-provider-exec; no NULs). Spool files are private.relaySpawnis refused.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)