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
vastsa2e7992f02f25
diff --cc apps/pi-host/src/credentials.tsindex 6223078a5,000000000..ab15a9644mode 100644,000000..100644--- a/apps/pi-host/src/credentials.ts+++ b/apps/pi-host/src/credentials.ts@@@ -1,119 -1,0 +1,119 @@@+import { randomBytes } from "node:crypto";+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";++import type { DeviceCredentialStore, DeviceRecord, PairingRecord } from "@pi-desktop/racp";++type IdentityFile = { hostId: string; createdAt: string };+type CredentialFile = { devices: DeviceRecord[]; pairings: PairingRecord[] };++const FILE_MODE = 0o600;++async function readJson<T>(path: string): Promise<T | null> {+ try {+ return JSON.parse(await readFile(path, "utf8")) as T;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw error;+ }+}++async function writeJsonAtomic(path: string, value: unknown): Promise<void> {+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });+ const temp = `${path}.${process.pid}.tmp`;+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: FILE_MODE });+ await rename(temp, path);+}++/**- * The Host's stable identity (D446): minted once at first start and kept++ * The Host's stable identity (D448): minted once at first start and kept+ * beside the data directory. Never derived from hostname, address, or path,+ * so two machines with the same project path are still two Hosts.+ */+export async function loadOrCreateHostId(dataDir: string): Promise<string> {+ const path = join(dataDir, "pi-host", "identity.json");+ const existing = await readJson<IdentityFile>(path);+ if (existing?.hostId) return existing.hostId;+ const created: IdentityFile = { hostId: `host_${randomBytes(12).toString("base64url")}`, createdAt: new Date().toISOString() };+ await writeJsonAtomic(path, created);+ return created.hostId;+}++/**+ * Device and pairing records under `<dataDir>/pi-host/credentials.json`,+ * owner-readable only. Tokens are stored as SHA-256 hashes (security §3.4);+ * the file never holds a usable credential.+ */+export class FileCredentialStore implements DeviceCredentialStore {+ private readonly path: string;+ private state: CredentialFile | null = null;+ private chain = Promise.resolve();++ constructor(dataDir: string) {+ this.path = join(dataDir, "pi-host", "credentials.json");+ }++ private async load(): Promise<CredentialFile> {+ if (!this.state) this.state = (await readJson<CredentialFile>(this.path)) ?? { devices: [], pairings: [] };+ return this.state;+ }++ private async mutate<T>(operation: (state: CredentialFile) => T): Promise<T> {+ let result!: T;+ const run = this.chain.then(async () => {+ const state = await this.load();+ result = operation(state);+ // Expired, consumed pairings are useless after a write; drop them.+ const now = Date.now();+ state.pairings = state.pairings.filter((pairing) => !pairing.consumedAt && Date.parse(pairing.expiresAt) > now);+ await writeJsonAtomic(this.path, state);+ });+ this.chain = run.catch(() => undefined);+ await run;+ return result;+ }++ async findDeviceByTokenHash(tokenHash: string): Promise<DeviceRecord | null> {+ const state = await this.load();+ return state.devices.find((device) => device.tokenHash === tokenHash) ?? null;+ }+ async saveDevice(record: DeviceRecord): Promise<void> {+ await this.mutate((state) => {+ state.devices = [...state.devices.filter((device) => device.deviceId !== record.deviceId), record];+ });+ }+ async touchDevice(deviceId: string, seenAt: string): Promise<void> {+ const state = await this.load();+ const device = state.devices.find((candidate) => candidate.deviceId === deviceId);+ // Last-seen is informational; it does not need a synchronous write per connection.+ if (device) device.lastSeenAt = seenAt;+ }+ async revokeDevice(deviceId: string, revokedAt: string): Promise<boolean> {+ return this.mutate((state) => {+ const device = state.devices.find((candidate) => candidate.deviceId === deviceId);+ if (!device || device.revokedAt) return false;+ device.revokedAt = revokedAt;+ return true;+ });+ }+ async listDevices(): Promise<DeviceRecord[]> {+ return [...(await this.load()).devices];+ }+ async findPairing(tokenHash: string): Promise<PairingRecord | null> {+ const state = await this.load();+ return state.pairings.find((pairing) => pairing.tokenHash === tokenHash) ?? null;+ }+ async savePairing(record: PairingRecord): Promise<void> {+ await this.mutate((state) => {+ state.pairings = [...state.pairings.filter((pairing) => pairing.tokenHash !== record.tokenHash), record];+ });+ }+ async consumePairing(tokenHash: string, consumedAt: string): Promise<boolean> {+ return this.mutate((state) => {+ const pairing = state.pairings.find((candidate) => candidate.tokenHash === tokenHash);+ if (!pairing || pairing.consumedAt) return false;+ pairing.consumedAt = consumedAt;+ return true;+ });+ }+}diff --cc apps/pi-host/src/host-operations.tsindex 12034a4b6,000000000..b8b1ae965mode 100644,000000..100644--- a/apps/pi-host/src/host-operations.ts+++ b/apps/pi-host/src/host-operations.ts@@@ -1,251 -1,0 +1,251 @@@+import { readdir, realpath, stat } from "node:fs/promises";+import { homedir } from "node:os";+import { basename, dirname, isAbsolute, join, resolve } from "node:path";++import { RacpError, type Principal, type SessionSummary } from "@pi-desktop/agent-host";+import {+ collectWorkspaceDiff,+ listDir,+ readWorkspaceFile,+ toSessionSummary,+ type HostRpc,+ type HostSessionRecord,+ type RuntimeService,+} from "@pi-desktop/host-runtime";+import type { RacpHostOperations, RacpProjectCatalog, RacpSessionCatalog, RacpWorkspaceAccess } from "@pi-desktop/racp";+import type { RacpProjectSummary } from "@pi-desktop/shared";++/** A project row as host-core lists it. */+type ProjectRow = { id: number; path: string; name: string; pinned?: boolean };++/** Directory names never offered by the folder picker. */+const HIDDEN_BROWSE_NAMES = new Set([".git", "node_modules", "__pycache__", ".Trash"]);+const MAX_BROWSE_ENTRIES = 500;++function hostError(error: unknown): never {+ const code = (error as { errorCode?: string; data?: { errorCode?: string } })?.data?.errorCode ?? (error as { errorCode?: string })?.errorCode;+ const message = error instanceof Error ? error.message : String(error);+ if (code === "NOT_FOUND" || code === "SESSION_NOT_FOUND") throw new RacpError("NOT_FOUND", message);+ if (code === "CONFLICT" || (code && code.startsWith("PLAN_"))) throw new RacpError("CONFLICT", message, { details: { code } });+ if (code === "INVALID_PARAMS" || code === "INVALID_ARGUMENT") throw new RacpError("INVALID_ARGUMENT", message);+ if (code === "HOST_UNAVAILABLE") throw new RacpError("AGENT_UNAVAILABLE", message, { retriable: true });+ throw new RacpError("INTERNAL", message, { details: code ? { code } : undefined });+}++function projectSummary(row: ProjectRow): RacpProjectSummary {+ return { id: String(row.id), label: row.name || basename(row.path), archived: false };+}++export type HostOperationsDeps = {+ getHost: () => HostRpc | null;+ runtime: Pick<RuntimeService, "compact" | "isBusy">;+ /** `pi-host` boots the sidecar's session cleanup on delete; the runtime link is optional at boot. */+ disposeSession?: (sessionId: string) => Promise<void>;+ revokeDevice?: (deviceId: string) => Promise<boolean>;+ /** Root the folder picker may not leave; defaults to the user's home directory. */+ browseRoot?: string;+};++function requireHost(getHost: () => HostRpc | null): HostRpc {+ const host = getHost();+ if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host-core is not running", { retriable: true });+ return host;+}++/** Session catalog over host-core RPC. */+export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatalog {+ const { getHost } = deps;+ async function projectPathFor(projectId: string | undefined, host: HostRpc): Promise<string | undefined> {+ if (!projectId) return undefined;+ const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {});+ const project = projects.find((row) => String(row.id) === projectId);+ if (!project) throw new RacpError("NOT_FOUND", `project ${projectId} is unknown`);+ return project.path;+ }+ /**+ * host-core keys a session by its project path; RACP exposes the project id+ * (spec §5.1), so the summary is decorated from the projects table. A path+ * with no row (a session whose project was removed) simply has no id.+ */+ async function withProjectIds(host: HostRpc, records: HostSessionRecord[]): Promise<SessionSummary[]> {+ const needsLookup = records.some((record) => record.projectPath);+ const byPath = new Map<string, string>();+ if (needsLookup) {+ const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ for (const project of projects ?? []) byPath.set(project.path, String(project.id));+ }+ return records.map((record) => {+ const summary = toSessionSummary(record);+ const projectId = record.projectPath ? byPath.get(record.projectPath) : undefined;+ return projectId ? { ...summary, projectId } : summary;+ });+ }+ async function get(host: HostRpc, sessionId: string): Promise<SessionSummary> {+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);+ if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ return (await withProjectIds(host, [result.session]))[0]!;+ }+ return {+ async list() {+ const host = requireHost(getHost);+ const result = await host.call<{ sessions: HostSessionRecord[] }>("session.list", {}).catch(hostError);+ return withProjectIds(host, result.sessions ?? []);+ },+ async create(input, _principal: Principal) {+ const host = requireHost(getHost);+ const projectPath = await projectPathFor(input.projectId, host);+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.create", {+ ...(input.title ? { title: input.title } : {}),+ ...(input.mode ? { mode: input.mode } : {}),+ ...(input.providerId ? { providerId: input.providerId } : {}),+ ...(input.modelId ? { modelId: input.modelId } : {}),+ ...(input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {}),+ ...(projectPath ? { projectPath } : {}),+ })+ .catch(hostError);+ if (!result.session) throw new RacpError("INTERNAL", "session.create returned no session");+ if (input.permissionMode) {+ await host+ .call("session.configure", { id: result.session.id, mode: result.session.mode ?? input.mode ?? "agent", permissionMode: input.permissionMode })+ .catch(hostError);+ }+ return get(host, result.session.id);+ },+ async configure(sessionId, input) {+ const host = requireHost(getHost);+ if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");+ const current = await get(host, sessionId);+ await host+ .call("session.configure", {+ id: sessionId,+ mode: input.mode ?? current.mode,+ ...(input.providerId !== undefined ? { providerId: input.providerId } : {}),+ ...(input.modelId !== undefined ? { modelId: input.modelId } : {}),+ ...(input.thinkingLevel !== undefined ? { thinkingLevel: input.thinkingLevel } : {}),+ ...(input.permissionMode !== undefined ? { permissionMode: input.permissionMode } : {}),+ })+ .catch(hostError);+ return get(host, sessionId);+ },+ async fork(sessionId, input) {+ const host = requireHost(getHost);+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.fork", {+ sessionId,+ ...(input.title ? { title: input.title } : {}),+ ...(input.throughMessageId ? { throughMessageId: input.throughMessageId } : {}),+ })+ .catch(hostError);+ if (!result.session) throw new RacpError("INTERNAL", "session.fork returned no session");+ return get(host, result.session.id);+ },+ async rename(sessionId, title) {+ await requireHost(getHost).call("session.rename", { id: sessionId, title }).catch(hostError);+ },+ async delete(sessionId) {+ if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");+ await requireHost(getHost).call("session.delete", { id: sessionId }).catch(hostError);+ await deps.disposeSession?.(sessionId).catch(() => undefined);+ },+ async compact(sessionId) {+ try {+ return await deps.runtime.compact(sessionId);+ } catch (error) {+ hostError(error);+ }+ },+ };+}++async function canonicalDirectory(path: string): Promise<string> {+ if (!isAbsolute(path)) throw new RacpError("INVALID_ARGUMENT", "path must be absolute");+ let real: string;+ try {+ real = await realpath(path);+ } catch {+ throw new RacpError("REMOTE_PATH_NOT_FOUND", `no such directory: ${path}`);+ }+ const info = await stat(real).catch(() => null);+ if (!info?.isDirectory()) throw new RacpError("REMOTE_PATH_NOT_FOUND", `not a directory: ${path}`);+ return real;+}+- /** Projects over host-core: registration canonicalizes on the Host (D446). */++/** Projects over host-core: registration canonicalizes on the Host (D448). */+export function createProjectCatalog(deps: HostOperationsDeps): RacpProjectCatalog {+ const { getHost } = deps;+ const browseRoot = resolve(deps.browseRoot ?? homedir());+ return {+ async list() {+ const host = requireHost(getHost);+ const result = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ return (result.projects ?? []).map(projectSummary);+ },+ async register(path) {+ const host = requireHost(getHost);+ const real = await canonicalDirectory(path);+ const result = await host.call<{ project?: ProjectRow | null }>("projects.create", { path: real }).catch(hostError);+ if (!result.project) throw new RacpError("INTERNAL", "projects.create returned no project");+ return { ...projectSummary(result.project), path: result.project.path };+ },+ async browse(path) {+ const target = path ? await canonicalDirectory(path) : browseRoot;+ const rootReal = await realpath(browseRoot).catch(() => browseRoot);+ if (target !== rootReal && !target.startsWith(rootReal.endsWith("/") ? rootReal : `${rootReal}/`)) {+ throw new RacpError("REMOTE_PATH_FORBIDDEN", "path is outside the browsable root");+ }+ const dirents = await readdir(target, { withFileTypes: true }).catch(() => {+ throw new RacpError("REMOTE_PATH_FORBIDDEN", `cannot read ${target}`);+ });+ const entries = dirents+ .filter((dirent) => dirent.isDirectory() && !HIDDEN_BROWSE_NAMES.has(dirent.name) && !dirent.name.startsWith("."))+ .map((dirent) => ({ name: dirent.name, path: join(target, dirent.name) }))+ .sort((a, b) => a.name.localeCompare(b.name))+ .slice(0, MAX_BROWSE_ENTRIES);+ const parent = target === rootReal ? undefined : dirname(target);+ return { path: target, ...(parent ? { parent } : {}), entries };+ },+ };+}++/** Workspace reads against the session's durable root, on the Host's filesystem. */+export function createWorkspaceAccess(deps: HostOperationsDeps): RacpWorkspaceAccess {+ const { getHost } = deps;+ async function sessionRoot(sessionId: string): Promise<string> {+ const host = requireHost(getHost);+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);+ if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ const root = result.session.projectPath?.trim();+ if (!root) throw new RacpError("CONFLICT", "the session has no project root");+ return root;+ }+ const forbidden = (error: unknown): never => {+ const message = error instanceof Error ? error.message : String(error);+ if (/escapes workspace root|outside allowed roots/.test(message)) throw new RacpError("REMOTE_PATH_FORBIDDEN", message);+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") throw new RacpError("REMOTE_PATH_NOT_FOUND", message);+ if (/not a file/.test(message)) throw new RacpError("INVALID_ARGUMENT", message);+ throw new RacpError("INTERNAL", message);+ };+ return {+ async list(sessionId, path) {+ const root = await sessionRoot(sessionId);+ return { entries: await listDir(root, path).catch(forbidden) };+ },+ async read(sessionId, path) {+ const root = await sessionRoot(sessionId);+ return readWorkspaceFile(root, path).catch(forbidden);+ },+ async diff(sessionId) {+ return collectWorkspaceDiff(await sessionRoot(sessionId));+ },+ };+}++export function createHostOperations(deps: HostOperationsDeps): Omit<RacpHostOperations, "terminal"> {+ return {+ sessions: createSessionCatalog(deps),+ projects: createProjectCatalog(deps),+ workspace: createWorkspaceAccess(deps),+ ...(deps.revokeDevice ? { revokeDevice: deps.revokeDevice } : {}),+ };+}diff --cc docs/adr/0283-headless-runtime-boundary.mdindex 1ffc08750,000000000..67ad351f6mode 100644,000000..100644--- a/docs/adr/0283-headless-runtime-boundary.md+++ b/docs/adr/0283-headless-runtime-boundary.md@@@ -1,118 -1,0 +1,118 @@@- # ADR 0282: Headless runtime boundary in `packages/host-runtime`++# ADR 0283: Headless runtime boundary in `packages/host-runtime`++- Status: Accepted for implementation+- Date: 2026-09-18- - Decision: D445++- 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/0284-racp-ws-transport.mdindex af2199aaa,000000000..8a78ed61emode 100644,000000..100644--- a/docs/adr/0284-racp-ws-transport.md+++ b/docs/adr/0284-racp-ws-transport.md@@@ -1,88 -1,0 +1,88 @@@- # ADR 0283: `RACP-WS` transport in `packages/racp`++# ADR 0284: `RACP-WS` transport in `packages/racp`++- Status: Accepted for implementation+- Date: 2026-09-18- - Decision: D446- - Related: ADR 0205 (D373 / D374 / D375), ADR 0282 (D445),++- Decision: D448++- Related: ADR 0205 (D373 / D374 / D375), ADR 0283 (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 0282); the desktop adapter composes `RacpClient` +++ `RuntimeService` (ADR 0283); 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/README.mdindex a1b3c2fda,928b5680b..db123c60b--- a/docs/adr/README.md+++ b/docs/adr/README.md@@@ -308,6 -308,5 +308,7 @@@ Each ADR includes| 0279 | [Resumable subagent delegations](0279-resumable-subagent-delegations.md) | Accepted for implementation (amends ADR 0062; ADR 0089; issue #513) || 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 | [Headless runtime boundary in `packages/host-runtime`](0282-headless-runtime-boundary.md) | Accepted for implementation (D445; ADR 0205 R2 prerequisite) |- | 0283 | [`RACP-WS` transport in `packages/racp`](0283-racp-ws-transport.md) | Accepted for implementation (D446; ADR 0205 R2) |+ | 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) || 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 9066cbd50,d3ae914f6..c395f889f--- 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 0282; Electron main adapts them and owns the++`packages/host-runtime`, ADR 0283; 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/19-remote-agent-control-protocol.mdindex ee986a701,0445410bf..8b067e895--- a/docs/spec/03-runtime/19-remote-agent-control-protocol.md+++ b/docs/spec/03-runtime/19-remote-agent-control-protocol.md@@@ -591,9 -591,6 +591,9 @@@ session root as working directory and s| `terminal/input` | controller | Write bytes to an open terminal || `terminal/resize` | controller | Resize an open terminal || `terminal/close` | controller | Close a terminal; idempotent |- | `connection/pair` | authenticated | Exchange the single-use pairing token presented on the upgrade for a device credential (security §3.4); only valid on a pairing connection (D446) |- | `project/register` | owner | Register a Host directory as a project: the Host canonicalizes and validates the path and returns the project id (D446) |- | `project/browse` | owner | List directories under a Host path, bounded, for the remote folder picker (D446) |++| `connection/pair` | authenticated | Exchange the single-use pairing token presented on the upgrade for a device credential (security §3.4); only valid on a pairing connection (D448) |++| `project/register` | owner | Register a Host directory as a project: the Host canonicalizes and validates the path and returns the project id (D448) |++| `project/browse` | owner | List directories under a Host path, bounded, for the remote folder picker (D448) |### 6.3 Deferred operations@@@ -1216,33 -1208,6 +1216,33 @@@ thing across all bindings8. The client treats a new major protocol version as incompatible unless anexplicit compatibility adapter is selected.- ## 14a. RACP-WS binding implementation notes (D446)++## 14a. RACP-WS binding implementation notes (D448)++`packages/racp` is the reference implementation of the `RACP-WS` binding.+Beyond the rules above it fixes these wire details:++- `connection/initialize` answers with `server.hostId`, the Host's stable+ identity minted at first start; a client keys its Host records by it, never+ by hostname, address, or path.+- The client sends `notifications/initialized` after the initialization+ result; the Host closes a connection that has not initialized within the+ §12 deadline.+- A JSON-RPC error carries the `RemoteError` under `error.data`; the numeric+ `error.code` is `-32601` for `METHOD_NOT_FOUND`, `-32602` for+ `INVALID_ARGUMENT`, and `-32000` otherwise.+- When the Host closes one subscription (`CLIENT_TOO_SLOW`) it sends the+ `events/closed` notification with the subscription id, the `RemoteError`,+ and the last safely delivered cursor; the connection stays open.+- Terminal events are connection-local and are never entered into the+ session's durable log; their `epoch` is the session's and+ `terminal.changed` carries the current sequence without allocating one.+- Device tokens are `pdt1.`-prefixed and pairing tokens `ppt1.`-prefixed;+ both are presented as `Authorization: Bearer` on the upgrade, stored+ hashed (SHA-256) on the Host, and never accepted from a URL.+- Reconnect never re-sends an in-flight request: the pending calls of the+ dropped connection fail with `HOST_DISCONNECTED`, and a caller that retries+ presents the same idempotency key.+## 15. Amendment historyD374 (2026-09-10) revised the D373 draft before implementation:diff --cc docs/spec/06-delivery/07-remote-control-rollout.mdindex 2f94a71c5,63e5d0ca5..d7ea20f5c--- a/docs/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/spec/06-delivery/07-remote-control-rollout.md@@@ -402,18 -402,7 +402,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, D445 / ADR 0282): `packages/host-runtime` holds the-- R2 and later: not started.++- R2 started (2026-09-18, D447 / ADR 0283): `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, D446 / ADR 0283): `packages/racp` holds the `RACP-WS`++- R2 (2026-09-18, D448 / ADR 0284): `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 2f834f9c3,ba9e36102..a5c9c0c4b--- 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) |- | D445 | Headless runtime boundary | **Amend ADR 0205 rollout R2 prerequisites (ADR 0282): 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 |- | D446 | RACP-WS transport and device pairing | **Amend ADR 0205 rollout R2 (ADR 0283): `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 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 |## B. Secondary implementation defaultsdiff --cc docs/zh-CN/adr/index.mdindex 96d848555,52994a0ad..0ce47eac3--- a/docs/zh-CN/adr/index.md+++ b/docs/zh-CN/adr/index.md@@@ -290,6 -290,7 +290,9 @@@ ADR 记录那些不应被静默改变�| 0278 | [规范应用 ID `net.aiuo.pi-desktop`](/adr/0278-canonical-application-id) | 已接受(D443;修订 D141 / D371 / ADR 0204;issue #524) || 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) || turn-process-and-thinking-display | [回合过程与思考展示](/adr/turn-process-and-thinking-display) | 已接受 |## 什么时候看 ADRdiff --cc docs/zh-CN/spec/03-runtime/07-process-model.mdindex 7745a3531,80444a43d..a08c4841d--- 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 0282;Electron main 适配它们并负责面向渲染层的状态):-监管参数(在Electron main中实现):++监管参数(传输、重启策略与回合生命周期位于 `packages/host-runtime`,ADR 0283;Electron main 适配它们并负责面向渲染层的状态):- 子进程退出立即拒绝该子进程的所有正在进行的 RPC(无 130 秒超时等待)。- 超过 64 MiB 的 NDJSON 请求行以 `LIMIT_EXCEEDED` 应答,不结束 stdin 读取器(ADR 0216)。Electron 在写入 stdin 前拒绝同样大小的载荷(ADR 0217)。diff --cc docs/zh-CN/spec/03-runtime/19-remote-agent-control-protocol.mdindex f69982f05,e43e5c560..e05123bba--- a/docs/zh-CN/spec/03-runtime/19-remote-agent-control-protocol.md+++ b/docs/zh-CN/spec/03-runtime/19-remote-agent-control-protocol.md@@@ -213,9 -213,6 +213,9 @@@ owner,工作区读取都按会话持�| `terminal/input` | controller | 向已打开终端写入字节 || `terminal/resize` | controller | 调整已打开终端尺寸 || `terminal/close` | controller | 关闭终端,幂等 |- | `connection/pair` | authenticated | 用升级请求携带的一次性配对令牌换取设备凭证(安全规格 §3.4);仅在配对连接上有效(D446) |- | `project/register` | owner | 将 Host 上的目录注册为项目:Host 规范化并校验路径,返回项目 id(D446) |- | `project/browse` | owner | 列出 Host 某路径下的目录,有界,供远程目录选择器使用(D446) |++| `connection/pair` | authenticated | 用升级请求携带的一次性配对令牌换取设备凭证(安全规格 §3.4);仅在配对连接上有效(D448) |++| `project/register` | owner | 将 Host 上的目录注册为项目:Host 规范化并校验路径,返回项目 id(D448) |++| `project/browse` | owner | 列出 Host 某路径下的目录,有界,供远程目录选择器使用(D448) |仍推迟的本地操作:diff --cc docs/zh-CN/spec/06-delivery/07-remote-control-rollout.mdindex 73ee29b5c,198cc6764..a7fece4ca--- a/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md@@@ -138,8 -138,7 +138,8 @@@ runbook 写明 feature flag、配对撤- R1 已交付:renderer 的内存 prompt 队列已退役;composer 经 `agent/queue/push` 推入,镜像 `agent/event/queueChanged`,“立即发送”即 `turn/prioritize` 加优雅停止。- R1 未完成:运行时级别的逐回合权限上限(当前被限制的回合在桥接层直接拒绝)。- - R2 已开始(2026-09-18,D445 / ADR 0282):`packages/host-runtime` 承载与 Electron 无关的运行时层 —— host-core 与 sidecar 的 stdio 传输、重启监督器、`RuntimeService`(模块的 `RuntimePort`,含持久回合生命周期)、转录持久化、无头启动解析器与已批准 Plan/Goal 的派发 —— Electron main 通过薄适配层运行其上。- - R2(2026-09-18,D446 / ADR 0283):`packages/racp` 承载 `RACP-WS` 服务端与客户端核心、回环上的 `ws` 绑定与设备令牌配对;握手、鉴权、幂等、队列顺序、审批、游标重放、驱逐、epoch 变更、慢客户端与不重复执行的重连都是包内测试。`pi-host` 包、SSH 引导与桌面适配器尚未开始。-- R2 及之后:尚未开始。++- 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 引导与桌面适配器尚未开始。## 8. 修订记录diff --cc docs/zh-CN/spec/08-meta/decisions-log.mdindex 1563f7251,9a2577b83..a7f5fd657--- 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) |- | D445 | 无头运行时边界 | **修订 ADR 0205 里程碑 R2 的前置条件(ADR 0282):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 的情况下运行与桌面相同的生命周期不变量;第二份中止锁、过期终态事件与持久落库后释放队列的实现会与桌面已修好的那份漂移 |- | D446 | RACP-WS 传输与设备配对 | **修订 ADR 0205 里程碑 R2(ADR 0283):`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 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` 能绑定的服务端和桌面能运行的客户端,以及安全规格描述的配对;不需要机器边界的一致性行为成为包内测试 |## B. 辅助实现默认值diff --cc packages/racp/src/server.tsindex b5ce45656,000000000..08edea5d9mode 100644,000000..100644--- a/packages/racp/src/server.ts+++ b/packages/racp/src/server.ts@@@ -1,364 -1,0 +1,364 @@@+import { randomUUID } from "node:crypto";++import { AgentHost, RacpError, type Principal } from "@pi-desktop/agent-host";+import {+ RACP_DEFAULT_LIMITS,+ RACP_DEFAULT_POLICY,+ RACP_EVENT_NOTIFICATION,+ RACP_INITIALIZED_NOTIFICATION,+ RACP_OPERATIONS,+ RACP_PROTOCOL_VERSION,+ RACP_SUBSCRIPTION_CLOSED_NOTIFICATION,+ RacpInitializeParamsSchema,+ protocolVersionsCompatible,+ rolesAllowOperation,+ type RacpEventEnvelope,+ type RacpInitializeResult,+ type RacpLimits,+ type RacpOperation,+ type RacpPolicy,+ type RacpServerCapabilities,+} from "@pi-desktop/shared";+import * as Value from "typebox/value";++import type { ConnectionAuth, DeviceTokenAuthenticator } from "./auth.js";+import type { RacpHostOperations } from "./host-operations.js";+import {+ encodeFrame,+ errorObjectFrom,+ isNotification,+ isRequest,+ isResponse,+ parseFrame,+ type JsonRpcErrorObject,+ type JsonRpcId,+ type JsonRpcMessage,+} from "./jsonrpc.js";+import { createOperations, type OperationContext, type OperationHandler } from "./operations.js";++/** One accepted transport connection, as the server drives it. */+export interface ServerConnectionTransport {+ send(frame: string): void;+ close(code: number, reason: string): void;+ onMessage(handler: (frame: string, byteLength: number) => void): void;+ onClose(handler: () => void): void;+}++export type RacpServerOptions = {+ agentHost: AgentHost;+ operations: RacpHostOperations;+ authenticator: DeviceTokenAuthenticator;- /** Stable Host identity (D446). */++ /** Stable Host identity (D448). */+ hostId: string;+ serverName?: string;+ serverVersion: string;+ limits?: Partial<RacpLimits>;+ policy?: Partial<RacpPolicy>;+ log: (level: "info" | "warn" | "error", message: string, data?: Record<string, unknown>) => void;+ now?: () => number;+ /** Deadline for `connection/initialize` after the socket opened (spec §12). */+ initializeTimeoutMs?: number;+};++type Subscription = { id: string; sessionId?: string };++type ServerRequestWaiter = {+ resolve: (value: unknown) => void;+ reject: (error: RacpError) => void;+ timer: ReturnType<typeof setTimeout>;+};++/** Per-connection state; the server keeps one per accepted socket. */+export class RacpConnection {+ readonly id = `conn_${randomUUID()}`;+ principal: Principal;+ initialized = false;+ readonly subscriptions = new Map<string, Subscription>();+ readonly terminals = new Set<string>();+ private readonly pendingServerRequests = new Map<string, ServerRequestWaiter>();+ private serverRequestCounter = 0;+ private closed = false;++ constructor(+ readonly auth: ConnectionAuth,+ readonly transport: ServerConnectionTransport,+ private readonly server: RacpServer,+ ) {+ this.principal = { ...auth.principal, connectionId: this.id };+ }++ send(message: JsonRpcMessage): void {+ if (this.closed) return;+ try {+ this.transport.send(encodeFrame(message));+ } catch (error) {+ this.server.log("warn", "racp send failed", { connectionId: this.id, error: String(error) });+ }+ }++ notify(method: string, params: unknown): void {+ this.send({ jsonrpc: "2.0", method, params });+ }++ /** A server-initiated request (spec §4.3); resolves with the client's result. */+ request<T = unknown>(method: string, params: unknown, timeoutMs: number): Promise<T> {+ this.serverRequestCounter += 1;+ const id = `srv_${this.serverRequestCounter}`;+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pendingServerRequests.delete(id);+ reject(new RacpError("TOOL_FAILED", `client did not answer ${method} in time`));+ }, timeoutMs);+ timer.unref?.();+ this.pendingServerRequests.set(id, { resolve: resolve as (value: unknown) => void, reject, timer });+ this.send({ jsonrpc: "2.0", id, method, params });+ });+ }++ handleResponse(id: JsonRpcId, result: unknown, error: JsonRpcErrorObject | undefined): void {+ const waiter = this.pendingServerRequests.get(String(id));+ if (!waiter) return;+ this.pendingServerRequests.delete(String(id));+ clearTimeout(waiter.timer);+ if (error) waiter.reject(new RacpError(error.data?.code ?? "TOOL_FAILED", error.message));+ else waiter.resolve(result);+ }++ close(code: number, reason: string): void {+ if (this.closed) return;+ this.closed = true;+ for (const waiter of this.pendingServerRequests.values()) {+ clearTimeout(waiter.timer);+ waiter.reject(new RacpError("AGENT_UNAVAILABLE", "connection closed"));+ }+ this.pendingServerRequests.clear();+ try {+ this.transport.close(code, reason);+ } catch {+ // Already gone.+ }+ }++ get isClosed(): boolean {+ return this.closed;+ }+}++/**+ * The `RACP-WS` server core: connection admission, initialization, request+ * dispatch with role checks from the operation catalog, event fan-out from+ * the Agent Host hub, and connection teardown that releases every+ * subscription and terminal the connection held. Transport framing is+ * injected so the same core runs over `ws` in `pi-host` and over an+ * in-memory pair in tests.+ */+export class RacpServer {+ readonly limits: RacpLimits;+ readonly policy: RacpPolicy;+ readonly capabilities: RacpServerCapabilities;+ private readonly connections = new Map<string, RacpConnection>();+ private readonly handlers: Map<RacpOperation, OperationHandler>;+ private readonly now: () => number;+ private closed = false;++ constructor(private readonly options: RacpServerOptions) {+ this.limits = { ...RACP_DEFAULT_LIMITS, ...options.limits };+ this.policy = { ...RACP_DEFAULT_POLICY, ...options.policy };+ this.now = options.now ?? (() => Date.now());+ this.capabilities = {+ eventReplay: true,+ snapshot: true,+ approvals: true,+ inputRequests: true,+ attachments: false,+ serverRequests: true,+ turnQueue: true,+ hostEvents: true,+ history: true,+ remoteHostProfile: true,+ toolRelay: false,+ terminal: Boolean(options.operations.terminal),+ notifications: false,+ bindings: ["RACP-WS"],+ };+ this.handlers = createOperations();+ }++ get log(): RacpServerOptions["log"] {+ return this.options.log;+ }++ connectionCount(): number {+ return this.connections.size;+ }++ /**+ * Admit one authenticated transport. Returns the connection, or `null`+ * when the Host is at its client limit (the transport is closed with+ * `RATE_LIMITED`).+ */+ accept(auth: ConnectionAuth, transport: ServerConnectionTransport): RacpConnection | null {+ if (this.closed) {+ transport.close(1001, "server closing");+ return null;+ }+ if (this.connections.size >= this.limits.maxConnectedClients) {+ this.options.log("warn", "racp connection refused: client limit", { limit: this.limits.maxConnectedClients });+ transport.close(1013, "RATE_LIMITED");+ return null;+ }+ const connection = new RacpConnection(auth, transport, this);+ this.connections.set(connection.id, connection);+ const initializeTimer = setTimeout(() => {+ if (!connection.initialized) {+ this.options.log("warn", "racp connection closed: initialize deadline", { connectionId: connection.id });+ connection.close(1002, "PROTOCOL_MISMATCH");+ }+ }, this.options.initializeTimeoutMs ?? 10_000);+ initializeTimer.unref?.();+ transport.onMessage((frame, byteLength) => {+ if (byteLength > this.limits.maxFrameBytes) {+ connection.send({+ jsonrpc: "2.0",+ id: 0,+ error: errorObjectFrom(new RacpError("PAYLOAD_TOO_LARGE", "frame exceeds maxFrameBytes"), this.traceId()),+ });+ return;+ }+ void this.handleFrame(connection, frame);+ });+ transport.onClose(() => {+ clearTimeout(initializeTimer);+ this.release(connection);+ });+ this.options.log("info", "racp connection accepted", {+ connectionId: connection.id,+ subject: auth.principal.subject,+ kind: auth.kind,+ });+ return connection;+ }++ /** Stop accepting and close every connection; running turns are untouched. */+ close(): void {+ this.closed = true;+ for (const connection of [...this.connections.values()]) {+ connection.close(1001, "server closing");+ this.release(connection);+ }+ }++ private traceId(): string {+ return `trace_${randomUUID()}`;+ }++ private release(connection: RacpConnection): void {+ if (!this.connections.delete(connection.id)) return;+ for (const subscription of connection.subscriptions.values()) {+ this.options.agentHost.unsubscribe(subscription.id, subscription.sessionId);+ }+ connection.subscriptions.clear();+ for (const terminalId of connection.terminals) {+ this.options.operations.terminal?.detach(terminalId);+ }+ connection.terminals.clear();+ connection.close(1000, "closed");+ this.options.log("info", "racp connection released", { connectionId: connection.id });+ }++ private async handleFrame(connection: RacpConnection, frame: string): Promise<void> {+ const message = parseFrame(frame);+ if (!message) {+ connection.send({+ jsonrpc: "2.0",+ id: 0,+ error: errorObjectFrom(new RacpError("INVALID_ARGUMENT", "frame is not a JSON-RPC 2.0 message"), this.traceId()),+ });+ return;+ }+ if (isResponse(message)) {+ connection.handleResponse(message.id, message.result, message.error);+ return;+ }+ if (!isRequest(message)) {+ if (isNotification(message) && message.method === RACP_INITIALIZED_NOTIFICATION) connection.initialized = true;+ return;+ }+ const traceId = this.traceId();+ try {+ const result = await this.dispatch(connection, message.method, message.params, traceId);+ connection.send({ jsonrpc: "2.0", id: message.id, result });+ } catch (error) {+ if (!(error instanceof RacpError)) {+ this.options.log("error", "racp operation failed", { method: message.method, traceId, error: String(error) });+ }+ connection.send({ jsonrpc: "2.0", id: message.id, error: errorObjectFrom(error, traceId) });+ }+ }++ private async dispatch(connection: RacpConnection, method: string, params: unknown, traceId: string): Promise<unknown> {+ if (method === "connection/initialize") {+ if (connection.initialized) throw new RacpError("CONFLICT", "the connection is already initialized");+ return this.initialize(connection, params);+ }+ if (!connection.initialized) {+ throw new RacpError("PROTOCOL_MISMATCH", "connection/initialize must complete first");+ }+ if (!(method in RACP_OPERATIONS)) throw new RacpError("METHOD_NOT_FOUND", `unknown operation ${method}`);+ const operation = method as RacpOperation;+ const handler = this.handlers.get(operation);+ if (!handler) throw new RacpError("METHOD_NOT_FOUND", `unknown operation ${method}`);+ if (!rolesAllowOperation(connection.principal.roles, operation)) {+ throw new RacpError("FORBIDDEN", `principal lacks the role for ${operation}`);+ }+ const context: OperationContext = {+ connection,+ principal: connection.principal,+ agentHost: this.options.agentHost,+ operations: this.options.operations,+ authenticator: this.options.authenticator,+ limits: this.limits,+ capabilities: this.capabilities,+ traceId,+ now: this.now,+ deliverEvent: (envelope) => this.deliverEvent(connection, envelope),+ closeSubscription: (subscriptionId, error, lastSafeCursor) => {+ connection.subscriptions.delete(subscriptionId);+ connection.notify(RACP_SUBSCRIPTION_CLOSED_NOTIFICATION, {+ subscriptionId,+ error: error.toRemoteError(this.traceId()),+ lastSafeCursor,+ });+ },+ log: this.options.log,+ };+ return handler(context, (params ?? {}) as Record<string, unknown>);+ }++ private deliverEvent(connection: RacpConnection, envelope: RacpEventEnvelope): void {+ connection.notify(RACP_EVENT_NOTIFICATION, envelope);+ }++ private initialize(connection: RacpConnection, params: unknown): RacpInitializeResult {+ if (!Value.Check(RacpInitializeParamsSchema, params)) {+ throw new RacpError("INVALID_ARGUMENT", "invalid connection/initialize params");+ }+ if (!protocolVersionsCompatible(RACP_PROTOCOL_VERSION, params.protocolVersion)) {+ throw new RacpError("PROTOCOL_MISMATCH", `protocol ${params.protocolVersion} is not compatible with ${RACP_PROTOCOL_VERSION}`);+ }+ if (!params.bindings.includes("RACP-WS")) {+ throw new RacpError("PROTOCOL_MISMATCH", "client does not offer the RACP-WS binding");+ }+ // A pairing connection may only pair; everything else needs the device's roles.+ connection.initialized = true;+ return {+ protocolVersion: RACP_PROTOCOL_VERSION,+ server: { name: this.options.serverName ?? "pi-host", version: this.options.serverVersion, hostId: this.options.hostId },+ connectionId: connection.id,+ principal: { subject: connection.principal.subject, roles: [...connection.principal.roles] },+ capabilities: this.capabilities,+ limits: this.limits,+ policy: this.policy,+ };+ }+}diff --cc packages/shared/src/errors.tsindex 8a5fbdbd8,1e5479d99..adf4c6b0a--- a/packages/shared/src/errors.ts+++ b/packages/shared/src/errors.ts@@@ -171,31 -171,6 +171,31 @@@ export const ErrorCodes =APPROVAL_STALE: "APPROVAL_STALE",PAYLOAD_TOO_LARGE: "PAYLOAD_TOO_LARGE",RATE_LIMITED: "RATE_LIMITED",+ /**- * Remote Host connection codes (D446 / ADR 0283). The desktop adapter and++ * Remote Host connection codes (D448 / ADR 0284). The desktop adapter and+ * the `pi-host` bootstrap classify a remote failure by these, never by+ * matching message text.+ */+ /** The transport to a paired Host dropped; the Host itself may still be running. */+ HOST_DISCONNECTED: "HOST_DISCONNECTED",+ /** Installing or starting `pi-host` over the bootstrap channel failed. */+ HOST_BOOTSTRAP_FAILED: "HOST_BOOTSTRAP_FAILED",+ /** The paired Host runs a different release than this client. */+ HOST_VERSION_MISMATCH: "HOST_VERSION_MISMATCH",+ /** The device credential was refused by the Host. */+ REMOTE_AUTH_FAILED: "REMOTE_AUTH_FAILED",+ /** The RACP connection could not be established. */+ REMOTE_CONNECTION_FAILED: "REMOTE_CONNECTION_FAILED",+ /** The transport's port forward could not be set up. */+ REMOTE_FORWARD_FAILED: "REMOTE_FORWARD_FAILED",+ /** A Host-side path does not exist. */+ REMOTE_PATH_NOT_FOUND: "REMOTE_PATH_NOT_FOUND",+ /** A Host-side path is outside what the principal may reach. */+ REMOTE_PATH_FORBIDDEN: "REMOTE_PATH_FORBIDDEN",+ PAIRING_FAILED: "PAIRING_FAILED",+ PAIRING_TOKEN_EXPIRED: "PAIRING_TOKEN_EXPIRED",+ /** The Host does not advertise the capability the operation needs. */+ CAPABILITY_UNAVAILABLE: "CAPABILITY_UNAVAILABLE",// Host-core RPC detail codes (spec 06 §7, 08 §3.1/§3.6). Electron surfaces// them unchanged through `AppError.code`.INVALID_PARAMS: "INVALID_PARAMS",diff --cc packages/shared/src/racp.tsindex 5ed730ee1,8b8f8d0d8..3caf0234f--- a/packages/shared/src/racp.ts+++ b/packages/shared/src/racp.ts@@@ -480,12 -480,7 +480,12 @@@ export type RacpInitializeParams = Statexport const RacpInitializeResultSchema = Type.Object({protocolVersion: Type.String({ minLength: 1 }),- server: Type.Object({ name: Type.String(), version: Type.String() }),+ server: Type.Object({+ name: Type.String(),+ version: Type.String(),- /** Stable identity of this Host, minted once at first start (D446). */++ /** Stable identity of this Host, minted once at first start (D448). */+ hostId: Type.Optional(Type.String({ minLength: 1 })),+ }),connectionId: Type.String({ minLength: 1 }),principal: Type.Object({subject: Type.String({ minLength: 1 }),