Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
Merge origin/main into feat/remote-host-kernel
vastsa952c75cb9bd6
diff --cc apps/desktop/electron/main/bootstrap/shutdown.tsindex c18d12412,da9cdb43e..098ac11ce--- a/apps/desktop/electron/main/bootstrap/shutdown.ts+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts@@@ -12,7 -12,7 +12,8 @@@ import type { PluginViewHost } from "..import type { AppUpdaterController } from "../updater";import type { UserMcpRuntime } from "../user-mcp";import type { McpControlServer } from "../mcp-control";+ import type { McpOAuthManager } from "../mcp-oauth";+import { getActiveRemoteHostsBoot, setActiveRemoteHostsBoot } from "./remote-hosts";const QUIT_TURN_SETTLE_BUDGET_MS = 2_000;diff --cc apps/desktop/electron/main/index.tsindex 8b06e0ad9,bd0a41aad..9fba91df3--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@@ -92,11 -92,11 +92,8 @@@ importexecutionFromResponse,executionListFromResponse,planExecutionFromUnknown,-} from "./plan-execution";-import {- readWindowState,- writeWindowState,-} from "./window-preferences";+} from "@pi-desktop/host-runtime";- import {- readWindowState,- writeWindowState,- } from "./window-preferences";++import { readWindowState, writeWindowState } from "./window-preferences";import { createPlanUiProbe } from "./plan-ui-probe";import type { McpControlController, McpControlServer } from "./mcp-control";import type { AgentHostBridge } from "./agent-host-bridge";diff --cc apps/desktop/test/agent-capability-settings.test.mjsindex 5adcd1b8a,5adcd1b8a..576e9f761--- a/apps/desktop/test/agent-capability-settings.test.mjs+++ b/apps/desktop/test/agent-capability-settings.test.mjs@@@ -297,9 -297,9 +297,11 @@@ test("revealing a skill carries the levtest("skill import is one native file and is copied through the host", () => {assert.notEqual(skillImport, "", "skill import handler should be present");assert.match(skillImport, /properties:\s*\["openFile"\]/);-- assert.doesNotMatch(skillImport, /properties:\s*\[[^\]]*(?:multiSelections|openDirectory)/);++ // Scan-and-import (a separate `skillImportScan` handler) opens a directory,++ // but the single-file skill-import branch must never do that or select many.++ assert.doesNotMatch(skillImport, /properties:\s*\[[^\]]*multiSelections/);assert.match(skillImport, /host\.call\("skills\.import"/);-- assert.match(read("../../../crates/host-core/src/user_skills.rs"), /fs::copy\(&source_path, &target\)/);++ assert.match(read("../../../crates/host-core/src/user_skills.rs"), /fs::copy\(source, target\)/);});test("MCP management reuses the validated modal and blocks same-level duplicates", () => {diff --cc apps/desktop/test/bounds-watchdog-platform.test.mjsindex 000000000,3976eb6d8..9b343c76emode 000000,100644..100644--- a/apps/desktop/test/bounds-watchdog-platform.test.mjs+++ b/apps/desktop/test/bounds-watchdog-platform.test.mjs@@@ -1,0 -1,67 +1,74 @@@+ /**+ * The Stage Manager bounds watchdog is macOS-only (D447).+ *+ * Behavioral: the platform rule is the whole decision — macOS keeps the+ * recovery watchdog, every other platform turns it off.+ *+ * Contract: `createWindow` clears the interval before it can read CG bounds or+ * re-layer the window, so no platform other than macOS repeats a+ * `setAlwaysOnTop(false)` that a window manager answers by raising the window.+ */+ import assert from "node:assert/strict";+ import test from "node:test";+ import { register } from "node:module";+ import { dirname, join } from "node:path";+ import { fileURLToPath, pathToFileURL } from "node:url";+ import { readMainModule } from "./helpers/source-contracts.mjs";++ const here = dirname(fileURLToPath(import.meta.url));+ register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++ const windowSource = await readMainModule("bootstrap/window.ts");++ /** The `boundsWatchdog` interval body, from its `setInterval` to its closing. */+ function watchdogBody() {- const start = windowSource.indexOf("const boundsWatchdog = setInterval(");- assert.notEqual(start, -1, "the bounds watchdog interval must exist");- const end = windowSource.indexOf("}, 1500);", start);++ // The source used to be a bare `const boundsWatchdog = setInterval(...)`;++ // it became `const boundsWatchdog: NodeJS.Timeout | null =++ // process.platform === "darwin" ? setInterval(...) : null` when the watchdog++ // stopped being registered on non-macOS platforms. Anchor on `setInterval(`++ // after the declaration so either form is accepted.++ const declaration = windowSource.indexOf("const boundsWatchdog");++ assert.notEqual(declaration, -1, "the bounds watchdog interval must exist");++ const start = windowSource.indexOf("setInterval(", declaration);++ assert.notEqual(start, -1, "the bounds watchdog must use setInterval");++ const end = windowSource.indexOf("}, 1500)", start);+ assert.notEqual(end, -1, "the watchdog must keep its 1500ms cadence");+ return windowSource.slice(start, end);+ }++ test("the bounds watchdog turns itself off outside macOS", () => {+ const body = watchdogBody();+ const guard = body.indexOf('if (process.platform !== "darwin")');+ assert.notEqual(guard, -1, "the watchdog must be gated on darwin");+ // The guard has to clear the interval, or it keeps ticking forever.+ const guardBlock = body.slice(guard, body.indexOf("const cg = readCgBounds();", guard));+ assert.match(guardBlock, /clearInterval\(boundsWatchdog\);/);+ assert.match(guardBlock, /return;/);+ // And it has to run before the watchdog can touch the window layer, which is+ // what Mutter answers by raising the window.+ assert.ok(+ guard < body.indexOf("setAlwaysOnTop(false)"),+ "the platform guard must precede the always-on-top reset",+ );+ assert.ok(+ guard < body.indexOf("ensureStableBounds(true)"),+ "the platform guard must precede shelf recovery",+ );+ // macOS keeps the Stage Manager path intact (D039, D053, D083).+ assert.match(body, /readCgBounds\(\)/);+ assert.match(body, /ensureStableBounds\(true\)/);+ });++ test("no other platform path re-layers the window on a timer", () => {+ // A repeating timer that clears the always-on-top layer is exactly what+ // Mutter turns into a raise, so it may only exist behind the darwin guard.+ const intervals = windowSource.split("setInterval(").slice(1);+ for (const chunk of intervals) {+ if (!chunk.includes("setAlwaysOnTop")) continue;+ assert.match(+ windowSource,- /if \(process\.platform !== "darwin"\) \{\s*clearInterval\(boundsWatchdog\);\s*return;\s*\}/,++ /if \(process\.platform !== "darwin"\) \{\s*(?:if \(boundsWatchdog\) )?clearInterval\(boundsWatchdog\);\s*return;\s*\}/,+ "a window-layer timer must be macOS-only",+ );+ }+ });diff --cc apps/desktop/test/extensions-page.test.mjsindex ddbd7057f,ddbd7057f..664c05bc1--- a/apps/desktop/test/extensions-page.test.mjs+++ b/apps/desktop/test/extensions-page.test.mjs@@@ -172,7 -172,7 +172,7 @@@ test("skill import is one native file aassert.doesNotMatch(handler, /\bmultiple\b/);assert.match(handler, /host\.call\("skills\.import"/);assert.match(settingsComponents.get("AgentSkillsPage.tsx"), /api\.importUserSkill\(/);-- assert.match(hostCapabilitySources, /fs::copy\(&source_path, &target\)/);++ assert.match(hostCapabilitySources, /fs::copy\(source, target\)/);});test("MCP management reuses the modal and validates its locked id and transport branches", () => {diff --cc apps/desktop/test/session-message-presentation.test.mjsindex 812928f6e,812928f6e..377ea8d5f--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@@ -42,6 -42,6 +42,17 @@@ function loadComponent(name, extras = {"../../../components/Markdown": { Markdown: ({ source: text }) => text },"../../../components/icons": new Proxy({}, { get: () => Icon }),"../../../components/ui": { TooltipButton },++ "../../../lib/hosted-search-ui": {++ HOSTED_SEARCH_PREVIEW_COUNT: 5,++ hostedSearchHost: () => "",++ hostedSearchFaviconCandidates: () => [],++ hostedSearchLabel: () => "",++ hostedSearchTitle: () => "",++ rewriteInlineCitationMarkup: (text) => text,++ urlsReferToSameSource: () => false,++ sourcesForHref: () => [],++ openChatHttpUrl: () => {},++ },"./shared": shared,...extras,};diff --cc apps/desktop/test/transcript-file-chips.test.mjsindex e0fe3f6d3,e0fe3f6d3..c1a0ab2ac--- a/apps/desktop/test/transcript-file-chips.test.mjs+++ b/apps/desktop/test/transcript-file-chips.test.mjs@@@ -64,7 -64,7 +64,7 @@@ test("a tool row and a tool result rowassert.match(hook, /const openFileRef = useOpenChatFileRef\(\);/);assert.match(hook,-- /target\.kind === "file" \? openFileRef\(target\.path\) : openUrl\(target\.url\)/,++ /target\.kind === "file" \? openFileRef\(target\.path\) : openHttpUrl\(target\.url\)/,);assert.doesNotMatch(hook, /openFile\(target\.path\)/);// Both surfaces still call that opener, and neither reaches the host viewer'sdiff --cc apps/desktop/test/window-resize.test.mjsindex 603a0b309,603a0b309..1f8d4c343--- a/apps/desktop/test/window-resize.test.mjs+++ b/apps/desktop/test/window-resize.test.mjs@@@ -12,8 -12,8 +12,10 @@@ const reservationHandler = mainSource.stest("the main window keeps native edge and corner resizing enabled", () => {assert.match(mainSource, /resizable:\s*true/);-- assert.match(mainSource, /minWidth:\s*windowMinWidth/);-- assert.match(mainSource, /minHeight:\s*windowMinHeight/);++ // The BrowserWindow props use the clamped `initialMin*` values so a small++ // work area does not lock the window past the display's own width.++ assert.match(mainSource, /minWidth:\s*initialMinWidth/);++ assert.match(mainSource, /minHeight:\s*initialMinHeight/);});test("bounds recovery waits for a stable native resize snapshot", () => {diff --cc apps/desktop/test/work-panel.test.mjsindex 7606da33d,7606da33d..34697423e--- a/apps/desktop/test/work-panel.test.mjs+++ b/apps/desktop/test/work-panel.test.mjs@@@ -422,8 -422,8 +422,13 @@@ test("work panel separator exposes intetest("Electron enforces the responsive shell minimum", () => {assert.match(mainSource, /const WINDOW_MIN_WIDTH = 1040/);assert.match(mainSource, /const WINDOW_MIN_HEIGHT = 700/);-- assert.match(mainSource, /minWidth:\s*windowMinWidth/);-- assert.match(mainSource, /minHeight:\s*windowMinHeight/);++ // The window creation clamps the minimum to fit the current work area, so++ // the props are the clamped `initialMin*` values, both derived from++ // `windowMin*` via `Math.min(windowMin*, restoreWorkArea.*)`.++ assert.match(mainSource, /minWidth:\s*initialMinWidth/);++ assert.match(mainSource, /minHeight:\s*initialMinHeight/);++ assert.match(mainSource, /initialMinWidth = Math\.min\(windowMinWidth/);++ assert.match(mainSource, /initialMinHeight = Math\.min\(windowMinHeight/);});test("built-in terminal is absent while the work panel keeps its other surfaces", () => {diff --cc docs/adr/0284-headless-runtime-boundary.mdindex 67ad351f6,000000000..b02414d80mode 100644,000000..100644--- a/docs/adr/0284-headless-runtime-boundary.md+++ b/docs/adr/0284-headless-runtime-boundary.md@@@ -1,118 -1,0 +1,118 @@@- # ADR 0283: Headless runtime boundary in `packages/host-runtime`++# ADR 0284: Headless runtime boundary in `packages/host-runtime`++- Status: Accepted for implementation+- Date: 2026-09-18+- Decision: D447+- Related: ADR 0205 (D373 / D374 / D375), ADR 0213 (D386),+ `02-architecture/05-remote-agent-control.md` §4 and §11,+ `03-runtime/07-process-model.md` §4,+ `06-delivery/07-remote-control-rollout.md` R2++## Context++Rollout R1 delivered the headless Agent Host module (`packages/agent-host`):+admission, the turn queue, the approval broker, the event log, and the+snapshot builder run without Electron. Everything underneath it did not. The+stdio transports to host-core and the agent sidecar, the restart supervisor,+the durable turn lifecycle (`session.beginTurn` → prompt → `session.endTurn`),+transcript persistence, the in-flight reply checkpoint, and approved+Plan/Goal execution all lived in `apps/desktop/electron/main`, and the+Electron `AgentHost` bridge reached them by invoking the desktop's own IPC+handlers. `HostProcess` resolved the binary from `process.resourcesPath`, and+`AgentSidecar` could only start the sidecar as+`process.execPath` + `ELECTRON_RUN_AS_NODE`.++R2 needs the same runtime on a machine that has no Electron: the `pi-host`+bundle (`02-architecture/05-remote-agent-control.md` §5.2) must run the Agent+Host module, the sidecar, and host-core behind a RACP server. Re-implementing+the turn lifecycle in a second place would create a second source of truth+for exactly the invariants the desktop spent a year fixing (abort locks,+stale terminal events, single-flight finalization, queue release after+durable settlement).++## Decision++1. **A new workspace package, `packages/host-runtime`, owns the+ Electron-independent runtime layer.** It depends on `shared`,+ `agent-host`, and `agent-runtime` only, and never on `electron` or on+ `apps/desktop`. Its modules are:+ - `HostProcess` and `AgentSidecar`: the stdio NDJSON JSON-RPC transports,+ moved from Electron main unchanged in behavior. Both take their launch+ as options — `binaryPath` / `dataDir` / extra `env` for host-core,+ `{ command, args, env }` for the sidecar — and an `onStderr` sink. The+ sidecar's `host.proxy` allowlist, local-tool short circuit, Plan-mode+ gate, vendor-auth binding check, and trusted-extension bridge are+ unchanged. `HostProcess` accepts an optional `diagnoseFailure` hook so+ an embedding host can name a boot refusal it can phrase.+ - `RuntimeSupervisor`: the restart policy of process-model §4 (0.5s → 1s+ → 2s capped at 4s, three restarts per two-minute window, single flight+ per child, never during shutdown, stop on the first unrecoverable+ failure). The embedding host supplies `start`, `afterRestart`,+ `isUnrecoverable`, and an event sink.+ - `RuntimeService`: `RuntimePort` for the Agent Host module on top of the+ two transports — prompt admission with the durable turn row and the+ user message appended before the sidecar starts, steer, stop, abort+ with the abort lock, asktool answers, manual compaction, and+ `finishTurn` with the same claim-before-await rule, stale-terminal+ guard, and settlement announcement as Electron main.+ - `TurnEventPipeline` and `TurnPersistence`: the per-event pass+ (tool-call tracking, D299 checkpoints, terminal events, completed rows)+ and an in-memory ordered append queue with a bounded retry while+ host-core restarts. A `pi-host` process ends only with its supervisor,+ so the desktop's file-backed outbox is not duplicated.+ - `createHeadlessLaunchResolver`: launch resolution from host-core's own+ registries (providers and secrets, the effective command shell, project+ instructions and memory, user skills, subagent definitions). It refuses+ vendor OAuth accounts and plugin agents, which need the desktop.+ - `PlanExecutionDispatcher`: approved Plan/Goal execution (D189) with the+ same claim, no-replay, and finalization rules.+ - Host-core adapters for the module's `SessionPort`, `QueueStore`+ (schema v15), and `permissions.pending`, plus the session-message+ ledger lookup, the inflight checkpointer, and the plan-execution+ decoders, moved out of Electron main.+2. **Electron main keeps thin adapters.** `electron/main/host-process.ts`+ and `agent-sidecar.ts` subclass the package classes and add only what+ Electron knows: the packaged binary and bundled-plugin locations, the+ `ELECTRON_RUN_AS_NODE` launch, redacted stderr logging, and the+ schema-too-new / glibc diagnoses. `runtime/lifecycle.ts` drives the shared+ supervisor and keeps the renderer status pushes, plugin locale resync,+ and approved-plan drain. The Agent Host bridge uses the shared host-core+ ports instead of its own copies. The local prompt path (`agent-ipc.ts`),+ with its attachments, slash expansion, plugin tools, MCP relay, vendor+ accounts, and notifications, is unchanged and still owned by the desktop.+3. **`TurnStartRequest` gains an optional `userMessageId`** so a client can+ keep its optimistic user row id through the headless runtime, exactly as+ the renderer does through IPC (D288). Additive; no caller is required to+ send it.+4. **No wire contract changes.** Electron IPC, the sidecar JSON-RPC, host-core+ RPC, and the Plugin SDK are untouched; the desktop's observable behavior,+ defaults, and persisted data are unchanged.++## Consequences++- `pi-host` (R2) can compose `HostProcess + AgentSidecar + RuntimeService ++ AgentHost + RuntimeSupervisor` in plain Node; the RACP server binds to the+ module, never to Electron IPC.+- The restart policy, the turn lifecycle, and the transports now have unit+ tests that run without Electron (`packages/host-runtime/src/*.test.ts`).+- The desktop's source-contract tests that pinned `host-process.ts` and+ `agent-sidecar.ts` now read the package sources; the renderer-facing+ status and diagnosis assertions still read the Electron adapters.+- Local Electron main still runs its own prompt path through IPC. Moving the+ desktop onto `RuntimeService` for local sessions is a later,+ behavior-preserving step; it is not required for R2 and is not done here.+- The headless resolver deliberately supports less than the desktop:+ no prompt attachments, no plugin tools, no desktop MCP relay, no vendor+ OAuth. Those return typed errors rather than degrading silently.++## Alternatives considered++- **Extract only the transports and re-implement the turn lifecycle in+ `pi-host`.** Rejected: the lifecycle invariants are the hard part, and a+ second copy would drift from the desktop's.+- **Keep the modules in `apps/desktop/electron/main` and import them from+ `pi-host`.** Rejected: `packages/*` must not depend on desktop+ implementation code, and the modules would keep growing Electron imports.+- **Put the runtime into `packages/agent-host`.** Rejected: the module is the+ transport-free semantic core with no process or filesystem knowledge, and+ the RACP server and integrations depend on it staying that way.diff --cc docs/adr/0285-racp-ws-transport.mdindex 8a78ed61e,000000000..d44906148mode 100644,000000..100644--- a/docs/adr/0285-racp-ws-transport.md+++ b/docs/adr/0285-racp-ws-transport.md@@@ -1,88 -1,0 +1,88 @@@- # ADR 0284: `RACP-WS` transport in `packages/racp`++# ADR 0285: `RACP-WS` transport in `packages/racp`++- Status: Accepted for implementation+- Date: 2026-09-18+- Decision: D448- - Related: ADR 0205 (D373 / D374 / D375), ADR 0283 (D447),++- Related: ADR 0205 (D373 / D374 / D375), ADR 0284 (D447),+ `03-runtime/19-remote-agent-control-protocol.md` §3, §4, §8, §11.1, §14a,+ `05-security/02-remote-control-security.md` §3.4, §5.1++## Context++R0 froze the RACP contract as typebox schemas and R1 delivered the headless+Agent Host module. Nothing yet moved a JSON-RPC frame between two processes:+the module was only driven by Electron IPC. R2 needs the normative `RACP-WS`+binding on both sides of an SSH tunnel — a server that the `pi-host` bundle+binds on loopback and a client that Electron main runs — and it needs the+device-token pairing of security §3.4, which the security spec described but+no code implemented.++## Decision++1. **A new workspace package, `packages/racp`, holds both ends of the+ binding.** It depends on `shared`, `agent-host`, and `ws` only. The server+ core (`RacpServer`) and the client core (`RacpClient`) take an injected+ transport, so the same code runs over `ws` in production and over an+ in-memory pair in tests; `bindRacpWebSocket` and `wsClientTransport` are+ the `ws` adapters.+2. **The server is a thin catalog over the module.** Every operation in+ `RACP_OPERATIONS` is dispatched through the catalog's role rule; the+ session, turn, event, approval, and input operations call the Agent Host+ module directly; the remote-host profile (session catalog mutations,+ projects, workspace reads, terminals) goes through the `RacpHostOperations`+ interface that `pi-host` implements. The server never touches host-core+ RPC, a filesystem, or a pty (security §7).+3. **Header-profile authentication with Host-issued device tokens.** The+ upgrade request must carry `Authorization: Bearer`; a token in the URL, a+ non-loopback peer, a wrong path, a missing subprotocol, or a binary frame+ is refused before any RPC. Tokens are `pdt1.` (device) or `ppt1.` (pairing),+ stored as SHA-256 hashes, and compared in constant time. A pairing token is+ single-use and expiring; it authenticates an unprivileged connection that+ may only call `connection/pair`, which mints an `owner` device.+4. **Three catalog additions, all in the remote-host profile:**+ `connection/pair`, `project/register`, and `project/browse`. Six codes+ join the shared error registry: `PAIRING_FAILED`,+ `PAIRING_TOKEN_EXPIRED`, `CAPABILITY_UNAVAILABLE`, `REMOTE_PATH_NOT_FOUND`,+ `REMOTE_PATH_FORBIDDEN`, and the desktop-side connection codes+ `HOST_DISCONNECTED`, `HOST_BOOTSTRAP_FAILED`, `HOST_VERSION_MISMATCH`,+ `REMOTE_AUTH_FAILED`, `REMOTE_CONNECTION_FAILED`, `REMOTE_FORWARD_FAILED`.+ `connection/initialize` gains `server.hostId`. The binding details that the+ protocol left open are recorded in spec §14a.+5. **Reconnect is the client's, replay is the Host's.** The client reconnects+ with bounded backoff, rejects the dropped connection's in-flight calls with+ `HOST_DISCONNECTED`, and never re-sends them; it remembers the last durable+ cursor per session so the caller resubscribes with `after`. The Host+ answers with a replay, or with a snapshot and a `resyncReason`, exactly as+ the module already did for IPC. A dropped connection releases its+ subscriptions and terminal attachments and touches no turn.+6. **`StartTurnParams.input.userMessageId`** is threaded from+ `turn/start`'s `input.messageId` through the queue record to the runtime,+ so a remote client keeps its optimistic user row id (D288) the way the+ renderer does over IPC.++## Consequences++- `pi-host` composes `RacpServer` + `bindRacpWebSocket` over the module and- `RuntimeService` (ADR 0283); the desktop adapter composes `RacpClient` +++ `RuntimeService` (ADR 0284); the desktop adapter composes `RacpClient` ++ `wsClientTransport`.+- The conformance behaviors of spec §14 that do not need a machine boundary+ (handshake, authorization, idempotency, queue ordering, approval decisions,+ cursor replay, eviction, epoch change, slow clients, reconnect without+ duplicate execution) are tests in `packages/racp` and run without Electron.+- Attachments and the tool relay are advertised as unavailable+ (`attachments: false`, `toolRelay: false`) and their operations fail with+ `CAPABILITY_UNAVAILABLE`; they land with their own change.+- The server bind refuses a non-loopback address outright rather than+ offering a TLS path; a non-loopback deployment is a later decision.++## Alternatives considered++- **Run RACP inside Electron main first (development loopback endpoint).**+ Rejected for this change: the only scheduled client is the desktop, and the+ first server is `pi-host`; a desktop-side listener would add a network+ surface with no consumer.+- **Cookie profile alongside the header profile.** Rejected: it belongs to+ the unscheduled browser milestone (D375).+- **Static shared secret instead of pairing.** Rejected by security §3.2 and+ §3.4: a pairing token must be single-use and become a per-device credential+ that can be revoked on its own.diff --cc docs/adr/0286-remote-host-desktop-kernel.mdindex 9f40dc6f4,000000000..f92d63312mode 100644,000000..100644--- a/docs/adr/0286-remote-host-desktop-kernel.md+++ b/docs/adr/0286-remote-host-desktop-kernel.md@@@ -1,213 -1,0 +1,213 @@@- # ADR 0285: Remote-host desktop kernel++# ADR 0286: Remote-host desktop kernel++- Status: Accepted for implementation+- Date: 2026-09-18+- Decision: D449- - Related: ADR 0205 (D373 / D374 / D375), ADR 0284 (D448),++- Related: ADR 0205 (D373 / D374 / D375), ADR 0285 (D448),+ `03-runtime/19-remote-agent-control-protocol.md` §3.4, §4, §5, §7, §8,+ `05-security/02-remote-control-security.md` §3.4,+ `06-delivery/07-remote-control-rollout.md` §2 R2++## Context+- ADR 0284 delivered the `RACP-WS` transport and pairing on both ends. The++ADR 0285 delivered the `RACP-WS` transport and pairing on both ends. The+`pi-host` bundle now binds a real WebSocket server on loopback and speaks the+frozen contract; a `RacpClient` in `packages/racp` reaches it with header+authentication. What was still missing on the desktop side of R2 was the+kernel — the code that lets the renderer treat a remote session exactly the+way it treats a local one (spec §3.4). Without it, the transport can only be+observed from tests.++Three constraints shaped the kernel:++- The renderer must never learn the transport. Every existing per-session IPC+ call — 17 channels covering agent, session, tool approval, ask-tool, and+ plan resolution — has one call site in `apps/desktop/src/lib/api.ts` that+ cannot know whether the answer came from `host-core` or from a paired host.+- The frozen architecture pins `apps/desktop/electron/main/index.ts` at+ 1500 LOC (`scripts/check-architecture.mjs`). Every new module must live+ outside it; wiring must fit the existing composition root.+- The desktop cannot open a network listener of its own (security §7). All+ outbound flows go through the RACP client to a host the user paired with,+ and every registration is per-session so a lost host cannot silently+ hijack a local session id.++## Decision++The desktop-side R2 kernel is five modules and one boot hook, all under+`apps/desktop/electron/main/remote/` (module state) and+`apps/desktop/electron/main/bootstrap/` (boot state), and one new workspace+dependency (`@pi-desktop/racp`).++1. **A single interception seam: `backend-router.ts`.** The router is+ consulted from `ipc/register.ts`'s `handle()` wrapper; it returns the+ sentinel `ROUTE_LOCAL` when no `RemoteBackend` is registered for the call's+ session id, and the local handler runs unchanged. A session becomes remote+ only once its renderer-visible id (`remote:<hostKey>:<hostSessionId>`,+ mirroring `native-pi:`) has an explicit registration. This makes remote+ support byte-for-byte compatible when disabled and prevents accidental+ routing of a local id.++2. **A stateless per-request session id.** `sessionIdForCall` recovers the+ session from either the first positional argument, `first.sessionId`,+ `first.id` (`sessionGet` uses this shape), or a+ `<remoteSessionId>#racp-approval:<hostApprovalId>` requestId used by tool+ approval. This last one lets `toolResolvePermission` route without a+ correlation map: the router encodes the session into the id it hands the+ renderer and decodes it when the renderer echoes the id back.++3. **A transport-agnostic backend: `remote-backend.ts`.** One+ `createRemoteBackend({hostKey, client, ...})` instance serves every session+ of a paired host — the router registers it under each id. The backend+ translates 17 channels to RACP requests and reshapes the results back into+ the exact response shapes `apps/desktop/src/lib/api.ts` already returns for+ the local handler. Channels the remote profile does not cover+ (`agentSteer`, attachments, desktop-only settings) either return false from+ `handles()` or throw `CAPABILITY_UNAVAILABLE`, so those calls fall back to+ the local handler while the session's transcript stays remote.++4. **Two synthesis rules to reconcile schema mismatches without a+ round-trip.**+ - Tool-approval resolution has no session id in its wire payload, so the+ backend encodes `<remoteSessionId>#racp-approval:<hostApprovalId>` into+ the requestId (§ Decision 2) and decodes it back for `approval/respond`.+ - `plansResolve` returns `PlanResolutionResult` to the renderer, but RACP's+ `approval/respond` returns only `RacpApprovalResult`. The backend+ synthesizes a minimal `PlanProposal` from the request identity to dismiss+ the card optimistically; the authoritative snapshot arrives on the+ follow-up `session.changed` event and replaces the placeholder.++5. **A pure event bridge: `remote-event-bridge.ts`.** RACP events are+ translated into `IPC.event.agentMessage` / `IPC.event.sessionsChanged` for+ the renderer. Item/turn/tool payloads already carry a local `AgentEvent`+ in `payload.event` and forward verbatim under an `AgentEventEnvelope` keyed+ by the remote session id. `approval.requested` of kind `tool` becomes a+ local `tool_permission_request` with the encoded requestId; plan and goal+ approvals ride the following `planning_state` event and are dropped. An+ `onLifecycle` callback signals `session.created`/`archived` for the router+ without a second subscription to the same stream.++6. **A coordinator per paired host:+ `remote-host-connection.ts`.** `createRemoteHostConnection({hostKey,+ client, router, emit})` composes the backend, the bridge, and the router.+ Its `open()` sequence closes the create-race between listing sessions and+ receiving lifecycle events: attach listener → subscribe host scope →+ `session/list` → per-session subscribes. `close()` unregisters every+ session and drops internal state; it is idempotent and safe to call before+ `open()`.++7. **A `RemoteHostClient` seam with multi-listener `subscribe`.** The+ connection consumes `{request, subscribe}`. `packages/racp` exposes+ `RacpClient.onEvent` as a single-slot construction option, which is not+ enough for a bridge + resync watchdog + later features. `racp-remote-host-client.ts`+ is the only file in `electron/main/remote/` that imports+ `@pi-desktop/racp`; it wraps the client, fans out its callback to every+ `subscribe()` listener, and swallows listener throws so a bad subscriber+ cannot silence the others.++8. **Encrypted-at-rest registry: `remote-host-registry.ts`.** Paired hosts+ live in `<dataDir>/remote-hosts.json`. Device tokens are encrypted with+ Electron's `safeStorage` before write and decrypted on read; a stolen file+ without keychain access reveals only URL and label. The registry is+ injected with an `EncryptionPort` (isAvailable / encryptString /+ decryptString) so Node-side tests supply a fake without pulling in+ Electron. `upsert` refuses to write when the keychain is unavailable;+ `list` drops any record it cannot decrypt rather than surfacing an empty+ token that would auth-fail downstream.++9. **Boot hook: `bootstrap/remote-hosts.ts`.** `createRemoteHostsBoot(...)`+ reads the registry, opens one adapter + one connection per host, and+ returns `{open, closeAll}`. Sequential open — a host's failure is logged+ and skipped, not fatal. An empty registry (the default install) is a full+ no-op: nothing connects, no backend registers, every renderer call keeps+ hitting the local handler byte-for-byte. `bootstrap/startup.ts` calls+ `open()` in the background so a slow host never delays the first window;+ `bootstrap/shutdown.ts` calls `closeAll()` from the existing shutdown+ promise so paired sockets are drained before host-core is torn down. A+ single module-level `activeRemoteHostsBoot` handle bridges startup and+ shutdown without expanding `index.ts` past its 1500-LOC ceiling.++## Invariants the kernel keeps++- **Renderer transport-agnosticism.** The renderer's `api.ts` code does not+ mention "remote". Its session ids may be namespaced; every response shape it+ parses is the local one.+- **Router-off default.** With no `RemoteBackend` registered, `route()`+ returns `ROUTE_LOCAL` for every call and the existing handler runs+ unchanged. Adding the kernel to a build without pairing is a zero-behavior+ change.+- **Least privilege at rest.** No plaintext device token ever touches disk.+ A `safeStorage` unavailable environment cannot write a token; it can still+ read what was already written when that platform was available.+- **Bounded shutdown.** `closeAll` closes every paired socket inside the same+ `Promise.allSettled` block that handles plugin, sidecar, and MCP disposals,+ before `host-core` is disposed, so in-flight remote turns can send their+ abort over a live socket.++## Out of scope++The kernel is complete for a paired host to answer renderer calls and stream+events. What is scheduled for later stages of R2:++- **Pairing UX (renderer + IPC).** Settings surfaces to enter a URL and+ pairing token, exchange it, and store the device token. The registry API+ is ready for this; the surface is not.+- **SSH bootstrap (Stage 4).** A supervisor that detects system `ssh`,- downloads the `pi-host-bundle` (verified by SHA-256 from ADR 0284's++ downloads the `pi-host-bundle` (verified by SHA-256 from ADR 0285's+ release pipeline), starts the remote binary, and opens the `-L` tunnel.+ Every paired host today assumes the loopback URL already exists.+- **Terminal work-panel client (Stage 5).** RACP terminal events are dropped+ by the event bridge; the work-panel session client will consume them.+- **Reverse tool relay (Stage 6).** A `RelayToolPort` bridge that lets the+ agent host run local desktop tools against a remote session. Belongs on the+ agent-host and pi-host, not on `packages/racp`.+- **Resync watchdog.** `resync.required` events are dropped today; the+ connection layer will eventually rebuild subscriptions from the last+ cursor per session (`RacpClient.cursorFor`).+- **Multi-listener contract.** `subscribe()` is used by exactly one consumer+ today (the event bridge); Stage 3b's resync watchdog will be the second.++## Alternatives considered++- **Route from each per-domain IPC handler.** Every one of 17 handlers would+ need to know about "remote" and duplicate the same dispatch. Rejected:+ God-modules would grow, and any new channel would need to be wired in twice.+- **Bake remote knowledge into the renderer.** A `remote:` prefix visible to+ the renderer forces `api.ts` to branch, and every store slice ends up+ aware of the transport. Rejected by spec §3.4.+- **Have the connection layer own its own RacpClient construction.** It would+ couple the coordinator to `packages/racp` and prevent unit tests from+ running without a real client. Rejected in favour of the injected+ `RemoteHostClient` seam.+- **A single-listener `RemoteHostClient`.** Simpler, but forces the resync+ watchdog and the event bridge to share the same callback. Rejected: their+ concerns are independent and their subscriptions should be too.+- **Plain-text registry.** Simpler read/write, but a compromised backup would+ hand attackers a device token that authenticates against a real `pi-host`.+ Rejected by security §3.4.++## Testing++Every module has a `node --test` fixture that exercises the seam in isolation+(fake RACP client, fake encryption, fake router). The RACP adapter runs+against the real in-memory harness (`@pi-desktop/racp/test-harness`), so its+fan-out and lifecycle contracts are checked against the same client the+production factory builds. The full desktop suite runs 2120+ tests with the+kernel on and every one passes; no `test:e2e:*` scenario is scheduled for the+kernel alone because it is dead code until pairing lands.++## Consequences++- The desktop can host a paired remote `pi-host` today; adding a URL and+ device token to `<dataDir>/remote-hosts.json` (encrypted-at-rest through+ `safeStorage`) makes the kernel connect, register sessions, and stream+ events into the existing renderer, no other flag or setting required.+- `apps/desktop` now depends on `@pi-desktop/racp`, and the racp package+ publishes a `./test-harness` export subpath. Both changes are additive.+- `apps/desktop/electron/main/index.ts` stays at exactly 1500 LOC. The+ startup/shutdown bridge is a module-level handle inside+ `bootstrap/remote-hosts.ts` — small, contained, and easy to remove once+ R2b lets the wiring live inside a broader remote-hosts service object.+- Any Stage 4–7 work (SSH bootstrap, terminal work-panel client, reverse+ tool relay, pairing UX) plugs into existing seams — the router, the event+ bridge, the registry — and does not need to revisit the transport layer.diff --cc docs/adr/README.mdindex cfc7b2a09,2618e0585..52a34bcc4--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -309,7 -309,5 +309,8 @@@ Each ADR includes| 0280 | [Plugin-owned UI localizes from the host locale](0280-plugin-owned-ui-localizes-from-host-locale.md) | Accepted (amends ADR 0267; ADR 0159) || 0281 | [Host speech capability](0281-host-speech-capability.md) | Accepted for implementation (amends ADR 0257) || 0282 | [Retry and right-size the compaction summary before retained-tail recovery](0282-compaction-summary-retry-and-sizing.md) | Accepted (amends ADR 0049; issue #543) |- | 0283 | [Headless runtime boundary in `packages/host-runtime`](0283-headless-runtime-boundary.md) | Accepted for implementation (D447; ADR 0205 R2 prerequisite) |- | 0284 | [`RACP-WS` transport in `packages/racp`](0284-racp-ws-transport.md) | Accepted for implementation (D448; ADR 0205 R2) |- | 0285 | [Remote-host desktop kernel](0285-remote-host-desktop-kernel.md) | Accepted for implementation (D449; ADR 0205 R2) |+ | 0283 | [Remote MCP server OAuth 2.1 authentication](0283-remote-mcp-oauth.md) | Accepted |++| 0284 | [Headless runtime boundary in `packages/host-runtime`](0284-headless-runtime-boundary.md) | Accepted for implementation (D447; ADR 0205 R2 prerequisite) |++| 0285 | [`RACP-WS` transport in `packages/racp`](0285-racp-ws-transport.md) | Accepted for implementation (D448; ADR 0205 R2) |++| 0286 | [Remote-host desktop kernel](0286-remote-host-desktop-kernel.md) | Accepted for implementation (D449; ADR 0205 R2) || turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |diff --cc docs/spec/03-runtime/07-process-model.mdindex c395f889f,d3ae914f6..4147617e1--- a/docs/spec/03-runtime/07-process-model.md+++ b/docs/spec/03-runtime/07-process-model.md@@@ -123,9 -123,7 +123,9 @@@ start its local service. Windows 11 ARMthe operating system's x64 emulation; native Windows ARM64 artifacts are notcurrently published.-Supervision parameters (implemented in Electron main):+Supervision parameters (the transports, restart policy, and turn lifecycle are- `packages/host-runtime`, ADR 0283; Electron main adapts them and owns the++`packages/host-runtime`, ADR 0284; Electron main adapts them and owns the+renderer-facing status):- Child exit rejects all in-flight RPCs for that child immediately (no 130s timeout wait).- An NDJSON request line over 64 MiB is drained and answered with `LIMIT_EXCEEDED`; it does not end the stdin reader (ADR 0216). Electron rejects the same size before writing stdin (ADR 0217).diff --cc docs/spec/03-runtime/08-error-codes.mdindex f2af47e88,b74a86e98..d7b7ccca1--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@@ -274,29 -274,6 +274,29 @@@ carries a marker naming which end survithe bounded window in sibling result fields(see [16-tool-result-limits](16-tool-result-limits.md)).+### 3.8 Remote control (RACP-WS / SSH bootstrap)++Emitted by the desktop's remote-host client and the `pi-host` server when a+session lives on a paired remote machine driven over `RACP-WS`+(see [19-remote-agent-control-protocol](19-remote-agent-control-protocol.md),+[../05-security/02-remote-control-security](../05-security/02-remote-control-security.md),- ADR 0284). The renderer never sees the local/remote split beyond a badge; these++ADR 0285). The renderer never sees the local/remote split beyond a badge; these+codes surface through the same error object as any other call.++| code | retriable | meaning |+|---|---|---|+| `HOST_DISCONNECTED` | yes | the remote host connection dropped; in-flight calls are rejected and the client reconnects and resubscribes by cursor |+| `HOST_BOOTSTRAP_FAILED` | no | provisioning the remote `pi-host` over SSH failed (download, checksum mismatch, or `install.sh`); `details.reason` names the stage |+| `HOST_VERSION_MISMATCH` | no | the remote `pi-host` version does not match the desktop; the desktop refuses to drive an incompatible host |+| `REMOTE_AUTH_FAILED` | no | the device or pairing token was rejected on the RACP-WS upgrade |+| `REMOTE_CONNECTION_FAILED` | yes | the RACP-WS transport could not connect (non-loopback URL, refused socket) |+| `REMOTE_FORWARD_FAILED` | yes | the SSH loopback port forward could not be established |+| `REMOTE_PATH_NOT_FOUND` | no | a remote project/workspace path does not exist on the host |+| `REMOTE_PATH_FORBIDDEN` | no | a remote path is outside the host's permitted roots |+| `PAIRING_FAILED` | no | `connection/pair` could not mint a device credential |+| `PAIRING_TOKEN_EXPIRED` | no | the single-use pairing token expired before pairing completed |+| `CAPABILITY_UNAVAILABLE` | no | an operation was requested for a capability the host advertised as unavailable (e.g. attachments, tool relay) |+## 4. Mapping rules### Host RPC numeric → AppError.codediff --cc docs/spec/06-delivery/07-remote-control-rollout.mdindex 3cc3d8ec4,63e5d0ca5..f1c8b7e8f--- a/docs/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/spec/06-delivery/07-remote-control-rollout.md@@@ -104,21 -104,6 +104,21 @@@ match `electron/main/index.ts` by sourcDeliver the first remote topology (`02-architecture/05-remote-agent-control.md`§5.2): the desktop as Remote Client of a headless Host on another machine.+R2 lands in two ordered slices so the desktop-side kernel can ship, be+tested, and stay dead code until the full topology is ready:+- - **R2a — Desktop kernel (delivered, ADR 0285).** The single interception++- **R2a — Desktop kernel (delivered, ADR 0286).** The single interception+ seam, the transport-agnostic backend, the event bridge, the coordinator, an+ encrypted-at-rest registry, and the boot hook. With an empty registry+ (default install) the kernel is a full no-op; the router has no remote+ backends, every renderer call still hits the local handler byte-for-byte.+ Every subsystem has a `node --test` fixture that exercises it against a+ fake — or, for the RACP adapter, against the real in-memory harness in+ `@pi-desktop/racp/test-harness`.+- **R2b — Pairing, SSH bootstrap, terminal, and reverse tool relay.** The+ remaining bullets below. R2's exit criteria stay unchanged and land with+ R2b; R2a alone is not user-visible and does not attempt them.+Deliverables:- the `pi-host` bundle: the module, the Node pi sidecar, and the platform's@@@ -417,18 -402,7 +417,18 @@@ Recorded on the `feat/remote-agent-hostgraceful stop.- R1 open: a runtime-level per-turn permission ceiling (a capped turncurrently fails closed in the bridge).- - R2 started (2026-09-18, D447 / ADR 0283): `packages/host-runtime` holds the-- R2 and later: not started.++- R2 started (2026-09-18, D447 / ADR 0284): `packages/host-runtime` holds the+ Electron-independent runtime layer — the host-core and sidecar stdio+ transports, the restart supervisor, `RuntimeService` (the module's+ `RuntimePort` with the durable turn lifecycle), transcript persistence, a+ headless launch resolver, and approved Plan/Goal dispatch — and Electron+ main runs on it through thin adapters.- - R2 (2026-09-18, D448 / ADR 0284): `packages/racp` holds the `RACP-WS`++- R2 (2026-09-18, D448 / ADR 0285): `packages/racp` holds the `RACP-WS`+ server and client cores, the `ws` binding on loopback, and device-token+ pairing; handshake, authorization, idempotency, queue order, approvals,+ cursor replay, eviction, epoch change, slow clients, and reconnect without+ duplicate execution are package tests. The `pi-host` bundle, the SSH+ bootstrap, and the desktop adapter are not started.## 8. Amendment historydiff --cc docs/spec/08-meta/decisions-log.mdindex a5c9c0c4b,515fbc8db..be71d299b--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@@ -22,8 -22,6 +22,8 @@@ This log freezes previously open questi| D010 | First release platform | **macOS arm64 only** | Focus acceptance and packaging || D373 | Remote Agent Control host boundary | *(amended by D374 and D375)* **Remote control (post-MVP) runs through a logical Agent Host that owns Sessions, Turns, event cursors, approvals, attachments, workspace policy, and crash recovery; a production Gateway owns identity, routing, rate limits, revocation, and audit, and the Agent Host connects outbound. The existing Electron IPC, `host.proxy`, and host-core stdio boundaries are never exposed.** | A remote surface needs its own boundary rather than a tunnel into local IPC or the host-core stdio contract (ADR 0205, E2E-221 through E2E-230) || D374 | Remote Agent Control v1 target amendments | **Amend D373 / ADR 0205: `RACP-WS` is the only normative v1 binding (`RACP-HTTP` is the browser profile, `RACP-GRPC` is reserved); typebox in `packages/shared` is the single contract source; the headless `packages/agent-host` module is the first deliverable and is shared by desktop IPC, local MCP, and RACP; cursors are `{ epoch, sequence }` with ephemeral deltas; the turn queue moves into the Host; host-core exposes `permissions.pending`; remote approvals carry the full local decision vocabulary under a default `ask` ceiling; browser clients use a cookie profile; the first deployment is single-tenant.** | Reviewing the D373 draft against the shipped desktop found the remote approval vocabulary narrower than the local contracts, pending requests held as connection state, per-token deltas exhausting the replay window, and more bindings than v1 can carry (ADR 0205) |- | D447 | Headless runtime boundary | **Amend ADR 0205 rollout R2 prerequisites (ADR 0283): the Electron-independent runtime layer under the Agent Host module lives in `packages/host-runtime` — the host-core and sidecar stdio transports, the restart supervisor (process-model §4 policy), the durable turn lifecycle (`RuntimeService` as the module's `RuntimePort`: `session.beginTurn` → user row → prompt → `session.endTurn`, abort lock, stale-terminal guard, single-flight finalization), transcript persistence with the D299 checkpoint, a headless launch resolver over host-core's own registries, approved Plan/Goal dispatch (D189), and the host-core adapters for `SessionPort` / `QueueStore` / `permissions.pending`. Electron main keeps thin adapters (binary and bundle locations, `ELECTRON_RUN_AS_NODE`, redacted stderr, schema/glibc diagnoses, renderer status pushes) and its own local prompt path. `TurnStartRequest` gains an optional `userMessageId`. No IPC, sidecar, host-core, Plugin SDK, default, or persisted-data change.** | `pi-host` must run the same lifecycle invariants as the desktop without Electron; a second implementation of abort locks, stale terminal events, and queue release after durable settlement would drift from the one the desktop already fixed |- | D448 | RACP-WS transport and device pairing | **Amend ADR 0205 rollout R2 (ADR 0284): `packages/racp` holds both ends of the normative `RACP-WS` binding. `RacpServer` dispatches every catalog operation through its role rule onto the Agent Host module and a `RacpHostOperations` interface the Host implements; `RacpClient` correlates requests, answers server-initiated requests, tracks the last durable cursor per session, reconnects with bounded backoff, and fails the dropped connection's in-flight calls with `HOST_DISCONNECTED` instead of re-sending them. Authentication is the header profile with Host-issued `pdt1.` device tokens and single-use, expiring `ppt1.` pairing tokens (hashed, constant-time compared; never in a URL); `connection/pair` mints an `owner` device. `connection/pair`, `project/register`, `project/browse`, `server.hostId`, the `events/closed` notification, and the codes `PAIRING_FAILED`, `PAIRING_TOKEN_EXPIRED`, `CAPABILITY_UNAVAILABLE`, `REMOTE_PATH_NOT_FOUND`, `REMOTE_PATH_FORBIDDEN`, `HOST_DISCONNECTED`, `HOST_BOOTSTRAP_FAILED`, `HOST_VERSION_MISMATCH`, `REMOTE_AUTH_FAILED`, `REMOTE_CONNECTION_FAILED`, `REMOTE_FORWARD_FAILED` join the contract (spec §14a). The bind refuses non-loopback addresses; attachments and the tool relay are advertised unavailable.** | The SSH-tunnel topology needs a server `pi-host` can bind and a client the desktop can run, with the pairing the security spec describes; the conformance behaviors that need no machine boundary become package tests |++| D447 | Headless runtime boundary | **Amend ADR 0205 rollout R2 prerequisites (ADR 0284): the Electron-independent runtime layer under the Agent Host module lives in `packages/host-runtime` — the host-core and sidecar stdio transports, the restart supervisor (process-model §4 policy), the durable turn lifecycle (`RuntimeService` as the module's `RuntimePort`: `session.beginTurn` → user row → prompt → `session.endTurn`, abort lock, stale-terminal guard, single-flight finalization), transcript persistence with the D299 checkpoint, a headless launch resolver over host-core's own registries, approved Plan/Goal dispatch (D189), and the host-core adapters for `SessionPort` / `QueueStore` / `permissions.pending`. Electron main keeps thin adapters (binary and bundle locations, `ELECTRON_RUN_AS_NODE`, redacted stderr, schema/glibc diagnoses, renderer status pushes) and its own local prompt path. `TurnStartRequest` gains an optional `userMessageId`. No IPC, sidecar, host-core, Plugin SDK, default, or persisted-data change.** | `pi-host` must run the same lifecycle invariants as the desktop without Electron; a second implementation of abort locks, stale terminal events, and queue release after durable settlement would drift from the one the desktop already fixed |++| D448 | RACP-WS transport and device pairing | **Amend ADR 0205 rollout R2 (ADR 0285): `packages/racp` holds both ends of the normative `RACP-WS` binding. `RacpServer` dispatches every catalog operation through its role rule onto the Agent Host module and a `RacpHostOperations` interface the Host implements; `RacpClient` correlates requests, answers server-initiated requests, tracks the last durable cursor per session, reconnects with bounded backoff, and fails the dropped connection's in-flight calls with `HOST_DISCONNECTED` instead of re-sending them. Authentication is the header profile with Host-issued `pdt1.` device tokens and single-use, expiring `ppt1.` pairing tokens (hashed, constant-time compared; never in a URL); `connection/pair` mints an `owner` device. `connection/pair`, `project/register`, `project/browse`, `server.hostId`, the `events/closed` notification, and the codes `PAIRING_FAILED`, `PAIRING_TOKEN_EXPIRED`, `CAPABILITY_UNAVAILABLE`, `REMOTE_PATH_NOT_FOUND`, `REMOTE_PATH_FORBIDDEN`, `HOST_DISCONNECTED`, `HOST_BOOTSTRAP_FAILED`, `HOST_VERSION_MISMATCH`, `REMOTE_AUTH_FAILED`, `REMOTE_CONNECTION_FAILED`, `REMOTE_FORWARD_FAILED` join the contract (spec §14a). The bind refuses non-loopback addresses; attachments and the tool relay are advertised unavailable.** | The SSH-tunnel topology needs a server `pi-host` can bind and a client the desktop can run, with the pairing the security spec describes; the conformance behaviors that need no machine boundary become package tests |## B. Secondary implementation defaultsdiff --cc docs/zh-CN/adr/index.mdindex 0ce47eac3,982b43674..a008fd57b--- a/docs/zh-CN/adr/index.md+++ b/docs/zh-CN/adr/index.md@@@ -291,8 -291,7 +291,9 @@@ ADR 记录那些不应被静默改变�| 0279 | [可恢复的子代理委托](/adr/0279-resumable-subagent-delegations) | 已接受待实现(修订 ADR 0062;ADR 0089;issue #513) || 0280 | [插件自有界面按宿主语言自行本地化](/adr/0280-plugin-owned-ui-localizes-from-host-locale) | 已接受(修订 ADR 0267;ADR 0159) || 0282 | [压缩摘要先重试并按实际提示大小预检,再回退保留尾部](/adr/0282-compaction-summary-retry-and-sizing) | 已接受(修订 ADR 0049;issue #543) |- | 0283 | [`packages/host-runtime` 的无头运行时边界](/adr/0283-headless-runtime-boundary) | 已接受(实施中)(D447;ADR 0205 R2 前置) |- | 0284 | [`packages/racp` 的 `RACP-WS` 传输](/adr/0284-racp-ws-transport) | 已接受(实施中)(D448;ADR 0205 R2) |+ | 0283 | [远程 MCP 服务端 OAuth 2.1 认证](/adr/0283-remote-mcp-oauth) | 已接受 |++| 0284 | [`packages/host-runtime` 的无头运行时边界](/adr/0284-headless-runtime-boundary) | 已接受(实施中)(D447;ADR 0205 R2 前置) |++| 0285 | [`packages/racp` 的 `RACP-WS` 传输](/adr/0285-racp-ws-transport) | 已接受(实施中)(D448;ADR 0205 R2) || turn-process-and-thinking-display | [回合过程与思考展示](/adr/turn-process-and-thinking-display) | 已接受 |## 什么时候看 ADRdiff --cc docs/zh-CN/spec/03-runtime/07-process-model.mdindex a08c4841d,80444a43d..c488a0549--- a/docs/zh-CN/spec/03-runtime/07-process-model.md+++ b/docs/zh-CN/spec/03-runtime/07-process-model.md@@@ -97,7 -97,7 +97,7 @@@ Windows 安装包目标为 x64。Window系统通过操作系统的 x64 模拟运行该 x64 安装包;目前不发布原生 Windows ARM64工件。- 监管参数(传输、重启策略与回合生命周期位于 `packages/host-runtime`,ADR 0283;Electron main 适配它们并负责面向渲染层的状态):-监管参数(在Electron main中实现):++监管参数(传输、重启策略与回合生命周期位于 `packages/host-runtime`,ADR 0284;Electron main 适配它们并负责面向渲染层的状态):- 子进程退出立即拒绝该子进程的所有正在进行的 RPC(无 130 秒超时等待)。- 超过 64 MiB 的 NDJSON 请求行以 `LIMIT_EXCEEDED` 应答,不结束 stdin 读取器(ADR 0216)。Electron 在写入 stdin 前拒绝同样大小的载荷(ADR 0217)。diff --cc docs/zh-CN/spec/03-runtime/08-error-codes.mdindex f8b264d92,cfaeacf51..2925f0940--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@@ -270,29 -270,6 +270,29 @@@ reveal 不并入任何行,必须重�同级结果字段中的有界窗口(请参阅 [16-工具-结果-限制](/zh-CN/spec/03-runtime/16-tool-result-limits))。+### 3.8 远程控制(RACP-WS / SSH 引导)++当会话位于经 `RACP-WS` 驱动的已配对远程主机上时,由桌面端的远程主机客户端与+`pi-host` 服务端发出(参见+[19-远程代理控制协议](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol)、+[../05-security/02-remote-control-security](/zh-CN/spec/05-security/02-remote-control-security)、- ADR 0284)。渲染进程除了一个标识徽章外看不到本地/远程之分;这些码通过与其他调用++ADR 0285)。渲染进程除了一个标识徽章外看不到本地/远程之分;这些码通过与其他调用+相同的错误对象浮现。++| 码 | 可重试 | 含义 |+|---|---|---|+| `HOST_DISCONNECTED` | 是 | 远程主机连接断开;进行中的调用被拒绝,客户端按游标重连并重新订阅 |+| `HOST_BOOTSTRAP_FAILED` | 否 | 经 SSH 配置远程 `pi-host` 失败(下载、校验和不匹配或 `install.sh`);`details.reason` 指明阶段 |+| `HOST_VERSION_MISMATCH` | 否 | 远程 `pi-host` 版本与桌面不匹配;桌面拒绝驱动不兼容的主机 |+| `REMOTE_AUTH_FAILED` | 否 | 设备或配对令牌在 RACP-WS 升级时被拒 |+| `REMOTE_CONNECTION_FAILED` | 是 | RACP-WS 传输无法连接(非回环 URL、套接字被拒) |+| `REMOTE_FORWARD_FAILED` | 是 | 无法建立 SSH 回环端口转发 |+| `REMOTE_PATH_NOT_FOUND` | 否 | 远程项目/工作区路径在主机上不存在 |+| `REMOTE_PATH_FORBIDDEN` | 否 | 远程路径在主机允许的根之外 |+| `PAIRING_FAILED` | 否 | `connection/pair` 无法铸造设备凭据 |+| `PAIRING_TOKEN_EXPIRED` | 否 | 一次性配对令牌在配对完成前已过期 |+| `CAPABILITY_UNAVAILABLE` | 否 | 请求的操作对应主机声明为不可用的能力(如附件、工具中继) |+## 4. 映射规则### 主机 RPC 数字 → AppError.codediff --cc docs/zh-CN/spec/06-delivery/07-remote-control-rollout.mdindex a49a063b0,198cc6764..47fbe9f5c--- a/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md@@@ -32,15 -32,7 +32,15 @@@ Linux 或 WSL 机器上的项目,即loopback RACP-WS 端点。抽取在在途版本发布后开始,`permissions.pending`、Host 队列和模块抽取各自独立提交,因为仓库存在并发会话,且 54 个测试按源码模式匹配 `electron/main/index.ts`,需要重新指向。-- R2:SSH 隧道上的远端 Host。交付 `pi-host` 包(模块、Node pi sidecar 与平台+- R2:SSH 隧道上的远端 Host。分两个有序切片交付,桌面侧内核先落地并保持关闭态:- - R2a — 桌面内核(已交付,见 ADR 0285):backend-router seam、传输无关的 remote-backend、++ - R2a — 桌面内核(已交付,见 ADR 0286):backend-router seam、传输无关的 remote-backend、+ event bridge、per-host coordinator、safeStorage 加密的 remote-host 注册表以及启动引导。+ 默认注册表为空即完整 no-op:router 无远程 backend,renderer 每次调用仍逐字节走本地+ handler。`node --test` 用 fake 或真实的 `@pi-desktop/racp/test-harness` 覆盖每个模块。+ - R2b — 配对、SSH 引导、终端、反向工具中继。R2 的出口条件保持不变,随 R2b 一并达成;+ R2a 单独不面向用户,且不尝试完成这些条件。++ 交付项:`pi-host` 包(模块、Node pi sidecar 与平台host-core 二进制,与桌面同版本,只绑定 loopback,由桌面经 SSH 上传的引导脚本从GitHub Releases 下载并校验公布的 SHA-256,再经该 SSH 会话启动并配对);位于 `lib/api.ts` 之下的桌面 RACP 客户端适配层,使远程会话像本地一样渲染;转发端口上的 `RACP-WS` header profile,遵守安全规格的 loopback 规则@@@ -146,8 -138,7 +146,8 @@@ runbook 写明 feature flag、配对撤- R1 已交付:renderer 的内存 prompt 队列已退役;composer 经 `agent/queue/push` 推入,镜像 `agent/event/queueChanged`,“立即发送”即 `turn/prioritize` 加优雅停止。- R1 未完成:运行时级别的逐回合权限上限(当前被限制的回合在桥接层直接拒绝)。- - R2 已开始(2026-09-18,D447 / ADR 0283):`packages/host-runtime` 承载与 Electron 无关的运行时层 —— host-core 与 sidecar 的 stdio 传输、重启监督器、`RuntimeService`(模块的 `RuntimePort`,含持久回合生命周期)、转录持久化、无头启动解析器与已批准 Plan/Goal 的派发 —— Electron main 通过薄适配层运行其上。- - R2(2026-09-18,D448 / ADR 0284):`packages/racp` 承载 `RACP-WS` 服务端与客户端核心、回环上的 `ws` 绑定与设备令牌配对;握手、鉴权、幂等、队列顺序、审批、游标重放、驱逐、epoch 变更、慢客户端与不重复执行的重连都是包内测试。`pi-host` 包、SSH 引导与桌面适配器尚未开始。-- R2 及之后:尚未开始。++- R2 已开始(2026-09-18,D447 / ADR 0284):`packages/host-runtime` 承载与 Electron 无关的运行时层 —— host-core 与 sidecar 的 stdio 传输、重启监督器、`RuntimeService`(模块的 `RuntimePort`,含持久回合生命周期)、转录持久化、无头启动解析器与已批准 Plan/Goal 的派发 —— Electron main 通过薄适配层运行其上。++- R2(2026-09-18,D448 / ADR 0285):`packages/racp` 承载 `RACP-WS` 服务端与客户端核心、回环上的 `ws` 绑定与设备令牌配对;握手、鉴权、幂等、队列顺序、审批、游标重放、驱逐、epoch 变更、慢客户端与不重复执行的重连都是包内测试。`pi-host` 包、SSH 引导与桌面适配器尚未开始。## 8. 修订记录diff --cc docs/zh-CN/spec/08-meta/decisions-log.mdindex a7f5fd657,1874be648..7bd47a623--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@@ -25,8 -25,6 +25,8 @@@| D010 | 首个发布平台 | **仅限 macOS arm64** | 重点验收及包装 || D373 | 远程 Agent 控制的 Host 边界 | *(由 D374 与 D375 修订)* **远程控制(MVP 之后)经由一个逻辑 Agent Host 运行,它拥有 Sessions、Turns、事件游标、审批、附件、工作区策略与崩溃恢复;生产 Gateway 拥有身份、路由、限流、吊销与审计,Agent Host 向外连接。现有 Electron IPC、`host.proxy` 与 host-core stdio 边界永不暴露。** | 远程表面需要自己的边界,而不是通往本地 IPC 或 host-core stdio 契约的隧道(ADR 0205,E2E-221 至 E2E-230) || D374 | 远程 Agent 控制 v1 目标修订 | **修订 D373 / ADR 0205:`RACP-WS` 是 v1 唯一规范绑定(`RACP-HTTP` 为浏览器 profile,`RACP-GRPC` 保留);`packages/shared` 中的 typebox 是唯一契约来源;无头的 `packages/agent-host` 模块是首个交付物,桌面 IPC、本地 MCP 与 RACP 共同调用;游标为 `{ epoch, sequence }` 且增量为临时数据;回合队列移入 Host;host-core 暴露 `permissions.pending`;远程审批携带完整本地决策词汇并默认 `ask` 上限;浏览器客户端使用 cookie profile;首个部署为单租户。** | 对照已交付桌面审查 D373 草案发现远程审批词汇比本地契约窄、待处理请求被当作连接状态、逐 token 增量会耗尽重放窗口、绑定数量超过 v1 承载能力(ADR 0205) |- | D447 | 无头运行时边界 | **修订 ADR 0205 里程碑 R2 的前置条件(ADR 0283):Agent Host 模块之下与 Electron 无关的运行时层放入 `packages/host-runtime` —— host-core 与 sidecar 的 stdio 传输、重启监督器(进程模型 §4 的策略)、持久回合生命周期(`RuntimeService` 作为模块的 `RuntimePort`:`session.beginTurn` → 用户行 → prompt → `session.endTurn`、中止锁、过期终态事件守卫、单飞终结)、带 D299 检查点的转录持久化、基于 host-core 自身注册表的无头启动解析器、已批准 Plan/Goal 的派发(D189),以及 `SessionPort` / `QueueStore` / `permissions.pending` 的 host-core 适配器。Electron main 只保留薄适配层(二进制与资源位置、`ELECTRON_RUN_AS_NODE`、脱敏 stderr、schema/glibc 诊断、渲染层状态推送)以及自己的本地 prompt 路径。`TurnStartRequest` 新增可选 `userMessageId`。不改 IPC、sidecar、host-core、插件 SDK、默认值或持久化数据。** | `pi-host` 必须在没有 Electron 的情况下运行与桌面相同的生命周期不变量;第二份中止锁、过期终态事件与持久落库后释放队列的实现会与桌面已修好的那份漂移 |- | D448 | RACP-WS 传输与设备配对 | **修订 ADR 0205 里程碑 R2(ADR 0284):`packages/racp` 同时承载规范绑定 `RACP-WS` 的两端。`RacpServer` 按目录的角色规则把每个操作分发到 Agent Host 模块与 Host 实现的 `RacpHostOperations` 接口;`RacpClient` 关联请求、应答服务端发起的请求、按会话记录最后的持久游标、以有界退避重连,并让断开连接上未完成的调用以 `HOST_DISCONNECTED` 失败而不是重发。认证采用 header profile:Host 签发的 `pdt1.` 设备令牌与一次性、有时限的 `ppt1.` 配对令牌(散列存储、常量时间比较、绝不出现在 URL 中);`connection/pair` 铸造 `owner` 设备。`connection/pair`、`project/register`、`project/browse`、`server.hostId`、`events/closed` 通知,以及错误码 `PAIRING_FAILED`、`PAIRING_TOKEN_EXPIRED`、`CAPABILITY_UNAVAILABLE`、`REMOTE_PATH_NOT_FOUND`、`REMOTE_PATH_FORBIDDEN`、`HOST_DISCONNECTED`、`HOST_BOOTSTRAP_FAILED`、`HOST_VERSION_MISMATCH`、`REMOTE_AUTH_FAILED`、`REMOTE_CONNECTION_FAILED`、`REMOTE_FORWARD_FAILED` 进入契约(规格 §14a)。绑定拒绝非回环地址;附件与工具中继宣告为不可用。** | SSH 隧道拓扑需要 `pi-host` 能绑定的服务端和桌面能运行的客户端,以及安全规格描述的配对;不需要机器边界的一致性行为成为包内测试 |++| D447 | 无头运行时边界 | **修订 ADR 0205 里程碑 R2 的前置条件(ADR 0284):Agent Host 模块之下与 Electron 无关的运行时层放入 `packages/host-runtime` —— host-core 与 sidecar 的 stdio 传输、重启监督器(进程模型 §4 的策略)、持久回合生命周期(`RuntimeService` 作为模块的 `RuntimePort`:`session.beginTurn` → 用户行 → prompt → `session.endTurn`、中止锁、过期终态事件守卫、单飞终结)、带 D299 检查点的转录持久化、基于 host-core 自身注册表的无头启动解析器、已批准 Plan/Goal 的派发(D189),以及 `SessionPort` / `QueueStore` / `permissions.pending` 的 host-core 适配器。Electron main 只保留薄适配层(二进制与资源位置、`ELECTRON_RUN_AS_NODE`、脱敏 stderr、schema/glibc 诊断、渲染层状态推送)以及自己的本地 prompt 路径。`TurnStartRequest` 新增可选 `userMessageId`。不改 IPC、sidecar、host-core、插件 SDK、默认值或持久化数据。** | `pi-host` 必须在没有 Electron 的情况下运行与桌面相同的生命周期不变量;第二份中止锁、过期终态事件与持久落库后释放队列的实现会与桌面已修好的那份漂移 |++| D448 | RACP-WS 传输与设备配对 | **修订 ADR 0205 里程碑 R2(ADR 0285):`packages/racp` 同时承载规范绑定 `RACP-WS` 的两端。`RacpServer` 按目录的角色规则把每个操作分发到 Agent Host 模块与 Host 实现的 `RacpHostOperations` 接口;`RacpClient` 关联请求、应答服务端发起的请求、按会话记录最后的持久游标、以有界退避重连,并让断开连接上未完成的调用以 `HOST_DISCONNECTED` 失败而不是重发。认证采用 header profile:Host 签发的 `pdt1.` 设备令牌与一次性、有时限的 `ppt1.` 配对令牌(散列存储、常量时间比较、绝不出现在 URL 中);`connection/pair` 铸造 `owner` 设备。`connection/pair`、`project/register`、`project/browse`、`server.hostId`、`events/closed` 通知,以及错误码 `PAIRING_FAILED`、`PAIRING_TOKEN_EXPIRED`、`CAPABILITY_UNAVAILABLE`、`REMOTE_PATH_NOT_FOUND`、`REMOTE_PATH_FORBIDDEN`、`HOST_DISCONNECTED`、`HOST_BOOTSTRAP_FAILED`、`HOST_VERSION_MISMATCH`、`REMOTE_AUTH_FAILED`、`REMOTE_CONNECTION_FAILED`、`REMOTE_FORWARD_FAILED` 进入契约(规格 §14a)。绑定拒绝非回环地址;附件与工具中继宣告为不可用。** | SSH 隧道拓扑需要 `pi-host` 能绑定的服务端和桌面能运行的客户端,以及安全规格描述的配对;不需要机器边界的一致性行为成为包内测试 |## B. 辅助实现默认值