Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(remote): implement RACP-WS transport

vastsae2c8384c9a66
diff --git a/CLAUDE.md b/CLAUDE.md
index 9cb351577..5b8aee3ef 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -233,6 +233,7 @@ packages/
agent-runtime/ pi sidecar wrapper
agent-host/ headless Agent Host module (admission, queue, approvals, events)
host-runtime/ Electron-independent runtime (transports, supervisor, turn lifecycle)
+ racp/ RACP-WS server/client and device pairing
plugin-sdk/ plugin author types/validators
plugin-devkit/ pi-plugin CLI
examples/plugins/ sample plugins
diff --git a/docs/adr/0283-racp-ws-transport.md b/docs/adr/0283-racp-ws-transport.md
new file mode 100644
index 000000000..af2199aaa
--- /dev/null
+++ b/docs/adr/0283-racp-ws-transport.md
@@ -0,0 +1,88 @@
+# ADR 0283: `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),
+ `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` +
+ `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 --git a/docs/adr/README.md b/docs/adr/README.md
index 797c64526..a1b3c2fda 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -309,4 +309,5 @@ 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 | [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) |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
diff --git a/docs/spec/02-architecture/03-repo-structure.md b/docs/spec/02-architecture/03-repo-structure.md
index f3e9f3d8e..715bc62de 100644
--- a/docs/spec/02-architecture/03-repo-structure.md
+++ b/docs/spec/02-architecture/03-repo-structure.md
@@ -38,6 +38,7 @@ PI-Desktop/
│ ├── agent-runtime/ # pi sidecar and runtime wrapper (bundled into the app)
│ ├── agent-host/ # headless Agent Host module: admission, queue, approvals, event log
│ ├── host-runtime/ # Electron-independent runtime: stdio transports, supervisor, turn lifecycle
+│ ├── racp/ # RACP-WS server and client, device-token pairing
│ ├── plugin-sdk/ # plugin author types and validators
│ └── plugin-devkit/ # pi-plugin CLI: scaffold, check, pack, publish
├── examples/
diff --git a/docs/spec/03-runtime/19-remote-agent-control-protocol.md b/docs/spec/03-runtime/19-remote-agent-control-protocol.md
index 0445410bf..ee986a701 100644
--- a/docs/spec/03-runtime/19-remote-agent-control-protocol.md
+++ b/docs/spec/03-runtime/19-remote-agent-control-protocol.md
@@ -591,6 +591,9 @@ session root as working directory and stream through `terminal.output`.
| `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) |
### 6.3 Deferred operations
@@ -1177,6 +1180,11 @@ Initial RACP codes are:
| `APPROVAL_STALE` | no | Approval response targets an old revision |
| `PAYLOAD_TOO_LARGE` | no | Request, event, or attachment exceeds a limit |
| `RATE_LIMITED` | yes | Principal, session, or host quota exceeded |
+| `PAIRING_FAILED` | no | The pairing token is unknown or was already exchanged |
+| `PAIRING_TOKEN_EXPIRED` | no | The pairing token's bootstrap window passed |
+| `CAPABILITY_UNAVAILABLE` | no | The Host does not advertise the capability the operation needs |
+| `REMOTE_PATH_NOT_FOUND` | no | A Host-side path does not exist |
+| `REMOTE_PATH_FORBIDDEN` | no | A Host-side path is outside what the principal may reach |
| `INTERNAL` | maybe | Unexpected failure with a trace id |
Implementations MUST map these codes into the shared `AppError` vocabulary
@@ -1208,6 +1216,33 @@ thing across all bindings.
8. The client treats a new major protocol version as incompatible unless an
explicit compatibility adapter is selected.
+## 14a. RACP-WS binding implementation notes (D446)
+
+`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 history
D374 (2026-09-10) revised the D373 draft before implementation:
diff --git a/docs/spec/06-delivery/07-remote-control-rollout.md b/docs/spec/06-delivery/07-remote-control-rollout.md
index 6cb33ea59..2f94a71c5 100644
--- a/docs/spec/06-delivery/07-remote-control-rollout.md
+++ b/docs/spec/06-delivery/07-remote-control-rollout.md
@@ -407,8 +407,13 @@ Recorded on the `feat/remote-agent-host` branch, 2026-09-10:
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. The `pi-host` bundle, the RACP-WS
- transport, the SSH bootstrap, and the desktop adapter are not started.
+ main runs on it through thin adapters.
+- R2 (2026-09-18, D446 / ADR 0283): `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 history
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 8c4edf7d7..2f834f9c3 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -23,6 +23,7 @@ This log freezes previously open questions into concrete decisions.
| 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 |
## B. Secondary implementation defaults
diff --git a/docs/zh-CN/spec/02-architecture/03-repo-structure.md b/docs/zh-CN/spec/02-architecture/03-repo-structure.md
index 9e9c56fbc..505ea910f 100644
--- a/docs/zh-CN/spec/02-architecture/03-repo-structure.md
+++ b/docs/zh-CN/spec/02-architecture/03-repo-structure.md
@@ -39,6 +39,7 @@ PI-Desktop/
│ ├── agent-runtime/ # pi sidecar 与运行时包装(打包进应用)
│ ├── agent-host/ # 无头 Agent Host 模块:准入、队列、审批、事件日志
│ ├── host-runtime/ # 与 Electron 无关的运行时:stdio 传输、监督器、回合生命周期
+│ ├── racp/ # RACP-WS 服务端与客户端、设备令牌配对
│ ├── plugin-sdk/ # 插件作者类型与校验器
│ └── plugin-devkit/ # pi-plugin CLI:scaffold、check、pack、publish
├── examples/
diff --git 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
index e43e5c560..f69982f05 100644
--- 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,6 +213,9 @@ owner,工作区读取都按会话持久根、Host 忽略规则和 `PATH_OUTSID
| `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) |
仍推迟的本地操作:
@@ -335,6 +338,11 @@ Plan/Goal 审批为带显式 `permissionMode` 的 `approve` 或 `reject`,且
| `APPROVAL_STALE` | no | 审批响应针对旧 revision |
| `PAYLOAD_TOO_LARGE` | no | 请求、事件或附件超限 |
| `RATE_LIMITED` | yes | 主体、会话或 Host 超额 |
+| `PAIRING_FAILED` | no | 配对令牌未知或已被兑换 |
+| `PAIRING_TOKEN_EXPIRED` | no | 配对令牌的引导窗口已过 |
+| `CAPABILITY_UNAVAILABLE` | no | Host 未宣告该操作所需的能力 |
+| `REMOTE_PATH_NOT_FOUND` | no | Host 侧路径不存在 |
+| `REMOTE_PATH_FORBIDDEN` | no | Host 侧路径超出主体可达范围 |
| `INTERNAL` | maybe | 带 trace id 的内部错误 |
错误必须同时携带稳定 code、可重试标记和 trace id。重复 mutation 使用同一
diff --git a/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md b/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md
index 2dc8a3d7c..73ee29b5c 100644
--- 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,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 通过薄适配层运行其上。`pi-host` 包、RACP-WS 传输、SSH 引导与桌面适配器尚未开始。
+- 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 引导与桌面适配器尚未开始。
## 8. 修订记录
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index f4e29596f..1563f7251 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -26,6 +26,7 @@
| 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` 能绑定的服务端和桌面能运行的客户端,以及安全规格描述的配对;不需要机器边界的一致性行为成为包内测试 |
## B. 辅助实现默认值
diff --git a/packages/README.md b/packages/README.md
index 5307d4634..52434fb19 100644
--- a/packages/README.md
+++ b/packages/README.md
@@ -6,3 +6,4 @@
- `agent-runtime` — pi sidecar + runtime wrapper
- `agent-host` — headless Agent Host module (admission, turn queue, approvals, event log)
- `host-runtime` — Electron-independent runtime layer (stdio transports, restart supervisor, turn lifecycle)
+- `racp` — RACP-WS server and client cores, `ws` binding, device-token pairing
diff --git a/packages/agent-host/src/agent-host.ts b/packages/agent-host/src/agent-host.ts
index ea03cdf23..babd591a8 100644
--- a/packages/agent-host/src/agent-host.ts
+++ b/packages/agent-host/src/agent-host.ts
@@ -91,7 +91,13 @@ export type StartTurnParams = {
sessionId: string;
idempotencyKey?: string;
admission?: RacpTurnAdmission;
- input: { text: string; attachments?: AgentPromptAttachment[]; sessionMessageId?: string };
+ input: {
+ text: string;
+ attachments?: AgentPromptAttachment[];
+ sessionMessageId?: string;
+ /** Client-chosen id for the durable user row (D288). */
+ userMessageId?: string;
+ };
context: RacpRequestContext;
};
@@ -470,6 +476,7 @@ export class AgentHost {
principalSubject: principal.subject,
content: params.input.text,
...(params.input.sessionMessageId ? { sessionMessageId: params.input.sessionMessageId } : {}),
+ ...(params.input.userMessageId ? { userMessageId: params.input.userMessageId } : {}),
...(params.input.attachments ? { attachments: params.input.attachments } : {}),
effectivePermissionMode,
...(idempotencyKey ? { idempotencyKey } : {}),
@@ -491,6 +498,7 @@ export class AgentHost {
sessionId: state.id,
content: params.input.text,
...(params.input.sessionMessageId ? { sessionMessageId: params.input.sessionMessageId } : {}),
+ ...(params.input.userMessageId ? { userMessageId: params.input.userMessageId } : {}),
...(params.input.attachments ? { attachments: params.input.attachments } : {}),
effectivePermissionMode,
...(idempotencyKey ? { idempotencyKey } : {}),
@@ -681,6 +689,13 @@ export class AgentHost {
return this.approvals.list(sessionId);
}
+ /** The RACP view of a session the caller already fetched: its durable summary plus live state. */
+ describeSession(summary: SessionSummary): RacpSession {
+ const state = this.state(summary.id);
+ state.permissionMode = summary.permissionMode;
+ return this.toRacpSession(summary, state);
+ }
+
queuedTurns(sessionId: string): RacpTurn[] {
return this.queueEntries(sessionId).map((entry) => entry.turn);
}
@@ -798,6 +813,7 @@ export class AgentHost {
sessionId,
content: record.content,
...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),
+ ...(record.userMessageId ? { userMessageId: record.userMessageId } : {}),
...(record.attachments ? { attachments: record.attachments } : {}),
effectivePermissionMode: record.effectivePermissionMode,
...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),
diff --git a/packages/agent-host/src/ports.ts b/packages/agent-host/src/ports.ts
index 0bd4fe7db..b784346ab 100644
--- a/packages/agent-host/src/ports.ts
+++ b/packages/agent-host/src/ports.ts
@@ -78,6 +78,8 @@ export type QueuedTurnRecord = {
principalSubject: string;
content: string;
sessionMessageId?: string;
+ /** Client-chosen id for the durable user row (D288). */
+ userMessageId?: string;
attachments?: AgentPromptAttachment[];
effectivePermissionMode: RacpPermissionMode;
idempotencyKey?: string;
diff --git a/packages/racp/package.json b/packages/racp/package.json
new file mode 100644
index 000000000..11b8c8201
--- /dev/null
+++ b/packages/racp/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@pi-desktop/racp",
+ "version": "0.15.0",
+ "private": true,
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc -p tsconfig.json",
+ "typecheck": "tsc -p tsconfig.json --noEmit",
+ "test": "vitest run",
+ "clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true})\""
+ },
+ "dependencies": {
+ "@pi-desktop/agent-host": "workspace:*",
+ "@pi-desktop/shared": "workspace:*",
+ "typebox": "^1.3.13",
+ "ws": "8.21.1"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "@types/ws": "^8.18.1",
+ "typescript": "^5.9.3",
+ "vitest": "^4.1.10"
+ }
+}
diff --git a/packages/racp/src/auth.ts b/packages/racp/src/auth.ts
new file mode 100644
index 000000000..030a0ed01
--- /dev/null
+++ b/packages/racp/src/auth.ts
@@ -0,0 +1,215 @@
+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
+import { isIP } from "node:net";
+
+import type { Principal } from "@pi-desktop/agent-host";
+import { RACP_DEVICE_TOKEN_PREFIX, RACP_PAIRING_TOKEN_PREFIX, type RacpRole } from "@pi-desktop/shared";
+
+/**
+ * Credentials for the header profile (security §3.1, §3.4). A device token
+ * is the long-lived credential a paired desktop presents on every upgrade; a
+ * pairing token is single-use, expiring, and only good for `connection/pair`.
+ * Neither ever appears in a URL; both are stored hashed on the Host.
+ */
+export type DeviceRecord = {
+ deviceId: string;
+ label: string;
+ roles: RacpRole[];
+ /** SHA-256 of the token, hex. */
+ tokenHash: string;
+ createdAt: string;
+ lastSeenAt?: string;
+ revokedAt?: string;
+};
+
+export type PairingRecord = {
+ tokenHash: string;
+ expiresAt: string;
+ /** Set once exchanged; a second exchange is refused. */
+ consumedAt?: string;
+};
+
+/** Durable credential storage; `pi-host` keeps it under its data directory. */
+export interface DeviceCredentialStore {
+ findDeviceByTokenHash(tokenHash: string): Promise<DeviceRecord | null>;
+ saveDevice(record: DeviceRecord): Promise<void>;
+ touchDevice(deviceId: string, seenAt: string): Promise<void>;
+ revokeDevice(deviceId: string, revokedAt: string): Promise<boolean>;
+ listDevices(): Promise<DeviceRecord[]>;
+ findPairing(tokenHash: string): Promise<PairingRecord | null>;
+ savePairing(record: PairingRecord): Promise<void>;
+ consumePairing(tokenHash: string, consumedAt: string): Promise<boolean>;
+}
+
+export class MemoryCredentialStore implements DeviceCredentialStore {
+ private readonly devices = new Map<string, DeviceRecord>();
+ private readonly pairings = new Map<string, PairingRecord>();
+
+ async findDeviceByTokenHash(tokenHash: string): Promise<DeviceRecord | null> {
+ for (const device of this.devices.values()) {
+ if (device.tokenHash === tokenHash) return device;
+ }
+ return null;
+ }
+ async saveDevice(record: DeviceRecord): Promise<void> {
+ this.devices.set(record.deviceId, record);
+ }
+ async touchDevice(deviceId: string, seenAt: string): Promise<void> {
+ const device = this.devices.get(deviceId);
+ if (device) device.lastSeenAt = seenAt;
+ }
+ async revokeDevice(deviceId: string, revokedAt: string): Promise<boolean> {
+ const device = this.devices.get(deviceId);
+ if (!device || device.revokedAt) return false;
+ device.revokedAt = revokedAt;
+ return true;
+ }
+ async listDevices(): Promise<DeviceRecord[]> {
+ return [...this.devices.values()];
+ }
+ async findPairing(tokenHash: string): Promise<PairingRecord | null> {
+ return this.pairings.get(tokenHash) ?? null;
+ }
+ async savePairing(record: PairingRecord): Promise<void> {
+ this.pairings.set(record.tokenHash, record);
+ }
+ async consumePairing(tokenHash: string, consumedAt: string): Promise<boolean> {
+ const pairing = this.pairings.get(tokenHash);
+ if (!pairing || pairing.consumedAt) return false;
+ pairing.consumedAt = consumedAt;
+ return true;
+ }
+}
+
+export function hashToken(token: string): string {
+ return createHash("sha256").update(token, "utf8").digest("hex");
+}
+
+export function newDeviceToken(): string {
+ return `${RACP_DEVICE_TOKEN_PREFIX}${randomBytes(32).toString("base64url")}`;
+}
+
+export function newPairingToken(): string {
+ return `${RACP_PAIRING_TOKEN_PREFIX}${randomBytes(24).toString("base64url")}`;
+}
+
+export function isDeviceToken(token: string): boolean {
+ return token.startsWith(RACP_DEVICE_TOKEN_PREFIX);
+}
+
+export function isPairingToken(token: string): boolean {
+ return token.startsWith(RACP_PAIRING_TOKEN_PREFIX);
+}
+
+/** Constant-time comparison of two hex digests of equal length. */
+export function hashesEqual(left: string, right: string): boolean {
+ const a = Buffer.from(left, "hex");
+ const b = Buffer.from(right, "hex");
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+/** `Authorization: Bearer <token>`; anything else is not a credential. */
+export function bearerToken(authorization: string | undefined): string | null {
+ if (!authorization) return null;
+ const match = /^Bearer\s+(\S+)$/i.exec(authorization.trim());
+ return match ? match[1]! : null;
+}
+
+export function isLoopbackAddress(address: string | undefined): boolean {
+ if (!address) return false;
+ const bare = address.startsWith("::ffff:") ? address.slice("::ffff:".length) : address;
+ const family = isIP(bare);
+ if (family === 4) return bare.startsWith("127.");
+ if (family === 6) return bare === "::1";
+ return false;
+}
+
+/** What the upgrade handler learned about a connection before any RPC ran. */
+export type ConnectionAuth =
+ | { kind: "device"; principal: Principal; device: DeviceRecord }
+ | { kind: "pairing"; principal: Principal; tokenHash: string };
+
+export type AuthenticateInput = {
+ authorization: string | undefined;
+ /** Rejected outright: a token in the URL is never accepted (security §3.1). */
+ urlHasToken: boolean;
+ connectionId: string;
+};
+
+/**
+ * The header-profile authenticator. A device token yields the device's
+ * principal; a still-valid pairing token yields an unprivileged principal
+ * that may only call `connection/pair`.
+ */
+export class DeviceTokenAuthenticator {
+ constructor(
+ private readonly store: DeviceCredentialStore,
+ private readonly now: () => number = () => Date.now(),
+ ) {}
+
+ async authenticate(input: AuthenticateInput): Promise<ConnectionAuth | null> {
+ if (input.urlHasToken) return null;
+ const token = bearerToken(input.authorization);
+ if (!token) return null;
+ const tokenHash = hashToken(token);
+ if (isDeviceToken(token)) {
+ const device = await this.store.findDeviceByTokenHash(tokenHash);
+ if (!device || device.revokedAt || !hashesEqual(device.tokenHash, tokenHash)) return null;
+ await this.store.touchDevice(device.deviceId, new Date(this.now()).toISOString());
+ return {
+ kind: "device",
+ device,
+ principal: {
+ subject: device.deviceId,
+ roles: [...device.roles],
+ pairedDevice: true,
+ connectionId: input.connectionId,
+ },
+ };
+ }
+ if (isPairingToken(token)) {
+ const pairing = await this.store.findPairing(tokenHash);
+ if (!pairing || pairing.consumedAt || Date.parse(pairing.expiresAt) <= this.now()) return null;
+ return {
+ kind: "pairing",
+ tokenHash,
+ principal: { subject: `pairing:${tokenHash.slice(0, 12)}`, roles: [], connectionId: input.connectionId },
+ };
+ }
+ return null;
+ }
+
+ /** Mint a single-use pairing token; the caller hands it over the bootstrap channel. */
+ async issuePairingToken(lifetimeMs: number): Promise<{ token: string; expiresAt: string }> {
+ const token = newPairingToken();
+ const expiresAt = new Date(this.now() + lifetimeMs).toISOString();
+ await this.store.savePairing({ tokenHash: hashToken(token), expiresAt });
+ return { token, expiresAt };
+ }
+
+ /** Exchange a pairing token (already authenticated on the upgrade) for a device credential. */
+ async pair(tokenHash: string, label: string, roles: RacpRole[]): Promise<{ deviceId: string; token: string }> {
+ const consumedAt = new Date(this.now()).toISOString();
+ const pairing = await this.store.findPairing(tokenHash);
+ if (!pairing) throw pairingError("PAIRING_FAILED", "the pairing token is unknown");
+ if (Date.parse(pairing.expiresAt) <= this.now()) {
+ throw pairingError("PAIRING_TOKEN_EXPIRED", "the pairing token has expired");
+ }
+ if (!(await this.store.consumePairing(tokenHash, consumedAt))) {
+ throw pairingError("PAIRING_FAILED", "the pairing token was already used");
+ }
+ const token = newDeviceToken();
+ const deviceId = `dev_${randomBytes(9).toString("base64url")}`;
+ await this.store.saveDevice({
+ deviceId,
+ label,
+ roles,
+ tokenHash: hashToken(token),
+ createdAt: consumedAt,
+ });
+ return { deviceId, token };
+ }
+}
+
+function pairingError(code: string, message: string): Error & { errorCode: string } {
+ return Object.assign(new Error(message), { errorCode: code });
+}
diff --git a/packages/racp/src/client.ts b/packages/racp/src/client.ts
new file mode 100644
index 000000000..031479770
--- /dev/null
+++ b/packages/racp/src/client.ts
@@ -0,0 +1,298 @@
+import { RacpError } from "@pi-desktop/agent-host";
+import {
+ RACP_EVENT_NOTIFICATION,
+ RACP_INITIALIZED_NOTIFICATION,
+ RACP_PROTOCOL_VERSION,
+ RACP_SUBSCRIPTION_CLOSED_NOTIFICATION,
+ isDurableEventKind,
+ type RacpCursor,
+ type RacpEventEnvelope,
+ type RacpInitializeParams,
+ type RacpInitializeResult,
+ type RacpRemoteError,
+} from "@pi-desktop/shared";
+
+import {
+ encodeFrame,
+ errorFromObject,
+ isNotification,
+ isRequest,
+ isResponse,
+ parseFrame,
+ type JsonRpcId,
+} from "./jsonrpc.js";
+
+/** One client-side transport connection: the thing `ws` (or a test pair) provides. */
+export interface ClientTransport {
+ send(frame: string): void;
+ close(code?: number, reason?: string): void;
+ onMessage(handler: (frame: string) => void): void;
+ onClose(handler: (info: { code: number; reason: string }) => void): void;
+ onError(handler: (error: Error) => void): void;
+}
+
+/** Opens a transport; rejects with a typed error when the connection cannot be made. */
+export type ClientTransportFactory = () => Promise<ClientTransport>;
+
+export type RacpClientState = "disconnected" | "connecting" | "connected" | "reconnecting" | "error";
+
+export type SubscriptionClosedNotice = {
+ subscriptionId: string;
+ error: RacpRemoteError;
+ lastSafeCursor: RacpCursor;
+};
+
+export type RacpClientOptions = {
+ transport: ClientTransportFactory;
+ client: { name: string; version: string };
+ /** Answer a server-initiated request (`approval/request`, `input/request`, `tool/execute`). */
+ onServerRequest?: (method: string, params: unknown) => Promise<unknown>;
+ onEvent?: (envelope: RacpEventEnvelope) => void;
+ onSubscriptionClosed?: (notice: SubscriptionClosedNotice) => void;
+ onStateChange?: (state: RacpClientState, error?: RacpError) => void;
+ /** Re-establish subscriptions after a reconnect. */
+ onReconnected?: (client: RacpClient) => Promise<void> | void;
+ log?: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;
+ requestTimeoutMs?: number;
+ reconnect?: { enabled: boolean; baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number };
+ sleep?: (ms: number) => Promise<void>;
+};
+
+type Pending = {
+ resolve: (value: unknown) => void;
+ reject: (error: RacpError) => void;
+ timer: ReturnType<typeof setTimeout>;
+ method: string;
+};
+
+/**
+ * The `RACP-WS` client core. Requests are correlated by id, server requests
+ * are answered through `onServerRequest`, and a dropped transport reconnects
+ * with bounded backoff. Reconnect never re-sends an in-flight mutation: the
+ * pending calls of the old connection are rejected with `HOST_DISCONNECTED`,
+ * and the caller retries with the same idempotency key if it wants to (spec
+ * §4.1, §10). Durable events are tracked per session so a subscription can
+ * resume from its last cursor.
+ */
+export class RacpClient {
+ private transport: ClientTransport | null = null;
+ private pending = new Map<string, Pending>();
+ private counter = 0;
+ private stateValue: RacpClientState = "disconnected";
+ private closedByUser = false;
+ private reconnectAttempt = 0;
+ private reconnecting: Promise<void> | null = null;
+ private initializeResult: RacpInitializeResult | null = null;
+ private readonly cursors = new Map<string, RacpCursor>();
+ private hostCursor: RacpCursor | null = null;
+
+ constructor(private readonly options: RacpClientOptions) {}
+
+ get state(): RacpClientState {
+ return this.stateValue;
+ }
+
+ get initialized(): RacpInitializeResult | null {
+ return this.initializeResult;
+ }
+
+ /** Last durable cursor seen for a session, for `after` on resubscribe. */
+ cursorFor(sessionId: string): RacpCursor | undefined {
+ return this.cursors.get(sessionId);
+ }
+
+ cursorForHost(): RacpCursor | undefined {
+ return this.hostCursor ?? undefined;
+ }
+
+ async connect(): Promise<RacpInitializeResult> {
+ this.closedByUser = false;
+ this.setState("connecting");
+ try {
+ const result = await this.open();
+ this.reconnectAttempt = 0;
+ this.setState("connected");
+ return result;
+ } catch (error) {
+ const typed = toRacpError(error, "REMOTE_CONNECTION_FAILED");
+ this.setState("error", typed);
+ throw typed;
+ }
+ }
+
+ async close(): Promise<void> {
+ this.closedByUser = true;
+ const transport = this.transport;
+ this.transport = null;
+ this.rejectPending(new RacpError("HOST_DISCONNECTED", "client closed"));
+ transport?.close(1000, "client closed");
+ this.setState("disconnected");
+ }
+
+ request<T = unknown>(method: string, params?: unknown): Promise<T> {
+ const transport = this.transport;
+ if (!transport || this.stateValue !== "connected") {
+ return Promise.reject(new RacpError("HOST_DISCONNECTED", `not connected (${this.stateValue})`, { retriable: true }));
+ }
+ return this.send<T>(transport, method, params);
+ }
+
+ private send<T>(transport: ClientTransport, method: string, params: unknown): Promise<T> {
+ this.counter += 1;
+ const id = `c${this.counter}`;
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new RacpError("TIMEOUT", `${method} timed out`, { retriable: true }));
+ }, this.options.requestTimeoutMs ?? 15_000);
+ timer.unref?.();
+ this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer, method });
+ try {
+ transport.send(encodeFrame({ jsonrpc: "2.0", id, method, params }));
+ } catch (error) {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(toRacpError(error, "HOST_DISCONNECTED"));
+ }
+ });
+ }
+
+ private async open(): Promise<RacpInitializeResult> {
+ const transport = await this.options.transport();
+ this.transport = transport;
+ transport.onMessage((frame) => this.handleFrame(transport, frame));
+ transport.onError((error) => this.options.log?.("warn", "racp transport error", { error: String(error) }));
+ transport.onClose((info) => this.handleClose(transport, info));
+ const params: RacpInitializeParams = {
+ protocolVersion: RACP_PROTOCOL_VERSION,
+ client: this.options.client,
+ bindings: ["RACP-WS"],
+ capabilities: { eventReplay: true, approvals: true, inputRequests: true, turnQueue: true, hostEvents: true, history: true, terminal: true },
+ };
+ const result = await this.send<RacpInitializeResult>(transport, "connection/initialize", params);
+ transport.send(encodeFrame({ jsonrpc: "2.0", method: RACP_INITIALIZED_NOTIFICATION, params: {} }));
+ this.initializeResult = result;
+ return result;
+ }
+
+ private handleFrame(transport: ClientTransport, frame: string): void {
+ if (transport !== this.transport) return;
+ const message = parseFrame(frame);
+ if (!message) return;
+ if (isResponse(message)) {
+ const pending = this.pending.get(String(message.id));
+ if (!pending) return;
+ this.pending.delete(String(message.id));
+ clearTimeout(pending.timer);
+ if (message.error) pending.reject(errorFromObject(message.error));
+ else pending.resolve(message.result);
+ return;
+ }
+ if (isRequest(message)) {
+ void this.answerServerRequest(transport, message.id, message.method, message.params);
+ return;
+ }
+ if (!isNotification(message)) return;
+ if (message.method === RACP_EVENT_NOTIFICATION) {
+ const envelope = message.params as RacpEventEnvelope;
+ this.track(envelope);
+ this.options.onEvent?.(envelope);
+ } else if (message.method === RACP_SUBSCRIPTION_CLOSED_NOTIFICATION) {
+ this.options.onSubscriptionClosed?.(message.params as SubscriptionClosedNotice);
+ }
+ }
+
+ private track(envelope: RacpEventEnvelope): void {
+ if (!isDurableEventKind(envelope.kind) || typeof envelope.sequence !== "number") return;
+ const cursor = { epoch: envelope.epoch, sequence: envelope.sequence };
+ if (envelope.scope === "host") this.hostCursor = cursor;
+ else if (envelope.sessionId) this.cursors.set(envelope.sessionId, cursor);
+ }
+
+ private async answerServerRequest(transport: ClientTransport, id: JsonRpcId, method: string, params: unknown): Promise<void> {
+ const handler = this.options.onServerRequest;
+ let response: string;
+ if (!handler) {
+ response = encodeFrame({
+ jsonrpc: "2.0",
+ id,
+ error: { code: -32601, message: "server requests are not handled", data: { code: "METHOD_NOT_FOUND", message: "unhandled", retriable: false, traceId: "" } },
+ });
+ } else {
+ try {
+ response = encodeFrame({ jsonrpc: "2.0", id, result: await handler(method, params) });
+ } catch (error) {
+ const typed = toRacpError(error, "TOOL_FAILED");
+ response = encodeFrame({ jsonrpc: "2.0", id, error: { code: -32000, message: typed.message, data: typed.toRemoteError("") } });
+ }
+ }
+ if (transport === this.transport) transport.send(response);
+ }
+
+ private handleClose(transport: ClientTransport, info: { code: number; reason: string }): void {
+ if (transport !== this.transport) return;
+ this.transport = null;
+ this.rejectPending(new RacpError("HOST_DISCONNECTED", `connection closed (${info.code} ${info.reason})`, { retriable: true }));
+ if (this.closedByUser) {
+ this.setState("disconnected");
+ return;
+ }
+ const policy = this.options.reconnect;
+ if (!policy?.enabled) {
+ this.setState("disconnected", new RacpError("HOST_DISCONNECTED", `connection closed (${info.code} ${info.reason})`, { retriable: true }));
+ return;
+ }
+ this.setState("reconnecting");
+ this.reconnecting ??= this.reconnectLoop().finally(() => {
+ this.reconnecting = null;
+ });
+ }
+
+ private async reconnectLoop(): Promise<void> {
+ const policy = this.options.reconnect!;
+ const sleep = this.options.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
+ while (!this.closedByUser) {
+ this.reconnectAttempt += 1;
+ if (policy.maxAttempts !== undefined && this.reconnectAttempt > policy.maxAttempts) {
+ this.setState("error", new RacpError("HOST_DISCONNECTED", "reconnect attempts exhausted", { retriable: true }));
+ return;
+ }
+ const delay = Math.min((policy.baseDelayMs ?? 500) * 2 ** (this.reconnectAttempt - 1), policy.maxDelayMs ?? 15_000);
+ await sleep(delay);
+ if (this.closedByUser) return;
+ try {
+ await this.open();
+ this.reconnectAttempt = 0;
+ this.setState("connected");
+ await this.options.onReconnected?.(this);
+ return;
+ } catch (error) {
+ this.options.log?.("warn", "racp reconnect failed", { attempt: this.reconnectAttempt, error: String(error) });
+ this.transport = null;
+ }
+ }
+ }
+
+ private rejectPending(error: RacpError): void {
+ for (const pending of this.pending.values()) {
+ clearTimeout(pending.timer);
+ pending.reject(error);
+ }
+ this.pending.clear();
+ }
+
+ private setState(state: RacpClientState, error?: RacpError): void {
+ this.stateValue = state;
+ try {
+ this.options.onStateChange?.(state, error);
+ } catch {
+ // A listener failure must not affect the connection.
+ }
+ }
+}
+
+function toRacpError(error: unknown, fallbackCode: string): RacpError {
+ if (error instanceof RacpError) return error;
+ const code = (error as { errorCode?: string })?.errorCode ?? fallbackCode;
+ return new RacpError(code, error instanceof Error ? error.message : String(error), { retriable: true });
+}
diff --git a/packages/racp/src/host-operations.ts b/packages/racp/src/host-operations.ts
new file mode 100644
index 000000000..4a0691557
--- /dev/null
+++ b/packages/racp/src/host-operations.ts
@@ -0,0 +1,89 @@
+import type { Principal, SessionSummary } from "@pi-desktop/agent-host";
+import type {
+ FsEntry,
+ FsReadResult,
+ RacpProjectSummary,
+ WorkspaceDiff,
+} from "@pi-desktop/shared";
+
+/**
+ * Everything the RACP server delegates to the Host besides the Agent Host
+ * module: session catalog mutations, projects, workspace reads, terminals.
+ * `pi-host` implements these on host-core and its filesystem; a test hands
+ * the server fakes. The server itself never touches host-core RPC, a
+ * filesystem, or a pty, so the boundary of security §7 holds by construction.
+ */
+export type SessionCreateInput = {
+ title?: string;
+ projectId?: string;
+ mode?: "agent" | "plan" | "goal";
+ providerId?: string;
+ modelId?: string;
+ thinkingLevel?: string;
+ permissionMode?: "ask" | "accept-edits" | "auto";
+};
+
+export type SessionConfigureInput = {
+ mode?: "agent" | "plan" | "goal";
+ providerId?: string;
+ modelId?: string;
+ thinkingLevel?: string;
+ permissionMode?: "ask" | "accept-edits" | "auto";
+};
+
+export interface RacpSessionCatalog {
+ list(): Promise<SessionSummary[]>;
+ create(input: SessionCreateInput, principal: Principal): Promise<SessionSummary>;
+ configure(sessionId: string, input: SessionConfigureInput): Promise<SessionSummary>;
+ fork(sessionId: string, input: { title?: string; throughMessageId?: string }): Promise<SessionSummary>;
+ rename(sessionId: string, title: string): Promise<void>;
+ delete(sessionId: string): Promise<void>;
+ compact(sessionId: string): Promise<{ accepted: boolean }>;
+}
+
+export type ProjectBrowseEntry = { name: string; path: string };
+
+export interface RacpProjectCatalog {
+ list(): Promise<RacpProjectSummary[]>;
+ /** Canonicalize and validate a Host directory, register it, return its id. */
+ register(path: string): Promise<RacpProjectSummary & { path: string }>;
+ /** Directories under `path` (or the user's home when omitted), bounded. */
+ browse(path?: string): Promise<{ path: string; parent?: string; entries: ProjectBrowseEntry[] }>;
+}
+
+export interface RacpWorkspaceAccess {
+ list(sessionId: string, path: string): Promise<{ entries: FsEntry[] }>;
+ read(sessionId: string, path: string): Promise<FsReadResult>;
+ diff(sessionId: string): Promise<WorkspaceDiff>;
+}
+
+export type TerminalOpenResult = {
+ terminalId: string;
+ /** Bounded replay ring, base64 (spec §6.2). */
+ replay: string;
+ cols: number;
+ rows: number;
+};
+
+export interface RacpTerminalAccess {
+ open(
+ sessionId: string,
+ options: { cols: number; rows: number },
+ sink: { output: (data: string) => void; exit: (code: number | null) => void },
+ ): Promise<TerminalOpenResult>;
+ input(terminalId: string, data: string): Promise<void>;
+ resize(terminalId: string, cols: number, rows: number): Promise<void>;
+ close(terminalId: string): Promise<void>;
+ /** Re-attach a subscriber after a reconnect; returns the replay ring. */
+ attach(terminalId: string, sink: { output: (data: string) => void; exit: (code: number | null) => void }): Promise<TerminalOpenResult | null>;
+ detach(terminalId: string): void;
+}
+
+export type RacpHostOperations = {
+ sessions: RacpSessionCatalog;
+ projects: RacpProjectCatalog;
+ workspace: RacpWorkspaceAccess;
+ terminal?: RacpTerminalAccess;
+ /** Owner-only: revoke a paired device (spec `session/revoke`). */
+ revokeDevice?: (deviceId: string) => Promise<boolean>;
+};
diff --git a/packages/racp/src/index.ts b/packages/racp/src/index.ts
new file mode 100644
index 000000000..a66bd37be
--- /dev/null
+++ b/packages/racp/src/index.ts
@@ -0,0 +1,7 @@
+export * from "./jsonrpc.js";
+export * from "./auth.js";
+export * from "./host-operations.js";
+export * from "./server.js";
+export * from "./client.js";
+export * from "./ws-binding.js";
+export type { OperationContext, OperationHandler } from "./operations.js";
diff --git a/packages/racp/src/jsonrpc.ts b/packages/racp/src/jsonrpc.ts
new file mode 100644
index 000000000..d850f3dd9
--- /dev/null
+++ b/packages/racp/src/jsonrpc.ts
@@ -0,0 +1,119 @@
+import { RacpError } from "@pi-desktop/agent-host";
+import type { RacpRemoteError } from "@pi-desktop/shared";
+
+/**
+ * JSON-RPC 2.0 framing for `RACP-WS` (spec §4.1): one UTF-8 message per text
+ * frame, no batches, and every failure carries a `RemoteError` under
+ * `error.data` so the code means the same thing on both sides.
+ */
+export type JsonRpcId = string | number;
+
+export type JsonRpcRequest = {
+ jsonrpc: "2.0";
+ id: JsonRpcId;
+ method: string;
+ params?: unknown;
+};
+
+export type JsonRpcNotification = {
+ jsonrpc: "2.0";
+ method: string;
+ params?: unknown;
+};
+
+export type JsonRpcErrorObject = {
+ code: number;
+ message: string;
+ data?: RacpRemoteError;
+};
+
+export type JsonRpcResponse = {
+ jsonrpc: "2.0";
+ id: JsonRpcId;
+ result?: unknown;
+ error?: JsonRpcErrorObject;
+};
+
+export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcResponse;
+
+/** Numeric JSON-RPC codes; the semantic code is the `RemoteError.code`. */
+export const JSON_RPC_CODES = {
+ parseError: -32700,
+ invalidRequest: -32600,
+ methodNotFound: -32601,
+ invalidParams: -32602,
+ application: -32000,
+} as const;
+
+export function isRequest(message: JsonRpcMessage): message is JsonRpcRequest {
+ return "method" in message && "id" in message && message.id !== undefined && message.id !== null;
+}
+
+export function isNotification(message: JsonRpcMessage): message is JsonRpcNotification {
+ return "method" in message && !("id" in message && message.id !== undefined && message.id !== null);
+}
+
+export function isResponse(message: JsonRpcMessage): message is JsonRpcResponse {
+ return !("method" in message) && "id" in message;
+}
+
+/** Parse one frame; anything that is not a single JSON-RPC 2.0 object is rejected. */
+export function parseFrame(text: string): JsonRpcMessage | null {
+ let value: unknown;
+ try {
+ value = JSON.parse(text);
+ } catch {
+ return null;
+ }
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ if (record.jsonrpc !== "2.0") return null;
+ const hasMethod = typeof record.method === "string";
+ const hasId = typeof record.id === "string" || typeof record.id === "number";
+ if (hasMethod) return record as unknown as JsonRpcRequest | JsonRpcNotification;
+ if (hasId && ("result" in record || "error" in record)) return record as unknown as JsonRpcResponse;
+ return null;
+}
+
+export function encodeFrame(message: JsonRpcMessage): string {
+ return JSON.stringify(message);
+}
+
+function numericCodeFor(code: string): number {
+ if (code === "METHOD_NOT_FOUND") return JSON_RPC_CODES.methodNotFound;
+ if (code === "INVALID_ARGUMENT") return JSON_RPC_CODES.invalidParams;
+ return JSON_RPC_CODES.application;
+}
+
+/** Turn any thrown value into the wire error; unknown failures become `INTERNAL`. */
+export function errorObjectFrom(error: unknown, traceId: string): JsonRpcErrorObject {
+ if (error instanceof RacpError) {
+ return { code: numericCodeFor(error.code), message: error.message, data: error.toRemoteError(traceId) };
+ }
+ const candidate = error as { errorCode?: unknown; code?: unknown; message?: unknown; retriable?: unknown } | null;
+ const code =
+ typeof candidate?.errorCode === "string"
+ ? candidate.errorCode
+ : typeof candidate?.code === "string"
+ ? candidate.code
+ : "INTERNAL";
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ code: numericCodeFor(code),
+ message,
+ data: { code, message, retriable: candidate?.retriable === true, traceId },
+ };
+}
+
+/** The client-side view of a wire error: a `RacpError` with the remote code. */
+export function errorFromObject(error: JsonRpcErrorObject): RacpError {
+ const remote = error.data;
+ if (remote && typeof remote.code === "string") {
+ return new RacpError(remote.code, remote.message || error.message, {
+ retriable: remote.retriable,
+ details: { ...(remote.details === undefined ? {} : { details: remote.details }), traceId: remote.traceId },
+ });
+ }
+ const code = error.code === JSON_RPC_CODES.methodNotFound ? "METHOD_NOT_FOUND" : "INTERNAL";
+ return new RacpError(code, error.message);
+}
diff --git a/packages/racp/src/operations.ts b/packages/racp/src/operations.ts
new file mode 100644
index 000000000..c7f3473ed
--- /dev/null
+++ b/packages/racp/src/operations.ts
@@ -0,0 +1,391 @@
+import type { AgentHost, Principal } from "@pi-desktop/agent-host";
+import { RacpError } from "@pi-desktop/agent-host";
+import {
+ RacpApprovalResponseSchema,
+ RacpCursorSchema,
+ RacpInputResponseSchema,
+ RacpRequestContextSchema,
+ type RacpCursor,
+ type RacpLimits,
+ type RacpOperation,
+ type RacpServerCapabilities,
+ type RacpEventEnvelope,
+} from "@pi-desktop/shared";
+import Type from "typebox";
+import * as Value from "typebox/value";
+
+import type { DeviceTokenAuthenticator } from "./auth.js";
+import type { RacpHostOperations } from "./host-operations.js";
+import type { RacpConnection } from "./server.js";
+
+export type OperationContext = {
+ connection: RacpConnection;
+ principal: Principal;
+ agentHost: AgentHost;
+ operations: RacpHostOperations;
+ authenticator: DeviceTokenAuthenticator;
+ limits: RacpLimits;
+ capabilities: RacpServerCapabilities;
+ traceId: string;
+ now: () => number;
+ deliverEvent: (envelope: RacpEventEnvelope) => void;
+ closeSubscription: (subscriptionId: string, error: RacpError, lastSafeCursor: RacpCursor) => void;
+ log: (level: "info" | "warn" | "error", message: string, data?: Record<string, unknown>) => void;
+};
+
+export type OperationHandler = (context: OperationContext, params: Record<string, unknown>) => Promise<unknown>;
+
+const SessionIdParams = Type.Object({ sessionId: Type.String({ minLength: 1 }) });
+const TurnIdParams = Type.Object({ turnId: Type.String({ minLength: 1 }) });
+const AttachParams = Type.Object({
+ sessionId: Type.String({ minLength: 1 }),
+ role: Type.Optional(Type.Union([Type.Literal("viewer"), Type.Literal("controller"), Type.Literal("approver"), Type.Literal("owner")])),
+ after: Type.Optional(RacpCursorSchema),
+ includeSnapshot: Type.Optional(Type.Boolean()),
+});
+const SubscribeParams = Type.Object({
+ scope: Type.Union([Type.Literal("session"), Type.Literal("host")]),
+ sessionId: Type.Optional(Type.String({ minLength: 1 })),
+ after: Type.Optional(RacpCursorSchema),
+});
+const TurnStartParams = Type.Object({
+ sessionId: Type.String({ minLength: 1 }),
+ idempotencyKey: Type.Optional(Type.String({ minLength: 1 })),
+ admission: Type.Optional(Type.Union([Type.Literal("reject_if_busy"), Type.Literal("queue")])),
+ input: Type.Object({
+ text: Type.String(),
+ attachments: Type.Optional(Type.Array(Type.Unknown())),
+ sessionMessageId: Type.Optional(Type.String()),
+ /** Client-chosen id for the durable user row (D288). */
+ messageId: Type.Optional(Type.String()),
+ }),
+ context: RacpRequestContextSchema,
+});
+const HistoryParams = Type.Object({
+ sessionId: Type.String({ minLength: 1 }),
+ beforeItemId: Type.Optional(Type.String()),
+ limit: Type.Optional(Type.Integer({ minimum: 1 })),
+});
+const SessionCreateParams = Type.Object({
+ title: Type.Optional(Type.String()),
+ projectId: Type.Optional(Type.String()),
+ mode: Type.Optional(Type.Union([Type.Literal("agent"), Type.Literal("plan"), Type.Literal("goal")])),
+ providerId: Type.Optional(Type.String()),
+ modelId: Type.Optional(Type.String()),
+ thinkingLevel: Type.Optional(Type.String()),
+ permissionMode: Type.Optional(Type.Union([Type.Literal("ask"), Type.Literal("accept-edits"), Type.Literal("auto")])),
+});
+const SessionConfigureParams = Type.Object({
+ sessionId: Type.String({ minLength: 1 }),
+ mode: Type.Optional(Type.Union([Type.Literal("agent"), Type.Literal("plan"), Type.Literal("goal")])),
+ providerId: Type.Optional(Type.String()),
+ modelId: Type.Optional(Type.String()),
+ thinkingLevel: Type.Optional(Type.String()),
+ permissionMode: Type.Optional(Type.Union([Type.Literal("ask"), Type.Literal("accept-edits"), Type.Literal("auto")])),
+});
+const WorkspacePathParams = Type.Object({ sessionId: Type.String({ minLength: 1 }), path: Type.Optional(Type.String()) });
+const TerminalOpenParams = Type.Object({
+ sessionId: Type.String({ minLength: 1 }),
+ cols: Type.Optional(Type.Integer({ minimum: 1, maximum: 1000 })),
+ rows: Type.Optional(Type.Integer({ minimum: 1, maximum: 1000 })),
+ /** Re-attach to a terminal this session already has open. */
+ terminalId: Type.Optional(Type.String({ minLength: 1 })),
+});
+const TerminalInputParams = Type.Object({ terminalId: Type.String({ minLength: 1 }), data: Type.String() });
+const TerminalResizeParams = Type.Object({
+ terminalId: Type.String({ minLength: 1 }),
+ cols: Type.Integer({ minimum: 1, maximum: 1000 }),
+ rows: Type.Integer({ minimum: 1, maximum: 1000 }),
+});
+const TerminalIdParams = Type.Object({ terminalId: Type.String({ minLength: 1 }) });
+const PairParams = Type.Object({ deviceLabel: Type.Optional(Type.String()) });
+
+function check<T extends Type.TSchema>(schema: T, params: unknown): Type.Static<T> {
+ if (!Value.Check(schema, params)) {
+ const first = Value.Errors(schema, params)[Symbol.iterator]().next().value as { path?: string; message?: string } | undefined;
+ throw new RacpError("INVALID_ARGUMENT", `invalid params${first?.path ? ` at ${first.path}` : ""}: ${first?.message ?? "schema mismatch"}`);
+ }
+ return params;
+}
+
+function requireTerminal(context: OperationContext) {
+ const terminal = context.operations.terminal;
+ if (!terminal || !context.capabilities.terminal) {
+ throw new RacpError("CAPABILITY_UNAVAILABLE", "this Host does not offer terminals");
+ }
+ return terminal;
+}
+
+function unavailable(capability: string): OperationHandler {
+ return async () => {
+ throw new RacpError("CAPABILITY_UNAVAILABLE", `${capability} is not offered by this Host`);
+ };
+}
+
+/** The operation catalog bound to the Agent Host module and the Host operations. */
+export function createOperations(): Map<RacpOperation, OperationHandler> {
+ const handlers = new Map<RacpOperation, OperationHandler>();
+
+ handlers.set("connection/initialize", async () => {
+ throw new RacpError("CONFLICT", "the connection is already initialized");
+ });
+ handlers.set("connection/ping", async (context) => ({ ok: true, serverTime: new Date(context.now()).toISOString() }));
+ handlers.set("connection/pair", async (context, params) => {
+ const input = check(PairParams, params);
+ if (context.connection.auth.kind !== "pairing") {
+ throw new RacpError("FORBIDDEN", "connection/pair needs a pairing token on the upgrade request");
+ }
+ const paired = await context.authenticator.pair(
+ context.connection.auth.tokenHash,
+ input.deviceLabel?.trim() || "desktop",
+ ["owner"],
+ ).catch((error: unknown) => {
+ const code = (error as { errorCode?: string })?.errorCode;
+ if (code === "PAIRING_FAILED" || code === "PAIRING_TOKEN_EXPIRED") {
+ throw new RacpError(code, error instanceof Error ? error.message : String(error));
+ }
+ throw error;
+ });
+ context.log("info", "device paired", { deviceId: paired.deviceId, connectionId: context.connection.id });
+ // The pairing connection stays unprivileged: the client reconnects with the device token.
+ return { deviceId: paired.deviceId, deviceToken: paired.token, roles: ["owner"] };
+ });
+ handlers.set("host/list", async () => {
+ throw new RacpError("METHOD_NOT_FOUND", "host/list exists only behind a Gateway");
+ });
+
+ handlers.set("project/list", async (context) => ({ projects: await context.operations.projects.list() }));
+ handlers.set("project/register", async (context, params) => {
+ const input = check(Type.Object({ path: Type.String({ minLength: 1 }) }), params);
+ const project = await context.operations.projects.register(input.path);
+ return { project };
+ });
+ handlers.set("project/browse", async (context, params) => {
+ const input = check(Type.Object({ path: Type.Optional(Type.String()) }), params);
+ return context.operations.projects.browse(input.path);
+ });
+
+ handlers.set("session/list", async (context) => {
+ const sessions = await context.operations.sessions.list();
+ return { sessions: sessions.map((summary) => context.agentHost.describeSession(summary)) };
+ });
+ handlers.set("session/get", async (context, params) => {
+ const input = check(SessionIdParams, params);
+ const summary = (await context.operations.sessions.list()).find((candidate) => candidate.id === input.sessionId);
+ if (!summary) throw new RacpError("NOT_FOUND", `session ${input.sessionId} is unknown`);
+ return { session: context.agentHost.describeSession(summary) };
+ });
+ handlers.set("session/create", async (context, params) => {
+ const input = check(SessionCreateParams, params);
+ const summary = await context.operations.sessions.create(input, context.principal);
+ context.agentHost.publishSessionChange("session.created", summary);
+ return { session: context.agentHost.describeSession(summary) };
+ });
+ handlers.set("session/attach", async (context, params) => {
+ const input = check(AttachParams, params);
+ return context.agentHost.attach(context.principal, {
+ sessionId: input.sessionId,
+ ...(input.role ? { role: input.role } : {}),
+ ...(input.after ? { after: input.after } : {}),
+ ...(input.includeSnapshot !== undefined ? { includeSnapshot: input.includeSnapshot } : {}),
+ });
+ });
+ handlers.set("session/history", async (context, params) => {
+ const input = check(HistoryParams, params);
+ return context.agentHost.history(context.principal, input);
+ });
+
+ handlers.set("events/subscribe", async (context, params) => {
+ const input = check(SubscribeParams, params);
+ if (context.connection.subscriptions.size >= context.limits.maxSubscriptionsPerConnection) {
+ throw new RacpError("RATE_LIMITED", "subscription limit reached for this connection", {
+ details: { limit: context.limits.maxSubscriptionsPerConnection },
+ });
+ }
+ const result = context.agentHost.subscribe(
+ context.principal,
+ { scope: input.scope, ...(input.sessionId ? { sessionId: input.sessionId } : {}), ...(input.after ? { after: input.after } : {}) },
+ {
+ deliver: (envelope) => context.deliverEvent(envelope),
+ close: (error, lastSafeCursor) => context.closeSubscription(result.subscriptionId, error, lastSafeCursor),
+ },
+ );
+ context.connection.subscriptions.set(result.subscriptionId, {
+ id: result.subscriptionId,
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
+ });
+ return result;
+ });
+ handlers.set("events/unsubscribe", async (context, params) => {
+ const input = check(Type.Object({ subscriptionId: Type.String({ minLength: 1 }) }), params);
+ const subscription = context.connection.subscriptions.get(input.subscriptionId);
+ if (!subscription) return { removed: false };
+ context.connection.subscriptions.delete(input.subscriptionId);
+ return { removed: context.agentHost.unsubscribe(subscription.id, subscription.sessionId) };
+ });
+ handlers.set("events/ack", async (context, params) => {
+ const input = check(Type.Object({ subscriptionId: Type.String({ minLength: 1 }), sequence: Type.Integer({ minimum: 0 }) }), params);
+ if (context.connection.subscriptions.has(input.subscriptionId)) {
+ context.agentHost.ack(input.subscriptionId, input.sequence);
+ }
+ return { ok: true };
+ });
+
+ handlers.set("turn/start", async (context, params) => {
+ const input = check(TurnStartParams, params);
+ if (Buffer.byteLength(input.input.text, "utf8") > context.limits.maxPromptBytes) {
+ throw new RacpError("PAYLOAD_TOO_LARGE", "prompt exceeds maxPromptBytes");
+ }
+ if (input.input.attachments?.length) {
+ throw new RacpError("CAPABILITY_UNAVAILABLE", "attachments are not offered by this Host");
+ }
+ return context.agentHost.startTurn(context.principal, {
+ sessionId: input.sessionId,
+ ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),
+ ...(input.admission ? { admission: input.admission } : {}),
+ input: {
+ text: input.input.text,
+ ...(input.input.sessionMessageId ? { sessionMessageId: input.input.sessionMessageId } : {}),
+ ...(input.input.messageId ? { userMessageId: input.input.messageId } : {}),
+ },
+ context: input.context,
+ });
+ });
+ handlers.set("turn/get", async (context, params) => ({ turn: context.agentHost.getTurn(check(TurnIdParams, params).turnId) }));
+ handlers.set("turn/stop", async (context, params) => ({
+ turn: await context.agentHost.stopTurn(context.principal, check(TurnIdParams, params).turnId),
+ }));
+ handlers.set("turn/interrupt", async (context, params) => ({
+ turn: await context.agentHost.interruptTurn(context.principal, check(TurnIdParams, params).turnId),
+ }));
+ handlers.set("turn/cancel", async (context, params) => ({
+ turn: await context.agentHost.cancelTurn(context.principal, check(TurnIdParams, params).turnId),
+ }));
+ handlers.set("turn/prioritize", async (context, params) => ({
+ turn: await context.agentHost.prioritizeTurn(context.principal, check(TurnIdParams, params).turnId),
+ }));
+
+ handlers.set("approval/respond", async (context, params) =>
+ context.agentHost.respondApproval(context.principal, check(RacpApprovalResponseSchema, params)),
+ );
+ handlers.set("input/respond", async (context, params) =>
+ context.agentHost.respondInput(context.principal, check(RacpInputResponseSchema, params)),
+ );
+
+ handlers.set("attachment/create", unavailable("attachments"));
+ handlers.set("attachment/complete", unavailable("attachments"));
+ handlers.set("tools/advertise", unavailable("tool relay"));
+
+ handlers.set("session/revoke", async (context, params) => {
+ const input = check(Type.Object({ deviceId: Type.String({ minLength: 1 }) }), params);
+ const revoke = context.operations.revokeDevice;
+ if (!revoke) throw new RacpError("CAPABILITY_UNAVAILABLE", "device revocation is not offered by this Host");
+ return { revoked: await revoke(input.deviceId) };
+ });
+ handlers.set("session/archive", unavailable("session archival"));
+
+ handlers.set("session/configure", async (context, params) => {
+ const { sessionId, ...input } = check(SessionConfigureParams, params);
+ const summary = await context.operations.sessions.configure(sessionId, input);
+ context.agentHost.publishSessionChange("session.changed", summary);
+ return { session: context.agentHost.describeSession(summary) };
+ });
+ handlers.set("session/fork", async (context, params) => {
+ const input = check(Type.Object({ sessionId: Type.String({ minLength: 1 }), title: Type.Optional(Type.String()), throughMessageId: Type.Optional(Type.String()) }), params);
+ const summary = await context.operations.sessions.fork(input.sessionId, input);
+ context.agentHost.publishSessionChange("session.created", summary);
+ return { session: context.agentHost.describeSession(summary) };
+ });
+ handlers.set("session/rename", async (context, params) => {
+ const input = check(Type.Object({ sessionId: Type.String({ minLength: 1 }), title: Type.String({ minLength: 1 }) }), params);
+ await context.operations.sessions.rename(input.sessionId, input.title);
+ const summary = (await context.operations.sessions.list()).find((candidate) => candidate.id === input.sessionId);
+ if (summary) context.agentHost.publishSessionChange("session.changed", summary);
+ return { ok: true };
+ });
+ handlers.set("session/delete", async (context, params) => {
+ const input = check(SessionIdParams, params);
+ await context.operations.sessions.delete(input.sessionId);
+ return { ok: true };
+ });
+ handlers.set("session/compact", async (context, params) => {
+ const input = check(SessionIdParams, params);
+ return context.operations.sessions.compact(input.sessionId);
+ });
+
+ handlers.set("workspace/list", async (context, params) => {
+ const input = check(WorkspacePathParams, params);
+ return context.operations.workspace.list(input.sessionId, input.path ?? "");
+ });
+ handlers.set("workspace/read", async (context, params) => {
+ const input = check(WorkspacePathParams, params);
+ if (!input.path) throw new RacpError("INVALID_ARGUMENT", "path is required");
+ return context.operations.workspace.read(input.sessionId, input.path);
+ });
+ handlers.set("workspace/diff", async (context, params) => {
+ const input = check(SessionIdParams, params);
+ return context.operations.workspace.diff(input.sessionId);
+ });
+
+ handlers.set("terminal/open", async (context, params) => {
+ const terminal = requireTerminal(context);
+ const input = check(TerminalOpenParams, params);
+ const sink = {
+ output: (data: string) =>
+ context.deliverEvent(terminalEvent(context, input.sessionId, "terminal.output", { terminalId: opened.terminalId, data })),
+ exit: (code: number | null) => {
+ context.connection.terminals.delete(opened.terminalId);
+ context.deliverEvent(terminalEvent(context, input.sessionId, "terminal.changed", { terminalId: opened.terminalId, state: "exited", code }));
+ },
+ };
+ let opened: Awaited<ReturnType<typeof terminal.open>>;
+ if (input.terminalId) {
+ const attached = await terminal.attach(input.terminalId, sink);
+ if (!attached) throw new RacpError("NOT_FOUND", `terminal ${input.terminalId} is not open`);
+ opened = attached;
+ } else {
+ opened = await terminal.open(input.sessionId, { cols: input.cols ?? 80, rows: input.rows ?? 24 }, sink);
+ }
+ context.connection.terminals.add(opened.terminalId);
+ return opened;
+ });
+ handlers.set("terminal/input", async (context, params) => {
+ const input = check(TerminalInputParams, params);
+ await requireTerminal(context).input(input.terminalId, input.data);
+ return { ok: true };
+ });
+ handlers.set("terminal/resize", async (context, params) => {
+ const input = check(TerminalResizeParams, params);
+ await requireTerminal(context).resize(input.terminalId, input.cols, input.rows);
+ return { ok: true };
+ });
+ handlers.set("terminal/close", async (context, params) => {
+ const input = check(TerminalIdParams, params);
+ context.connection.terminals.delete(input.terminalId);
+ await requireTerminal(context).close(input.terminalId);
+ return { ok: true };
+ });
+
+ return handlers;
+}
+
+/** Terminal events are connection-local: they never enter the replay log (spec §5.3). */
+function terminalEvent(
+ context: OperationContext,
+ sessionId: string,
+ kind: "terminal.output" | "terminal.changed",
+ payload: Record<string, unknown>,
+): RacpEventEnvelope {
+ const cursor = context.agentHost.hub.stream(sessionId).cursor();
+ return {
+ eventId: `term_${context.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
+ scope: "session",
+ sessionId,
+ epoch: cursor.epoch,
+ ...(kind === "terminal.output" ? { afterSequence: cursor.sequence } : { sequence: cursor.sequence }),
+ revision: 0,
+ kind,
+ occurredAt: new Date(context.now()).toISOString(),
+ payload,
+ };
+}
diff --git a/packages/racp/src/racp.test.ts b/packages/racp/src/racp.test.ts
new file mode 100644
index 000000000..c40f55b2e
--- /dev/null
+++ b/packages/racp/src/racp.test.ts
@@ -0,0 +1,346 @@
+import { describe, expect, it } from "vitest";
+import type { AgentEventEnvelope, RacpEventEnvelope, RacpInitializeResult, RacpSessionSnapshot, RacpTurn, UiMessage } from "@pi-desktop/shared";
+
+import { hashToken, newPairingToken } from "./auth.js";
+import { OWNER_TOKEN, VIEWER_TOKEN, flush, harness } from "./test-harness.js";
+
+function envelope(sessionId: string, turnId: string, event: AgentEventEnvelope["event"]): AgentEventEnvelope {
+ return { sessionId, turnId, ts: Date.parse("2026-09-18T00:00:01.000Z"), event };
+}
+
+const context = (requestId: string, idempotencyKey?: string) => ({ requestId, ...(idempotencyKey ? { idempotencyKey } : {}) });
+
+describe("RACP-WS handshake and authentication", () => {
+ it("negotiates protocol, capabilities, limits, and the Host identity", async () => {
+ const h = await harness();
+ const { client } = await h.connect(OWNER_TOKEN);
+ const init = client.initialized as RacpInitializeResult;
+ expect(init.protocolVersion).toBe("1.0");
+ expect(init.server.hostId).toBe("host_test");
+ expect(init.principal).toEqual({ subject: "dev_owner", roles: ["owner"] });
+ expect(init.capabilities.remoteHostProfile).toBe(true);
+ expect(init.capabilities.bindings).toEqual(["RACP-WS"]);
+ expect(init.capabilities.terminal).toBe(false);
+ expect(init.limits.maxQueuedTurnsPerSession).toBe(8);
+ expect(init.policy.remoteMaxPermissionMode).toBe("ask");
+ const ping = await client.request<{ ok: boolean }>("connection/ping");
+ expect(ping.ok).toBe(true);
+ await client.close();
+ expect(h.server.connectionCount()).toBe(0);
+ });
+
+ it("refuses an unknown, revoked, or URL-carried credential before any RPC", async () => {
+ const h = await harness();
+ await expect(h.connect("pdt1.nonsense")).rejects.toMatchObject({ code: "REMOTE_AUTH_FAILED" });
+ expect(await h.authenticator.authenticate({ authorization: `Bearer ${OWNER_TOKEN}`, urlHasToken: true, connectionId: "c" })).toBeNull();
+ expect(await h.authenticator.authenticate({ authorization: `Basic ${OWNER_TOKEN}`, urlHasToken: false, connectionId: "c" })).toBeNull();
+ await h.store.revokeDevice("dev_owner", "2026-09-18T00:00:00.000Z");
+ await expect(h.connect(OWNER_TOKEN)).rejects.toMatchObject({ code: "REMOTE_AUTH_FAILED" });
+ });
+
+ it("rejects a request before initialization and an unknown operation after it", async () => {
+ const h = await harness();
+ const { client } = await h.connect(OWNER_TOKEN);
+ await expect(client.request("no/such")).rejects.toMatchObject({ code: "METHOD_NOT_FOUND" });
+ await expect(client.request("host/list")).rejects.toMatchObject({ code: "METHOD_NOT_FOUND" });
+ await expect(client.request("connection/initialize", {})).rejects.toMatchObject({ code: "CONFLICT" });
+ });
+
+ it("enforces roles from the catalog and the client limit", async () => {
+ const h = await harness({ limits: { maxConnectedClients: 1 } });
+ const viewer = await h.connect(VIEWER_TOKEN);
+ await expect(viewer.client.request("turn/start", { sessionId: "s1", input: { text: "x" }, context: context("r1") })).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(viewer.client.request("project/register", { path: "/x" })).rejects.toMatchObject({ code: "FORBIDDEN" });
+ const list = await viewer.client.request<{ sessions: unknown[] }>("session/list");
+ expect(list.sessions).toHaveLength(1);
+ await expect(h.connect(OWNER_TOKEN)).rejects.toMatchObject({ code: "REMOTE_CONNECTION_FAILED" });
+ });
+
+ it("exchanges a single-use pairing token for an owner device credential", async () => {
+ const h = await harness();
+ const issued = await h.authenticator.issuePairingToken(60_000);
+ const pairing = await h.connect(issued.token);
+ expect(pairing.client.initialized?.principal.roles).toEqual([]);
+ await expect(pairing.client.request("session/list")).rejects.toMatchObject({ code: "FORBIDDEN" });
+ const paired = await pairing.client.request<{ deviceId: string; deviceToken: string; roles: string[] }>("connection/pair", { deviceLabel: "my laptop" });
+ expect(paired.roles).toEqual(["owner"]);
+ expect(paired.deviceToken.startsWith("pdt1.")).toBe(true);
+ // Second exchange on the same token is refused; the new device token works.
+ await expect(pairing.client.request("connection/pair", {})).rejects.toMatchObject({ code: "PAIRING_FAILED" });
+ await expect(h.connect(issued.token)).rejects.toMatchObject({ code: "REMOTE_AUTH_FAILED" });
+ const device = await h.connect(paired.deviceToken);
+ expect(device.client.initialized?.principal).toEqual({ subject: paired.deviceId, roles: ["owner"] });
+ const stored = (await h.store.listDevices()).find((record) => record.deviceId === paired.deviceId);
+ expect(stored?.tokenHash).toBe(hashToken(paired.deviceToken));
+ expect(stored?.label).toBe("my laptop");
+ });
+
+ it("refuses an expired pairing token and a pairing call on a device connection", async () => {
+ const h = await harness();
+ const expired = newPairingToken();
+ await h.store.savePairing({ tokenHash: hashToken(expired), expiresAt: "2000-01-01T00:00:00.000Z" });
+ await expect(h.connect(expired)).rejects.toMatchObject({ code: "REMOTE_AUTH_FAILED" });
+ const { client } = await h.connect(OWNER_TOKEN);
+ await expect(client.request("connection/pair", {})).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+});
+
+describe("RACP-WS turns, events, and approvals", () => {
+ it("runs a turn end to end: attach, subscribe, start, ordered durable events, completion", async () => {
+ const h = await harness();
+ const { client, events } = await h.connect(OWNER_TOKEN);
+ const attach = await client.request<{ session: { id: string; status: string }; snapshot: RacpSessionSnapshot }>("session/attach", { sessionId: "s1" });
+ expect(attach.session.status).toBe("idle");
+ expect(attach.snapshot.cursor).toEqual({ epoch: expect.any(String), sequence: 0 });
+ const sub = await client.request<{ subscriptionId: string; replayComplete: boolean }>("events/subscribe", { scope: "session", sessionId: "s1" });
+ expect(sub.replayComplete).toBe(true);
+ const started = await client.request<{ accepted: boolean; turn: RacpTurn }>("turn/start", {
+ sessionId: "s1",
+ input: { text: "hello", messageId: "6f1c1e2a-3b4d-4c5e-8f6a-7b8c9d0e1f2a" },
+ context: context("r1", "k1"),
+ });
+ expect(started.turn.status).toBe("running");
+ expect(h.runtime.prompts[0]).toMatchObject({ content: "hello", userMessageId: "6f1c1e2a-3b4d-4c5e-8f6a-7b8c9d0e1f2a", effectivePermissionMode: "ask" });
+ const message: UiMessage = { id: "m1", role: "assistant", content: "hi", createdAt: "2026-09-18T00:00:01.000Z", status: "complete" };
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_start" }));
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_start", message: { ...message, status: "streaming" } }));
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_update", message: { ...message, status: "streaming" }, deltaText: "hi" }));
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_end", message }));
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_end", messageIds: ["m1"] }));
+ await flush();
+ const sequenced = events.filter((event) => typeof event.sequence === "number").map((event) => event.sequence);
+ expect(sequenced).toEqual([...sequenced].sort((a, b) => a - b));
+ expect(new Set(sequenced).size).toBe(sequenced.length);
+ expect(events.map((event) => event.kind)).toEqual(["turn.started", "item.started", "item.delta", "item.completed", "turn.completed", "session.changed"]);
+ expect(events.find((event) => event.kind === "item.delta")?.afterSequence).toBe(2);
+ const turn = await client.request<{ turn: RacpTurn }>("turn/get", { turnId: "rt_1" });
+ expect(turn.turn.status).toBe("completed");
+ expect(client.cursorFor("s1")).toEqual({ epoch: events[0]!.epoch, sequence: 5 });
+ });
+
+ it("returns the same turn for a repeated idempotency key and refuses a changed input", async () => {
+ const h = await harness();
+ const { client } = await h.connect(OWNER_TOKEN);
+ await client.request("session/attach", { sessionId: "s1" });
+ const first = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", input: { text: "hello" }, context: context("r1", "same") });
+ const second = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", input: { text: "hello" }, context: context("r2", "same") });
+ expect(second.turn.id).toBe(first.turn.id);
+ expect(h.runtime.prompts).toHaveLength(1);
+ await expect(client.request("turn/start", { sessionId: "s1", input: { text: "other" }, context: context("r3", "same") })).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" });
+ await expect(client.request("turn/start", { sessionId: "s1", input: { text: "busy" }, context: context("r4") })).rejects.toMatchObject({ code: "AGENT_BUSY" });
+ const queued = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", admission: "queue", input: { text: "later" }, context: context("r5") });
+ expect(queued.turn.status).toBe("queued");
+ expect(queued.turn.queuePosition).toBe(1);
+ });
+
+ it("stops, interrupts, and cancels through the catalog and enforces the prompt limit", async () => {
+ const h = await harness({ limits: { maxPromptBytes: 16 } });
+ const { client } = await h.connect(OWNER_TOKEN);
+ await client.request("session/attach", { sessionId: "s1" });
+ await expect(client.request("turn/start", { sessionId: "s1", input: { text: "x".repeat(17) }, context: context("r0") })).rejects.toMatchObject({ code: "PAYLOAD_TOO_LARGE" });
+ const started = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", input: { text: "go" }, context: context("r1") });
+ const queued = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", admission: "queue", input: { text: "next" }, context: context("r2") });
+ await client.request("turn/stop", { turnId: started.turn.id });
+ expect(h.runtime.stops).toEqual(["s1"]);
+ await client.request("turn/interrupt", { turnId: started.turn.id });
+ expect(h.runtime.aborts).toEqual([{ sessionId: "s1", turnId: started.turn.id }]);
+ const canceled = await client.request<{ turn: RacpTurn }>("turn/cancel", { turnId: queued.turn.id });
+ expect(canceled.turn.status).toBe("canceled");
+ await expect(client.request("turn/cancel", { turnId: started.turn.id })).rejects.toMatchObject({ code: "CONFLICT" });
+ });
+
+ it("delivers approval requests to a viewer and lets the owner resolve them once", async () => {
+ const h = await harness();
+ const ownerSide = await h.connect(OWNER_TOKEN);
+ const viewerSide = await h.connect(VIEWER_TOKEN);
+ await ownerSide.client.request("session/attach", { sessionId: "s1" });
+ await ownerSide.client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ await viewerSide.client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ await ownerSide.client.request("turn/start", { sessionId: "s1", input: { text: "run" }, context: context("r1") });
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_start" }));
+ h.host.ingest(
+ envelope("s1", "rt_1", {
+ type: "tool_permission_request",
+ request: { requestId: "perm-1", sessionId: "s1", toolCallId: "c1", toolName: "Bash", argsPreview: "rm", risk: "high", reason: "shell" },
+ }),
+ );
+ await flush();
+ const requested = viewerSide.events.find((event) => event.kind === "approval.requested");
+ expect(requested).toBeDefined();
+ expect((requested!.payload as { allowedDecisions: string[] }).allowedDecisions).toEqual(["allow-once", "deny"]);
+ await expect(viewerSide.client.request("approval/respond", { approvalId: "perm-1", decision: "allow-once", context: context("r2") })).rejects.toMatchObject({ code: "FORBIDDEN" });
+ const resolved = await ownerSide.client.request<{ status: string; alreadyResolved: boolean }>("approval/respond", { approvalId: "perm-1", decision: "deny", context: context("r3") });
+ expect(resolved).toMatchObject({ status: "resolved", alreadyResolved: false });
+ expect(h.approvals.tool).toEqual([{ requestId: "perm-1", decision: "deny" }]);
+ const again = await ownerSide.client.request<{ alreadyResolved: boolean; decision: string }>("approval/respond", { approvalId: "perm-1", decision: "allow-once", context: context("r4") });
+ expect(again).toMatchObject({ alreadyResolved: true, decision: "deny" });
+ expect(h.approvals.tool).toHaveLength(1);
+ await flush();
+ expect(viewerSide.events.filter((event) => event.kind === "approval.resolved")).toHaveLength(1);
+ });
+
+ it("answers input requests and closes the subscription of a client that stops acknowledging", async () => {
+ const h = await harness();
+ const closed: unknown[] = [];
+ const { client, events } = await h.connect(OWNER_TOKEN, { onSubscriptionClosed: (notice) => closed.push(notice) });
+ await client.request("session/attach", { sessionId: "s1" });
+ await client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ await client.request("turn/start", { sessionId: "s1", input: { text: "ask" }, context: context("r1") });
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_start" }));
+ h.host.ingest(envelope("s1", "rt_1", { type: "asktool_request", request: { requestId: "ask-1", sessionId: "s1", toolCallId: "c1", questions: [{ question: "Which?", options: ["a", "b"] }] } }));
+ await flush();
+ const input = events.find((event) => event.kind === "input.requested");
+ expect(input).toBeDefined();
+ await client.request("input/respond", { inputId: "ask-1", answers: [["a"]], context: context("r2") });
+ expect(h.runtime.inputs).toEqual([{ requestId: "ask-1", sessionId: "s1", answers: [["a"]] }]);
+ // Acknowledgements release the bound; without them a slow client is closed with a resumable cursor.
+ for (let index = 0; index < 1_005; index += 1) {
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_end", message: { id: `m${index}`, role: "assistant", content: "x", createdAt: "2026-09-18T00:00:01.000Z", status: "complete" } }));
+ }
+ await flush();
+ expect(closed).toHaveLength(1);
+ expect(closed[0]).toMatchObject({ error: { code: "CLIENT_TOO_SLOW" }, lastSafeCursor: { sequence: expect.any(Number) } });
+ });
+});
+
+describe("RACP-WS reconnect", () => {
+ it("keeps the turn running across a drop and resumes events by cursor without a second prompt", async () => {
+ const h = await harness();
+ const { client, events, link } = await h.connect(OWNER_TOKEN, { reconnect: { enabled: true, baseDelayMs: 1 } });
+ await client.request("session/attach", { sessionId: "s1" });
+ await client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ const started = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", input: { text: "long job" }, context: context("r1", "job-1") });
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_start" }));
+ await flush();
+ const before = events.length;
+ link().drop();
+ await flush();
+ // Events that happened while disconnected are retained by the Host.
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_end", message: { id: "m1", role: "assistant", content: "still working", createdAt: "2026-09-18T00:00:01.000Z", status: "complete" } }));
+ await flush();
+ expect(client.state).toBe("connected");
+ expect(h.runtime.aborts).toEqual([]);
+ expect(h.runtime.stops).toEqual([]);
+ const attach = await client.request<{ replayComplete: boolean; session: { activeTurnId?: string } }>("session/attach", { sessionId: "s1", after: client.cursorFor("s1") });
+ expect(attach.replayComplete).toBe(true);
+ expect(attach.session.activeTurnId).toBe(started.turn.id);
+ const resumed = await client.request<{ replayComplete: boolean; starting: { sequence: number } }>("events/subscribe", { scope: "session", sessionId: "s1", after: client.cursorFor("s1") });
+ expect(resumed.replayComplete).toBe(true);
+ await flush();
+ const replayed = events.slice(before).filter((event) => typeof event.sequence === "number");
+ expect(replayed.map((event) => event.kind)).toEqual(["item.completed"]);
+ // The same idempotency key after reconnect returns the same turn: nothing re-executes.
+ const again = await client.request<{ turn: RacpTurn }>("turn/start", { sessionId: "s1", input: { text: "long job" }, context: context("r2", "job-1") });
+ expect(again.turn.id).toBe(started.turn.id);
+ expect(h.runtime.prompts).toHaveLength(1);
+ // The old connection's subscription was released with it.
+ expect(h.host.hub.subscriptionCount()).toBe(1);
+ });
+
+ it("falls back to a snapshot when the cursor is from another epoch or was evicted", async () => {
+ const h = await harness({ limits: { replayWindowEvents: 3 } });
+ const { client, events } = await h.connect(OWNER_TOKEN);
+ await client.request("session/attach", { sessionId: "s1" });
+ await client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ await client.request("turn/start", { sessionId: "s1", input: { text: "go" }, context: context("r1") });
+ h.host.ingest(envelope("s1", "rt_1", { type: "agent_start" }));
+ await flush();
+ const early = client.cursorFor("s1")!;
+ for (let index = 0; index < 6; index += 1) {
+ h.host.ingest(envelope("s1", "rt_1", { type: "message_end", message: { id: `m${index}`, role: "assistant", content: "x", createdAt: "2026-09-18T00:00:01.000Z", status: "complete" } }));
+ }
+ await flush();
+ const evicted = await client.request<{ replayComplete: boolean; resyncReason?: string; snapshot?: RacpSessionSnapshot }>("session/attach", { sessionId: "s1", after: early });
+ expect(evicted.replayComplete).toBe(false);
+ expect(evicted.resyncReason).toBe("evicted");
+ expect(evicted.snapshot?.activeTurn?.id).toBe("rt_1");
+ const otherEpoch = await client.request<{ replayComplete: boolean; resyncReason?: string }>("session/attach", { sessionId: "s1", after: { epoch: "ep_old", sequence: 1 } });
+ expect(otherEpoch.resyncReason).toBe("epoch");
+ const ahead = await client.request<{ resyncReason?: string }>("events/subscribe", { scope: "session", sessionId: "s1", after: { epoch: early.epoch, sequence: 999 } });
+ expect(ahead.resyncReason).toBe("ahead");
+ expect(events.length).toBeGreaterThan(0);
+ });
+
+ it("rejects in-flight requests on a drop with HOST_DISCONNECTED and reports state changes", async () => {
+ const h = await harness();
+ const states: string[] = [];
+ const { client, link } = await h.connect(OWNER_TOKEN, { onStateChange: (state) => states.push(state) });
+ const pending = client.request("connection/ping");
+ link().drop();
+ await expect(pending).rejects.toMatchObject({ code: "HOST_DISCONNECTED" });
+ await flush();
+ expect(client.state).toBe("disconnected");
+ await expect(client.request("connection/ping")).rejects.toMatchObject({ code: "HOST_DISCONNECTED" });
+ expect(states).toEqual(["connecting", "connected", "disconnected"]);
+ });
+
+ it("gives up after the reconnect budget and reports an error state", async () => {
+ const h = await harness();
+ const states: string[] = [];
+ const { client, link } = await h.connect(OWNER_TOKEN, { reconnect: { enabled: true, baseDelayMs: 1, maxAttempts: 2 }, onStateChange: (state) => states.push(state) });
+ await h.store.revokeDevice("dev_owner", "2026-09-18T00:00:00.000Z");
+ link().drop();
+ await flush();
+ await flush();
+ expect(states.at(-1)).toBe("error");
+ expect(client.state).toBe("error");
+ });
+});
+
+describe("RACP-WS remote-host profile", () => {
+ it("creates, configures, forks, renames, and deletes sessions and publishes host events", async () => {
+ const h = await harness();
+ const { client, events } = await h.connect(OWNER_TOKEN);
+ await client.request("events/subscribe", { scope: "host" });
+ const created = await client.request<{ session: { id: string; title: string; permissionMode: string } }>("session/create", { title: "Remote job", permissionMode: "accept-edits" });
+ expect(created.session.permissionMode).toBe("accept-edits");
+ const configured = await client.request<{ session: { mode: string } }>("session/configure", { sessionId: created.session.id, mode: "plan" });
+ expect(configured.session.mode).toBe("plan");
+ const forked = await client.request<{ session: { id: string } }>("session/fork", { sessionId: created.session.id });
+ expect(forked.session.id).toBe(`${created.session.id}-fork`);
+ await client.request("session/rename", { sessionId: created.session.id, title: "Renamed" });
+ expect(h.sessions.get(created.session.id)?.title).toBe("Renamed");
+ await client.request("session/delete", { sessionId: forked.session.id });
+ expect(h.sessions.has(forked.session.id)).toBe(false);
+ await client.request("session/compact", { sessionId: created.session.id });
+ await flush();
+ expect(events.filter((event) => event.scope === "host").map((event) => event.kind)).toEqual(["session.created", "session.changed", "session.created", "session.changed"]);
+ await expect(client.request("session/get", { sessionId: "nope" })).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("serves projects and bounded workspace reads and maps Host path errors to stable codes", async () => {
+ const h = await harness();
+ const { client } = await h.connect(OWNER_TOKEN);
+ const projects = await client.request<{ projects: Array<{ id: string }> }>("project/list");
+ expect(projects.projects[0]?.id).toBe("proj");
+ const registered = await client.request<{ project: { id: string; label: string } }>("project/register", { path: "/srv/app" });
+ expect(registered.project).toMatchObject({ id: "proj-2", label: "app" });
+ await expect(client.request("project/register", { path: "/srv/missing" })).rejects.toMatchObject({ code: "REMOTE_PATH_NOT_FOUND" });
+ const browsed = await client.request<{ entries: unknown[] }>("project/browse", {});
+ expect(browsed.entries).toHaveLength(1);
+ const listed = await client.request<{ entries: Array<{ name: string }> }>("workspace/list", { sessionId: "s1", path: "" });
+ expect(listed.entries[0]?.name).toBe("README.md");
+ const read = await client.request<{ kind: string; content: string }>("workspace/read", { sessionId: "s1", path: "README.md" });
+ expect(read).toMatchObject({ kind: "text", content: "hello" });
+ await expect(client.request("workspace/read", { sessionId: "s1", path: "../etc/passwd" })).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });
+ await expect(client.request("workspace/read", { sessionId: "s1" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ const diff = await client.request<{ repo: boolean }>("workspace/diff", { sessionId: "s1" });
+ expect(diff.repo).toBe(true);
+ await expect(client.request("terminal/open", { sessionId: "s1" })).rejects.toMatchObject({ code: "CAPABILITY_UNAVAILABLE" });
+ await expect(client.request("attachment/create", {})).rejects.toMatchObject({ code: "CAPABILITY_UNAVAILABLE" });
+ });
+
+ it("rejects malformed params and oversized frames with typed errors", async () => {
+ const h = await harness({ limits: { maxFrameBytes: 512 } });
+ const { client, link } = await h.connect(OWNER_TOKEN);
+ await expect(client.request("turn/start", { sessionId: "s1" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ await expect(client.request("session/attach", { sessionId: 42 })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ link().clientSide().send("x".repeat(600));
+ await flush();
+ const last = JSON.parse(link().toClient.at(-1)!) as { error?: { data?: { code?: string } } };
+ expect(last.error?.data?.code).toBe("PAYLOAD_TOO_LARGE");
+ });
+});
+
+/** Type-only assertion that the envelope import stays used. */
+export type _Envelope = RacpEventEnvelope;
diff --git a/packages/racp/src/server.ts b/packages/racp/src/server.ts
new file mode 100644
index 000000000..b5ce45656
--- /dev/null
+++ b/packages/racp/src/server.ts
@@ -0,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). */
+ 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 --git a/packages/racp/src/test-harness.ts b/packages/racp/src/test-harness.ts
new file mode 100644
index 000000000..2d69ff9fc
--- /dev/null
+++ b/packages/racp/src/test-harness.ts
@@ -0,0 +1,272 @@
+import type { AskToolResolution } from "@pi-desktop/shared";
+import { RacpError, AgentHost, type ApprovalPort, type Principal, type RuntimePort, type SessionPort, type SessionSummary, type TurnStartRequest } from "@pi-desktop/agent-host";
+
+import { DeviceTokenAuthenticator, MemoryCredentialStore, hashToken, newDeviceToken, type ConnectionAuth } from "./auth.js";
+import { RacpClient, type ClientTransport, type ClientTransportFactory } from "./client.js";
+import type { RacpHostOperations } from "./host-operations.js";
+import { RacpServer, type ServerConnectionTransport } from "./server.js";
+
+/** An in-memory transport pair: what `ws` provides, without a socket. */
+export class MemoryLink {
+ private clientHandlers: { message?: (frame: string) => void; close?: (info: { code: number; reason: string }) => void } = {};
+ private serverHandlers: { message?: (frame: string, byteLength: number) => void; close?: () => void } = {};
+ private open = true;
+ /** Frames the server sent, for assertions. */
+ readonly toClient: string[] = [];
+ readonly toServer: string[] = [];
+
+ get isOpen(): boolean {
+ return this.open;
+ }
+
+ serverSide(): ServerConnectionTransport {
+ return {
+ send: (frame) => {
+ if (!this.open) throw new Error("link closed");
+ this.toClient.push(frame);
+ queueMicrotask(() => this.clientHandlers.message?.(frame));
+ },
+ close: (code, reason) => this.drop(code, reason),
+ onMessage: (handler) => {
+ this.serverHandlers.message = handler;
+ },
+ onClose: (handler) => {
+ this.serverHandlers.close = handler;
+ },
+ };
+ }
+
+ clientSide(): ClientTransport {
+ return {
+ send: (frame) => {
+ if (!this.open) throw new Error("link closed");
+ this.toServer.push(frame);
+ queueMicrotask(() => this.serverHandlers.message?.(frame, Buffer.byteLength(frame, "utf8")));
+ },
+ close: (code, reason) => this.drop(code ?? 1000, reason ?? ""),
+ onMessage: (handler) => {
+ this.clientHandlers.message = handler;
+ },
+ onClose: (handler) => {
+ this.clientHandlers.close = handler;
+ },
+ onError: () => undefined,
+ };
+ }
+
+ /** Simulate the network dropping: both ends observe a close. */
+ drop(code = 1006, reason = "dropped"): void {
+ if (!this.open) return;
+ this.open = false;
+ queueMicrotask(() => {
+ this.serverHandlers.close?.();
+ this.clientHandlers.close?.({ code, reason });
+ });
+ }
+}
+
+export class FakeRuntime implements RuntimePort {
+ prompts: TurnStartRequest[] = [];
+ stops: string[] = [];
+ aborts: Array<{ sessionId: string; turnId?: string }> = [];
+ inputs: AskToolResolution[] = [];
+ private counter = 0;
+ async prompt(request: TurnStartRequest): Promise<{ turnId: string }> {
+ this.prompts.push(request);
+ this.counter += 1;
+ return { turnId: `rt_${this.counter}` };
+ }
+ async stop(sessionId: string): Promise<{ requested: boolean }> {
+ this.stops.push(sessionId);
+ return { requested: true };
+ }
+ async abort(sessionId: string, turnId?: string): Promise<void> {
+ this.aborts.push({ sessionId, turnId });
+ }
+ async respondInput(resolution: AskToolResolution): Promise<void> {
+ this.inputs.push(resolution);
+ }
+}
+
+export function summary(id: string, permissionMode: SessionSummary["permissionMode"] = "ask"): SessionSummary {
+ return {
+ id,
+ title: `Session ${id}`,
+ projectId: "proj",
+ mode: "agent",
+ permissionMode,
+ createdAt: "2026-09-18T00:00:00.000Z",
+ updatedAt: "2026-09-18T00:00:00.000Z",
+ };
+}
+
+export function buildHost(limits: Partial<import("@pi-desktop/shared").RacpLimits> = {}): { host: AgentHost; runtime: FakeRuntime; sessions: Map<string, SessionSummary>; approvals: { tool: Array<{ requestId: string; decision: string }> } } {
+ const runtime = new FakeRuntime();
+ const sessions = new Map<string, SessionSummary>([["s1", summary("s1")]]);
+ const sessionPort: SessionPort = {
+ async get(sessionId) {
+ return sessions.get(sessionId) ?? null;
+ },
+ async history() {
+ return { items: [], hasMore: false };
+ },
+ };
+ const approvals = { tool: [] as Array<{ requestId: string; decision: string }> };
+ const approvalPort: ApprovalPort = {
+ async resolveTool(requestId, decision) {
+ approvals.tool.push({ requestId, decision });
+ },
+ async resolveContract() {},
+ async listPendingTools() {
+ return [];
+ },
+ };
+ const host = new AgentHost({ runtime, sessions: sessionPort, approvals: approvalPort, limits: { replayWindowEvents: 50, ...limits } });
+ return { host, runtime, sessions, approvals };
+}
+
+export function fakeOperations(sessions: Map<string, SessionSummary>): RacpHostOperations {
+ let counter = 0;
+ return {
+ sessions: {
+ async list() {
+ return [...sessions.values()];
+ },
+ async create(input) {
+ counter += 1;
+ const created = { ...summary(`s${counter + 1}`), title: input.title ?? "New session", ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}) };
+ sessions.set(created.id, created);
+ return created;
+ },
+ async configure(sessionId, input) {
+ const current = sessions.get(sessionId);
+ if (!current) throw new RacpError("NOT_FOUND", "session");
+ const next = { ...current, ...(input.mode ? { mode: input.mode } : {}), ...(input.permissionMode ? { permissionMode: input.permissionMode } : {}) };
+ sessions.set(sessionId, next);
+ return next;
+ },
+ async fork(sessionId) {
+ const current = sessions.get(sessionId);
+ if (!current) throw new RacpError("NOT_FOUND", "session");
+ const forked = { ...current, id: `${sessionId}-fork`, title: `${current.title} (fork)` };
+ sessions.set(forked.id, forked);
+ return forked;
+ },
+ async rename(sessionId, title) {
+ const current = sessions.get(sessionId);
+ if (current) sessions.set(sessionId, { ...current, title });
+ },
+ async delete(sessionId) {
+ sessions.delete(sessionId);
+ },
+ async compact() {
+ return { accepted: true };
+ },
+ },
+ projects: {
+ async list() {
+ return [{ id: "proj", label: "proj", archived: false }];
+ },
+ async register(path) {
+ if (path.includes("missing")) throw new RacpError("REMOTE_PATH_NOT_FOUND", "no such directory");
+ return { id: "proj-2", label: path.split("/").pop() ?? path, archived: false, path };
+ },
+ async browse(path) {
+ return { path: path ?? "/home/user", entries: [{ name: "work", path: `${path ?? "/home/user"}/work` }] };
+ },
+ },
+ workspace: {
+ async list(_sessionId, path) {
+ if (path.includes("..")) throw new RacpError("REMOTE_PATH_FORBIDDEN", "escapes root");
+ return { entries: [{ name: "README.md", kind: "file", size: 12 }] };
+ },
+ async read(_sessionId, path) {
+ if (path.includes("..")) throw new RacpError("REMOTE_PATH_FORBIDDEN", "escapes root");
+ return { kind: "text", content: "hello", size: 5 };
+ },
+ async diff() {
+ return { repo: true, clean: true, files: [] };
+ },
+ },
+ };
+}
+
+export const OWNER_TOKEN = newDeviceToken();
+export const VIEWER_TOKEN = newDeviceToken();
+
+export async function credentialStore(): Promise<{ store: MemoryCredentialStore; authenticator: DeviceTokenAuthenticator }> {
+ const store = new MemoryCredentialStore();
+ await store.saveDevice({ deviceId: "dev_owner", label: "desktop", roles: ["owner"], tokenHash: hashToken(OWNER_TOKEN), createdAt: "2026-09-18T00:00:00.000Z" });
+ await store.saveDevice({ deviceId: "dev_viewer", label: "watcher", roles: ["viewer"], tokenHash: hashToken(VIEWER_TOKEN), createdAt: "2026-09-18T00:00:00.000Z" });
+ return { store, authenticator: new DeviceTokenAuthenticator(store) };
+}
+
+export type Harness = {
+ server: RacpServer;
+ host: AgentHost;
+ runtime: FakeRuntime;
+ sessions: Map<string, SessionSummary>;
+ approvals: { tool: Array<{ requestId: string; decision: string }> };
+ authenticator: DeviceTokenAuthenticator;
+ store: MemoryCredentialStore;
+ links: MemoryLink[];
+ /** Open a client whose transport authenticates with `token` on every (re)connect. */
+ connect(token: string, options?: Partial<ConstructorParameters<typeof RacpClient>[0]>): Promise<{ client: RacpClient; events: import("@pi-desktop/shared").RacpEventEnvelope[]; link: () => MemoryLink }>;
+};
+
+export async function harness(options: { limits?: Partial<import("@pi-desktop/shared").RacpLimits>; operations?: Partial<RacpHostOperations> } = {}): Promise<Harness> {
+ const { host, runtime, sessions, approvals } = buildHost(options.limits);
+ const { store, authenticator } = await credentialStore();
+ const operations = { ...fakeOperations(sessions), ...options.operations };
+ const server = new RacpServer({
+ agentHost: host,
+ operations,
+ authenticator,
+ hostId: "host_test",
+ serverVersion: "0.15.0",
+ limits: options.limits,
+ log: () => undefined,
+ initializeTimeoutMs: 1_000,
+ });
+ const links: MemoryLink[] = [];
+ return {
+ server,
+ host,
+ runtime,
+ sessions,
+ approvals,
+ authenticator,
+ store,
+ links,
+ async connect(token, clientOptions = {}) {
+ const events: import("@pi-desktop/shared").RacpEventEnvelope[] = [];
+ let current: MemoryLink | null = null;
+ const transport: ClientTransportFactory = async () => {
+ const auth: ConnectionAuth | null = await authenticator.authenticate({ authorization: `Bearer ${token}`, urlHasToken: false, connectionId: "pending" });
+ if (!auth) throw Object.assign(new Error("unauthorized"), { errorCode: "REMOTE_AUTH_FAILED" });
+ const link = new MemoryLink();
+ links.push(link);
+ current = link;
+ const accepted = server.accept(auth, link.serverSide());
+ if (!accepted) throw Object.assign(new Error("refused"), { errorCode: "REMOTE_CONNECTION_FAILED" });
+ return link.clientSide();
+ };
+ const client = new RacpClient({
+ transport,
+ client: { name: "test", version: "0.15.0" },
+ onEvent: (envelope) => events.push(envelope),
+ requestTimeoutMs: 2_000,
+ sleep: async () => undefined,
+ ...clientOptions,
+ });
+ await client.connect();
+ return { client, events, link: () => current! };
+ },
+ };
+}
+
+export const owner: Principal = { subject: "dev_owner", roles: ["owner"], pairedDevice: true };
+
+export async function flush(): Promise<void> {
+ for (let index = 0; index < 8; index += 1) await new Promise((resolve) => setImmediate(resolve));
+}
diff --git a/packages/racp/src/ws-binding.test.ts b/packages/racp/src/ws-binding.test.ts
new file mode 100644
index 000000000..51536a22a
--- /dev/null
+++ b/packages/racp/src/ws-binding.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from "vitest";
+import { WebSocket } from "ws";
+import { RACP_WS_SUBPROTOCOL } from "@pi-desktop/shared";
+
+import { RacpClient } from "./client.js";
+import { OWNER_TOKEN, harness } from "./test-harness.js";
+import { bindRacpWebSocket, wsClientTransport } from "./ws-binding.js";
+
+describe("RACP-WS over a loopback socket", () => {
+ it("authenticates on the upgrade, runs the handshake, and delivers events over ws", async () => {
+ const h = await harness();
+ const binding = await bindRacpWebSocket({ server: h.server, authenticator: h.authenticator, port: 0, log: () => undefined });
+ try {
+ const url = `ws://127.0.0.1:${binding.address.port}/v1/racp/ws`;
+ const events: unknown[] = [];
+ const client = new RacpClient({
+ transport: wsClientTransport({ url, token: OWNER_TOKEN }),
+ client: { name: "test", version: "0.15.0" },
+ onEvent: (envelope) => events.push(envelope),
+ });
+ const init = await client.connect();
+ expect(init.server.hostId).toBe("host_test");
+ await client.request("session/attach", { sessionId: "s1" });
+ await client.request("events/subscribe", { scope: "session", sessionId: "s1" });
+ await client.request("turn/start", { sessionId: "s1", input: { text: "hi" }, context: { requestId: "r1" } });
+ h.host.ingest({ sessionId: "s1", turnId: "rt_1", ts: 1, event: { type: "agent_start" } });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(events).toHaveLength(1);
+ await client.close();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(h.server.connectionCount()).toBe(0);
+ } finally {
+ await binding.close();
+ }
+ });
+
+ it("refuses a missing credential, a token in the URL, a wrong path, and a binary frame", async () => {
+ const h = await harness();
+ const binding = await bindRacpWebSocket({ server: h.server, authenticator: h.authenticator, port: 0, log: () => undefined });
+ try {
+ const base = `ws://127.0.0.1:${binding.address.port}`;
+ const status = (url: string, headers: Record<string, string> = {}) =>
+ new Promise<number | "open">((resolve) => {
+ const socket = new WebSocket(url, [RACP_WS_SUBPROTOCOL], { headers });
+ socket.once("unexpected-response", (_request, response) => {
+ resolve(response.statusCode ?? 0);
+ socket.terminate();
+ });
+ socket.once("open", () => {
+ resolve("open");
+ socket.terminate();
+ });
+ socket.once("error", () => resolve(0));
+ });
+ expect(await status(`${base}/v1/racp/ws`)).toBe(401);
+ expect(await status(`${base}/v1/racp/ws?token=${OWNER_TOKEN}`, { Authorization: `Bearer ${OWNER_TOKEN}` })).toBe(401);
+ expect(await status(`${base}/other`, { Authorization: `Bearer ${OWNER_TOKEN}` })).toBe(404);
+ expect(await status(`${base}/v1/racp/ws`, { Authorization: `Bearer ${OWNER_TOKEN}` })).toBe("open");
+ await expect(new RacpClient({ transport: wsClientTransport({ url: `${base}/v1/racp/ws`, token: "pdt1.bad" }), client: { name: "t", version: "1" } }).connect()).rejects.toMatchObject({ code: "REMOTE_AUTH_FAILED" });
+
+ const closeCode = await new Promise<number>((resolve) => {
+ const socket = new WebSocket(`${base}/v1/racp/ws`, [RACP_WS_SUBPROTOCOL], { headers: { Authorization: `Bearer ${OWNER_TOKEN}` } });
+ socket.once("open", () => socket.send(Buffer.from([1, 2, 3])));
+ socket.once("close", (code) => resolve(code));
+ });
+ expect(closeCode).toBe(1003);
+ expect(h.server.connectionCount()).toBe(0);
+ } finally {
+ await binding.close();
+ }
+ });
+
+ it("refuses to bind a non-loopback address and plain ws to a non-loopback host", async () => {
+ const h = await harness();
+ await expect(bindRacpWebSocket({ server: h.server, authenticator: h.authenticator, host: "0.0.0.0", port: 0, log: () => undefined })).rejects.toMatchObject({ errorCode: "INVALID_ARGUMENT" });
+ await expect(wsClientTransport({ url: "ws://example.com/v1/racp/ws", token: OWNER_TOKEN })()).rejects.toMatchObject({ errorCode: "REMOTE_CONNECTION_FAILED" });
+ });
+});
diff --git a/packages/racp/src/ws-binding.ts b/packages/racp/src/ws-binding.ts
new file mode 100644
index 000000000..62d7731bc
--- /dev/null
+++ b/packages/racp/src/ws-binding.ts
@@ -0,0 +1,186 @@
+import type { IncomingMessage } from "node:http";
+import { createServer, type Server } from "node:http";
+import type { Socket } from "node:net";
+
+import { RACP_WS_PATH, RACP_WS_SUBPROTOCOL } from "@pi-desktop/shared";
+import { WebSocket, WebSocketServer } from "ws";
+
+import { isLoopbackAddress, type DeviceTokenAuthenticator } from "./auth.js";
+import type { ClientTransport, ClientTransportFactory } from "./client.js";
+import type { RacpServer, ServerConnectionTransport } from "./server.js";
+
+export type WsBindingOptions = {
+ server: RacpServer;
+ authenticator: DeviceTokenAuthenticator;
+ /** Loopback only unless TLS terminates in front (security §5.1); a non-loopback bind is refused here. */
+ host?: string;
+ port: number;
+ log: (level: "info" | "warn" | "error", message: string, data?: Record<string, unknown>) => void;
+ heartbeatMs?: number;
+};
+
+export type WsBinding = {
+ address: { host: string; port: number };
+ close(): Promise<void>;
+};
+
+function wsTransport(socket: WebSocket): ServerConnectionTransport {
+ return {
+ send: (frame) => socket.send(frame),
+ close: (code, reason) => socket.close(code, reason),
+ onMessage: (handler) => {
+ socket.on("message", (data, isBinary) => {
+ if (isBinary) {
+ socket.close(1003, "binary frames are not accepted");
+ return;
+ }
+ const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.concat(data as Buffer[]).toString("utf8");
+ handler(text, Buffer.byteLength(text, "utf8"));
+ });
+ },
+ onClose: (handler) => {
+ socket.once("close", handler);
+ socket.once("error", () => handler());
+ },
+ };
+}
+
+/**
+ * Bind the RACP server to a loopback WebSocket listener (spec §11.1). The
+ * upgrade request carries the bearer credential; a token in the URL, a
+ * non-loopback peer, a wrong path, or a missing subprotocol is refused
+ * before any RPC runs.
+ */
+export async function bindRacpWebSocket(options: WsBindingOptions): Promise<WsBinding> {
+ const host = options.host ?? "127.0.0.1";
+ if (!isLoopbackAddress(host)) {
+ throw Object.assign(new Error("pi-host binds loopback only; a non-loopback bind requires TLS"), {
+ errorCode: "INVALID_ARGUMENT",
+ });
+ }
+ const http: Server = createServer((_request, response) => {
+ response.statusCode = 426;
+ response.setHeader("Upgrade", "websocket");
+ response.end("RACP-WS endpoint");
+ });
+ const wss = new WebSocketServer({ noServer: true, handleProtocols: (protocols) => (protocols.has(RACP_WS_SUBPROTOCOL) ? RACP_WS_SUBPROTOCOL : false) });
+ const sockets = new Set<WebSocket>();
+
+ http.on("upgrade", (request: IncomingMessage, socket: Socket, head: Buffer) => {
+ void (async () => {
+ const url = new URL(request.url ?? "/", "http://localhost");
+ const reject = (status: number, reason: string) => {
+ options.log("warn", "racp upgrade refused", { reason, peer: request.socket.remoteAddress });
+ socket.write(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\n\r\n`);
+ socket.destroy();
+ };
+ if (url.pathname !== RACP_WS_PATH) return reject(404, "Not Found");
+ if (!isLoopbackAddress(request.socket.remoteAddress)) return reject(403, "Forbidden");
+ const urlHasToken = [...url.searchParams.keys()].some((key) => /token|auth/i.test(key));
+ const auth = await options.authenticator.authenticate({
+ authorization: request.headers.authorization,
+ urlHasToken,
+ connectionId: "pending",
+ });
+ if (!auth) return reject(401, "Unauthorized");
+ wss.handleUpgrade(request, socket, head, (ws) => {
+ sockets.add(ws);
+ ws.once("close", () => sockets.delete(ws));
+ const connection = options.server.accept(auth, wsTransport(ws));
+ if (!connection) return;
+ // Heartbeat (spec §11.1): a peer that stops answering pings is dropped.
+ let alive = true;
+ ws.on("pong", () => {
+ alive = true;
+ });
+ const heartbeat = setInterval(() => {
+ if (ws.readyState !== WebSocket.OPEN) return;
+ if (!alive) {
+ ws.terminate();
+ return;
+ }
+ alive = false;
+ ws.ping();
+ }, options.heartbeatMs ?? 30_000);
+ heartbeat.unref?.();
+ ws.once("close", () => clearInterval(heartbeat));
+ });
+ })().catch((error) => {
+ options.log("error", "racp upgrade failed", { error: String(error) });
+ socket.destroy();
+ });
+ });
+
+ await new Promise<void>((resolve, reject) => {
+ http.once("error", reject);
+ http.listen(options.port, host, () => {
+ http.off("error", reject);
+ resolve();
+ });
+ });
+ const address = http.address();
+ const port = typeof address === "object" && address ? address.port : options.port;
+ options.log("info", "racp listening", { host, port });
+ return {
+ address: { host, port },
+ close: async () => {
+ for (const ws of sockets) ws.terminate();
+ wss.close();
+ await new Promise<void>((resolve) => http.close(() => resolve()));
+ },
+ };
+}
+
+export type WsClientOptions = {
+ url: string;
+ token: string;
+ connectTimeoutMs?: number;
+};
+
+/** A `ws`-backed client transport for the header profile. */
+export function wsClientTransport(options: WsClientOptions): ClientTransportFactory {
+ return () =>
+ new Promise<ClientTransport>((resolve, reject) => {
+ const url = new URL(options.url);
+ if (url.protocol !== "ws:" && url.protocol !== "wss:") {
+ reject(Object.assign(new Error("RACP endpoint must be ws:// or wss://"), { errorCode: "REMOTE_CONNECTION_FAILED" }));
+ return;
+ }
+ if (url.protocol === "ws:" && !isLoopbackAddress(url.hostname) && url.hostname !== "localhost") {
+ reject(Object.assign(new Error("plain ws:// is accepted only on loopback"), { errorCode: "REMOTE_CONNECTION_FAILED" }));
+ return;
+ }
+ const socket = new WebSocket(url, [RACP_WS_SUBPROTOCOL], {
+ headers: { Authorization: `Bearer ${options.token}` },
+ handshakeTimeout: options.connectTimeoutMs ?? 10_000,
+ });
+ let settled = false;
+ socket.once("open", () => {
+ settled = true;
+ resolve({
+ send: (frame) => socket.send(frame),
+ close: (code, reason) => socket.close(code ?? 1000, reason),
+ onMessage: (handler) => {
+ socket.on("message", (data, isBinary) => {
+ if (isBinary) return;
+ handler(typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf8") : Buffer.concat(data as Buffer[]).toString("utf8"));
+ });
+ },
+ onClose: (handler) => socket.once("close", (code, reason) => handler({ code, reason: reason.toString() })),
+ onError: (handler) => socket.on("error", handler),
+ });
+ });
+ socket.once("error", (error) => {
+ if (settled) return;
+ settled = true;
+ reject(Object.assign(new Error(error.message), { errorCode: "REMOTE_CONNECTION_FAILED" }));
+ });
+ socket.once("unexpected-response", (_request, response) => {
+ if (settled) return;
+ settled = true;
+ const code = response.statusCode === 401 || response.statusCode === 403 ? "REMOTE_AUTH_FAILED" : "REMOTE_CONNECTION_FAILED";
+ reject(Object.assign(new Error(`upgrade refused: ${response.statusCode}`), { errorCode: code }));
+ socket.terminate();
+ });
+ });
+}
diff --git a/packages/racp/tsconfig.json b/packages/racp/tsconfig.json
new file mode 100644
index 000000000..bbd31e1e4
--- /dev/null
+++ b/packages/racp/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "outDir": "dist",
+ "tsBuildInfoFile": "dist/tsconfig.tsbuildinfo",
+ "rootDir": "src",
+ "composite": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*"],
+ "exclude": ["src/**/*.test.ts"],
+ "references": [{ "path": "../shared" }, { "path": "../agent-host" }]
+}
diff --git a/packages/racp/vitest.config.ts b/packages/racp/vitest.config.ts
new file mode 100644
index 000000000..ae847ff6d
--- /dev/null
+++ b/packages/racp/vitest.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ },
+});
diff --git a/packages/shared/fixtures/racp.schema.json b/packages/shared/fixtures/racp.schema.json
index ce5e4416a..11063f35a 100644
--- a/packages/shared/fixtures/racp.schema.json
+++ b/packages/shared/fixtures/racp.schema.json
@@ -1918,6 +1918,10 @@
},
"version": {
"type": "string"
+ },
+ "hostId": {
+ "type": "string",
+ "minLength": 1
}
}
},
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index 1e5479d99..8a5fbdbd8 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -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
+ * 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 --git a/packages/shared/src/racp.ts b/packages/shared/src/racp.ts
index 8b8f8d0d8..5ed730ee1 100644
--- a/packages/shared/src/racp.ts
+++ b/packages/shared/src/racp.ts
@@ -480,7 +480,12 @@ export type RacpInitializeParams = Static<typeof RacpInitializeParamsSchema>;
export 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). */
+ hostId: Type.Optional(Type.String({ minLength: 1 })),
+ }),
connectionId: Type.String({ minLength: 1 }),
principal: Type.Object({
subject: Type.String({ minLength: 1 }),
@@ -552,6 +557,12 @@ export const RACP_OPERATIONS = {
"terminal/input": { role: "controller", profile: "remote-host", mutation: true },
"terminal/resize": { role: "controller", profile: "remote-host", mutation: true },
"terminal/close": { role: "controller", profile: "remote-host", mutation: true },
+ /** Exchange a single-use pairing token for a device credential (security §3.4). */
+ "connection/pair": { role: "authenticated", profile: "remote-host", mutation: true },
+ /** Register a Host directory as a project; the Host canonicalizes and validates the path. */
+ "project/register": { role: "owner", profile: "remote-host", mutation: true },
+ /** List directories under a Host path, for the remote folder picker; bounded and owner-only. */
+ "project/browse": { role: "owner", profile: "remote-host", mutation: false },
} as const satisfies Record<string, RacpOperationSpec>;
export type RacpOperation = keyof typeof RACP_OPERATIONS;
@@ -561,6 +572,14 @@ export type RacpServerRequest = (typeof RACP_SERVER_REQUESTS)[number];
/** Notification method that carries an `EventEnvelope` on the WS binding. */
export const RACP_EVENT_NOTIFICATION = "session/event" as const;
+/** Notification the Host sends when it closes one subscription (`CLIENT_TOO_SLOW`, §8). */
+export const RACP_SUBSCRIPTION_CLOSED_NOTIFICATION = "events/closed" as const;
+/** Client notification that completes initialization (§3). */
+export const RACP_INITIALIZED_NOTIFICATION = "notifications/initialized" as const;
+
+/** Bearer scheme prefixes on the upgrade request (security §3.4). */
+export const RACP_DEVICE_TOKEN_PREFIX = "pdt1." as const;
+export const RACP_PAIRING_TOKEN_PREFIX = "ppt1." as const;
/** Operations the desktop offers locally that RACP reserves but does not expose. */
export const RACP_DEFERRED_OPERATIONS = [
@@ -758,6 +777,11 @@ export type RacpErrorSpec = { retriable: boolean | "maybe" };
export const RACP_ERROR_CODES = {
UNAUTHORIZED: { retriable: false },
+ PAIRING_FAILED: { retriable: false },
+ PAIRING_TOKEN_EXPIRED: { retriable: false },
+ CAPABILITY_UNAVAILABLE: { retriable: false },
+ REMOTE_PATH_NOT_FOUND: { retriable: false },
+ REMOTE_PATH_FORBIDDEN: { retriable: false },
FORBIDDEN: { retriable: false },
PROTOCOL_MISMATCH: { retriable: false },
METHOD_NOT_FOUND: { retriable: false },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b80c354f6..f56cd42b3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -268,6 +268,34 @@ importers:
specifier: ^4.1.10
+ packages/racp:
+ dependencies:
+ '@pi-desktop/agent-host':
+ specifier: workspace:*
+ version: link:../agent-host
+ '@pi-desktop/shared':
+ specifier: workspace:*
+ version: link:../shared
+ typebox:
+ specifier: ^1.3.13
+ version: 1.3.13
+ ws:
+ specifier: 8.21.1
+ version: 8.21.1
+ devDependencies:
+ '@types/node':
+ specifier: ^24.13.3
+ version: 24.13.3
+ '@types/ws':
+ specifier: ^8.18.1
+ version: 8.18.1
+ typescript:
+ specifier: ^5.9.3
+ version: 5.9.3
+ vitest:
+ specifier: ^4.1.10
+
packages/shared:
dependencies:
typebox: