Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(pi-host): headless RACP-WS agent host
vastsacb8898a86016
diff --git a/.gitignore b/.gitignoreindex a63800493..f08d1fbee 100644--- a/.gitignore+++ b/.gitignore@@ -17,6 +17,7 @@ apps/desktop/dist-electron/apps/desktop/release/packages/*/dist/packages/*/dist-bundle/+apps/*/dist-bundle/# Local design-source exportsdocs/image/pi_logo.pngdiff --git a/apps/pi-host/package.json b/apps/pi-host/package.jsonnew file mode 100644index 000000000..2d6a049ea--- /dev/null+++ b/apps/pi-host/package.json@@ -0,0 +1,37 @@+{+ "name": "@pi-desktop/pi-host",+ "version": "0.15.0",+ "private": true,+ "type": "module",+ "description": "Headless PI Agent Host: RACP-WS server over the Agent Host module, the pi sidecar, and host-core",+ "bin": {+ "pi-host": "./dist/cli.js"+ },+ "main": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "scripts": {+ "build": "tsc -p tsconfig.json",+ "typecheck": "tsc -p tsconfig.json --noEmit",+ "test": "vitest run",+ "bundle": "node scripts/bundle.mjs",+ "clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('dist-bundle',{recursive:true,force:true})\""+ },+ "dependencies": {+ "@pi-desktop/agent-host": "workspace:*",+ "@pi-desktop/agent-runtime": "workspace:*",+ "@pi-desktop/host-runtime": "workspace:*",+ "@pi-desktop/racp": "workspace:*",+ "@pi-desktop/shared": "workspace:*",+ "ws": "8.21.1"+ },+ "optionalDependencies": {+ "node-pty": "1.1.0"+ },+ "devDependencies": {+ "@types/node": "^24.13.3",+ "@types/ws": "^8.18.1",+ "esbuild": "^0.25.12",+ "typescript": "^5.9.3",+ "vitest": "^4.1.10"+ }+}diff --git a/apps/pi-host/scripts/bundle.mjs b/apps/pi-host/scripts/bundle.mjsnew file mode 100644index 000000000..44f8e4405--- /dev/null+++ b/apps/pi-host/scripts/bundle.mjs@@ -0,0 +1,89 @@+#!/usr/bin/env node+/**+ * Assemble the self-contained `pi-host` bundle for one Linux target:+ *+ * dist-bundle/pi-host-<version>-<platform>-<arch>/+ * pi-host.js the CLI, esbuild-bundled with every workspace package+ * agent-runtime/sidecar.js the same sidecar bundle the desktop ships+ * bin/pi-desktop-host-core the platform host-core binary+ * node_modules/node-pty optional; terminals are disabled without it+ * package.json { type: module, version }+ * install.sh copies the bundle under ~/.pi-desktop/pi-host/<version>+ *+ * Usage: node scripts/bundle.mjs [--host-core <path>] [--platform linux] [--arch x64|arm64] [--out <dir>]+ */+import { execFileSync } from "node:child_process";+import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync, chmodSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { createRequire } from "node:module";++const here = dirname(fileURLToPath(import.meta.url));+const app = resolve(here, "..");+const root = resolve(app, "../..");+const require = createRequire(import.meta.url);+const { version } = require(join(app, "package.json"));++const args = Object.fromEntries(+ process.argv.slice(2).flatMap((arg, index, all) => (arg.startsWith("--") && arg.length > 2 ? [[arg.slice(2), all[index + 1] && !all[index + 1].startsWith("--") ? all[index + 1] : true]] : [])),+);+const platform = String(args.platform ?? process.platform);+const arch = String(args.arch ?? process.arch);+const exe = platform === "win32" ? ".exe" : "";+const hostCore = resolve(String(args["host-core"] ?? join(root, `target/release/pi-desktop-host-core${exe}`)));+const sidecar = join(root, "packages/agent-runtime/dist-bundle/sidecar.js");+const out = resolve(String(args.out ?? join(app, "dist-bundle", `pi-host-${version}-${platform}-${arch}`)));++for (const [label, path] of [["host-core binary", hostCore], ["sidecar bundle", sidecar]]) {+ if (!existsSync(path)) {+ console.error(`${label} missing: ${path}`);+ process.exit(1);+ }+}++rmSync(out, { recursive: true, force: true });+mkdirSync(join(out, "bin"), { recursive: true });+mkdirSync(join(out, "agent-runtime"), { recursive: true });++execFileSync(+ require.resolve("esbuild/bin/esbuild"),+ [+ join(app, "src/cli.ts"),+ "--bundle",+ "--platform=node",+ "--format=esm",+ "--target=node22",+ "--external:node-pty",+ "--external:bufferutil",+ "--external:utf-8-validate",+ `--outfile=${join(out, "pi-host.js")}`,+ "--banner:js=import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);",+ ],+ { stdio: "inherit", cwd: app },+);+cpSync(sidecar, join(out, "agent-runtime/sidecar.js"));+writeFileSync(join(out, "agent-runtime/package.json"), '{ "type": "module" }\n');+cpSync(hostCore, join(out, `bin/pi-desktop-host-core${exe}`));+chmodSync(join(out, `bin/pi-desktop-host-core${exe}`), 0o755);+try {+ const pty = dirname(require.resolve("node-pty/package.json"));+ cpSync(pty, join(out, "node_modules/node-pty"), { recursive: true, dereference: true });+} catch {+ console.warn("node-pty not installed; the bundle ships without terminals");+}+writeFileSync(join(out, "package.json"), `${JSON.stringify({ name: "pi-host", version, type: "module", bin: { "pi-host": "./pi-host.js" } }, null, 2)}\n`);+writeFileSync(+ join(out, "install.sh"),+ `#!/bin/sh+# Install this pi-host bundle under the user's home (D375 bootstrap).+set -eu+target="\${PI_HOST_INSTALL_DIR:-$HOME/.pi-desktop/pi-host}/${version}"+mkdir -p "$target"+cp -R "$(dirname "$0")"/. "$target"/+chmod 755 "$target/bin/pi-desktop-host-core${exe}"+ln -sfn "$target" "$(dirname "$target")/current"+echo "PI_HOST_INSTALLED $target"+`,+);+chmodSync(join(out, "install.sh"), 0o755);+console.log(`bundled ${out}`);diff --git a/apps/pi-host/src/app.ts b/apps/pi-host/src/app.tsnew file mode 100644index 000000000..31833564c--- /dev/null+++ b/apps/pi-host/src/app.ts@@ -0,0 +1,283 @@+import { mkdir } from "node:fs/promises";+import { join } from "node:path";++import { AgentHost, type ApprovalPort } from "@pi-desktop/agent-host";+import {+ AgentSidecar,+ HostProcess,+ PlanExecutionDispatcher,+ RuntimeService,+ RuntimeSupervisor,+ createHeadlessLaunchResolver,+ createHostQueueStore,+ createHostSessionPort,+ listPendingToolRequests,+} from "@pi-desktop/host-runtime";+import { DeviceTokenAuthenticator, RacpServer, bindRacpWebSocket, type RacpHostOperations, type WsBinding } from "@pi-desktop/racp";+import { APP_VERSION, type AgentEventEnvelope } from "@pi-desktop/shared";++import type { PiHostConfig } from "./config.js";+import { FileCredentialStore, loadOrCreateHostId } from "./credentials.js";+import { createHostOperations } from "./host-operations.js";+import { createLogger, type HostLogger } from "./logger.js";+import { TerminalService, loadPty } from "./terminal.js";++export type PiHostApp = {+ hostId: string;+ address: { host: string; port: number };+ agentHost: AgentHost;+ runtime: RuntimeService;+ authenticator: DeviceTokenAuthenticator;+ server: RacpServer;+ log: HostLogger;+ /** Mint a single-use pairing token for the bootstrap channel. */+ issuePairingToken(lifetimeMs: number): Promise<{ token: string; expiresAt: string }>;+ stop(): Promise<void>;+};++const APPROVAL_REQUEST_TIMEOUT_MS = 30 * 60 * 1000;++/**+ * Compose the headless Host: host-core and the sidecar under the shared+ * supervisor, the runtime service as the module's runtime port, the Agent+ * Host module, and the RACP server on loopback. Everything the desktop+ * would own for a local session — transcript, queue, approvals, tools,+ * workspace — lives here on this machine.+ */+export async function startPiHost(config: PiHostConfig, options: { log?: HostLogger } = {}): Promise<PiHostApp> {+ await mkdir(config.dataDir, { recursive: true, mode: 0o700 });+ const log = options.log ?? createLogger({ dataDir: config.dataDir, minLevel: config.logLevel });+ const hostId = await loadOrCreateHostId(config.dataDir);+ const store = new FileCredentialStore(config.dataDir);+ const authenticator = new DeviceTokenAuthenticator(store);++ const state: { host: HostProcess | null; sidecar: AgentSidecar | null; stopping: boolean } = { host: null, sidecar: null, stopping: false };+ const getHost = () => state.host;+ const getSidecar = () => state.sidecar;++ const launch = createHeadlessLaunchResolver({ getHost, dataDir: config.dataDir, log: (level, message, data) => log(level, message, data) });+ const runtime = new RuntimeService({ getHost, getSidecar, launch, log });++ const approvals: ApprovalPort = {+ async resolveTool(requestId, decision) {+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ await host.call("permissions.resolve", { requestId, decision });+ },+ async resolveContract(input) {+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ const pending = await host.call<{ plans?: Array<{ id: string; turnId?: string; toolCallId?: string }> }>("plans.pending", { sessionId: input.sessionId });+ const proposal = (pending.plans ?? []).find((candidate) => candidate.id === input.proposalId);+ if (!proposal) throw Object.assign(new Error(`proposal ${input.proposalId} is not pending`), { errorCode: "NOT_FOUND" });+ const result = await host.call("plans.resolve", {+ proposalId: input.proposalId,+ sessionId: input.sessionId,+ turnId: proposal.turnId ?? "",+ toolCallId: proposal.toolCallId ?? "",+ action: input.action,+ ...(input.version !== undefined ? { version: input.version } : {}),+ ...(input.permissionMode ? { targetPermissionMode: input.permissionMode } : {}),+ });+ if (input.action === "approve") void plans.dispatchExecutionForProposal(input.proposalId);+ return void result;+ },+ listPendingTools: (sessionId) => listPendingToolRequests(getHost, sessionId),+ };+ const agentHost = new AgentHost({+ runtime,+ sessions: createHostSessionPort(getHost),+ approvals,+ queueStore: createHostQueueStore(getHost),+ localApprovalLifetimeMs: APPROVAL_REQUEST_TIMEOUT_MS,+ });+ const plans = new PlanExecutionDispatcher({ getHost, getSidecar, launch, runtime, log });++ // Every runtime event feeds the module; a settled turn closes it there too.+ const abortingSessions = new Set<string>();+ runtime.onEvent((envelope: AgentEventEnvelope) => {+ const interrupted = envelope.event.type === "agent_end" && abortingSessions.has(envelope.sessionId);+ if (envelope.event.type === "agent_end" || envelope.event.type === "error") abortingSessions.delete(envelope.sessionId);+ try {+ agentHost.ingest(envelope, { interrupted });+ } catch (error) {+ log("warn", "agent host ingest failed", { sessionId: envelope.sessionId, type: envelope.event.type, error: String(error) });+ }+ });+ runtime.onTurnEnded((info) => {+ abortingSessions.delete(info.sessionId);+ const status = info.reason === "aborted" ? "interrupted" : info.reason === "error" ? "failed" : "completed";+ try {+ agentHost.endTurn(info.sessionId, info.turnId, status, info.errorCode ? { error: { code: info.errorCode, message: info.errorCode, retriable: false, traceId: "" } } : {});+ agentHost.kick(info.sessionId);+ } catch (error) {+ log("warn", "agent host end turn failed", { sessionId: info.sessionId, turnId: info.turnId, error: String(error) });+ }+ });+ const originalAbort = runtime.abort.bind(runtime);+ runtime.abort = async (sessionId, turnId) => {+ abortingSessions.add(sessionId);+ try {+ await originalAbort(sessionId, turnId);+ } catch (error) {+ abortingSessions.delete(sessionId);+ throw error;+ }+ };++ const startHost = async () => {+ const host = new HostProcess({ binaryPath: config.hostCoreBinary, dataDir: config.dataDir, onStderr: log.child("host") });+ host.onExit(({ intentional }) => {+ if (state.host !== host) return;+ state.host = null;+ if (intentional || state.stopping) return;+ log("error", "host-core exited unexpectedly");+ void supervisor.superviseRestart("host");+ });+ state.host = host;+ try {+ await host.handshake();+ await host.call("session.recoverInflightMessages").catch((error: unknown) => log("warn", "in-flight recovery failed", { error: String(error) }));+ } catch (error) {+ if (state.host === host) state.host = null;+ await host.dispose();+ throw error;+ }+ runtime.attachHost(host);+ state.sidecar?.setHost(host);+ log("info", "host-core handshake ok", { generation: host.generation });+ };+ const startSidecar = async () => {+ const sidecar = new AgentSidecar({+ launch: { command: config.nodeBinary, args: [config.sidecarEntry], env: { ...process.env, PI_DESKTOP_DATA_DIR: config.dataDir } },+ onStderr: log.child("agent"),+ });+ sidecar.onExit(({ intentional, code, signal, stderrTail }) => {+ if (state.sidecar !== sidecar) return;+ state.sidecar = null;+ if (intentional || state.stopping) return;+ log("error", "agent sidecar exited unexpectedly", { exitCode: code, signal, stderrTail });+ void supervisor.superviseRestart("sidecar");+ });+ sidecar.setProjectInstructionResolver(async ({ projectPath, path }) => {+ const { loadInstructionChain } = await import("@pi-desktop/agent-runtime");+ return loadInstructionChain(projectPath, path);+ });+ sidecar.setLocalTool("Skill", async ({ args, sessionId }) => {+ const id = String((args as { id?: unknown })?.id ?? "").trim();+ const host = getHost();+ if (!id || !host) return { ok: false, isError: true, content: "Skill: `id` is required." };+ const session = await host.call<{ session?: { projectPath?: string } | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(() => null);+ const result = await host.call<{ skill: { id: string; name: string } | null; body: string | null }>("skills.read", { id, projectPath: session?.session?.projectPath ?? null }).catch(() => null);+ if (!result?.skill || typeof result.body !== "string") return { ok: false, isError: true, content: `Skill: "${id}" is not available on this Host.` };+ return { ok: true, content: `# Skill: ${result.skill.name} (${result.skill.id})\n\n${result.body}` };+ });+ sidecar.setTrustedExtensionBridge({+ publishCommands: () => undefined,+ publishDiagnostics: () => undefined,+ requestUi: async () => {+ throw new Error("extension UI is not available on a headless host");+ },+ configureModel: async () => {+ throw new Error("extension model configuration is not available on a headless host");+ },+ queuePush: async (params) =>+ agentHost.startTurn({ subject: "extension", roles: ["controller"] }, {+ sessionId: String(params.sessionId ?? ""),+ admission: "queue",+ input: { text: String(params.content ?? "") },+ context: { requestId: `ext-${Date.now().toString(36)}`, ...(typeof params.idempotencyKey === "string" ? { idempotencyKey: params.idempotencyKey } : {}) },+ }),+ queuePrioritize: async (params) => agentHost.prioritizeTurn({ subject: "extension", roles: ["controller"] }, String(params.id ?? "")),+ });+ state.sidecar = sidecar;+ runtime.attachSidecar(sidecar);+ if (state.host) sidecar.setHost(state.host);+ await sidecar.call("sidecar.configure", { hostBinary: config.hostCoreBinary, dataDir: config.dataDir });+ log("info", "agent sidecar configured");+ };+ const supervisor = new RuntimeSupervisor({+ start: { host: startHost, sidecar: startSidecar },+ afterRestart: () => plans.drainApprovedPlanExecutions(),+ isShuttingDown: () => state.stopping,+ onEvent: (event) => {+ if (event.phase === "fatal") log("error", `${event.kind} restart gave up`, { reason: event.reason, error: event.error ? String(event.error) : undefined });+ else if (event.phase === "restarted") log("warn", `${event.kind} restarted after crash`, { attempt: event.attempt });+ else if (event.phase === "restart_failed") log("error", `${event.kind} restart failed`, { attempt: event.attempt, error: String(event.error) });+ },+ });++ await startHost();+ await startSidecar();+ await agentHost.start();+ await plans.drainApprovedPlanExecutions().catch((error: unknown) => log("warn", "queued approved plan drain failed", { error: String(error) }));++ const pty = loadPty();+ const terminal = pty+ ? new TerminalService({+ pty,+ log,+ sessionRoot: async (sessionId) => {+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ const result = await host.call<{ session?: { projectPath?: string } | null }>("session.get", { id: sessionId, messageLimit: 1 });+ const root = result.session?.projectPath?.trim();+ if (!root) throw Object.assign(new Error("the session has no project root"), { errorCode: "CONFLICT" });+ return root;+ },+ })+ : undefined;+ if (!pty) log("warn", "node-pty is not installed; terminals are disabled");++ const operations: RacpHostOperations = {+ ...createHostOperations({+ getHost,+ runtime,+ browseRoot: config.browseRoot,+ disposeSession: async (sessionId) => {+ const sidecar = getSidecar();+ if (!sidecar) return;+ sidecar.clearProjectInstructionRoot(sessionId);+ await sidecar.call("agent.disposeSession", { sessionId }).catch(() => undefined);+ },+ revokeDevice: (deviceId) => store.revokeDevice(deviceId, new Date().toISOString()),+ }),+ ...(terminal ? { terminal } : {}),+ };+ const server = new RacpServer({ agentHost, operations, authenticator, hostId, serverVersion: APP_VERSION, log });+ let binding: WsBinding;+ try {+ binding = await bindRacpWebSocket({ server: server, authenticator, host: config.host, port: config.port, log });+ } catch (error) {+ state.stopping = true;+ await state.sidecar?.dispose();+ await state.host?.dispose();+ throw error;+ }+ log("info", "pi-host ready", { hostId, host: binding.address.host, port: binding.address.port, version: APP_VERSION, terminal: Boolean(terminal) });++ return {+ hostId,+ address: binding.address,+ agentHost,+ runtime,+ authenticator,+ server,+ log,+ issuePairingToken: (lifetimeMs) => authenticator.issuePairingToken(lifetimeMs),+ async stop() {+ if (state.stopping) return;+ state.stopping = true;+ log("info", "pi-host stopping");+ server.close();+ await binding.close();+ await terminal?.closeAll();+ plans.dispose();+ await runtime.dispose();+ await state.sidecar?.dispose();+ await state.host?.dispose();+ state.sidecar = null;+ state.host = null;+ },+ };+}diff --git a/apps/pi-host/src/cli.ts b/apps/pi-host/src/cli.tsnew file mode 100644index 000000000..5ae655207--- /dev/null+++ b/apps/pi-host/src/cli.ts@@ -0,0 +1,60 @@+#!/usr/bin/env node+import { parseArgs, resolveConfig } from "./config.js";+import { startPiHost } from "./app.js";++/**+ * `pi-host [--data-dir <dir>] [--port <n>] [--pair] [--host-core <bin>] [--sidecar <entry>]`+ *+ * stdout carries exactly the lines a bootstrap script parses:+ * PI_HOST_READY {"hostId":..,"port":..,"version":..}+ * PI_HOST_PAIRING_TOKEN {"token":..,"expiresAt":..} (with --pair)+ * Everything else is structured stderr.+ */+async function main(): Promise<void> {+ const args = parseArgs(process.argv.slice(2));+ if (args.help === true) {+ process.stdout.write(+ [+ "pi-host — headless PI Agent Host (RACP-WS on loopback)",+ "",+ " --data-dir <dir> host data directory (default ~/.pi-desktop)",+ " --port <n> loopback port (default 0 = pick free)",+ " --host <addr> bind address; loopback only",+ " --pair print a single-use pairing token at start",+ " --pairing-lifetime-ms <n> pairing token lifetime (default 600000)",+ " --host-core <path> pi-desktop-host-core binary",+ " --sidecar <path> agent sidecar entry",+ " --browse-root <dir> folder-picker root (default home)",+ " --log-level <level> info | warn | error",+ "",+ ].join("\n"),+ );+ return;+ }+ const config = resolveConfig(args);+ const app = await startPiHost(config);+ process.stdout.write(`PI_HOST_READY ${JSON.stringify({ hostId: app.hostId, host: app.address.host, port: app.address.port, version: (await import("@pi-desktop/shared")).APP_VERSION })}\n`);+ if (config.pair) {+ const pairing = await app.issuePairingToken(config.pairingLifetimeMs);+ process.stdout.write(`PI_HOST_PAIRING_TOKEN ${JSON.stringify(pairing)}\n`);+ }+ const stop = (signal: string) => {+ app.log("info", "signal received", { signal });+ void app.stop().finally(() => process.exit(0));+ };+ process.once("SIGINT", () => stop("SIGINT"));+ process.once("SIGTERM", () => stop("SIGTERM"));+ process.on("unhandledRejection", (reason) => {+ app.log("error", "unhandled rejection", { error: reason instanceof Error ? reason.stack ?? reason.message : String(reason) });+ });+ process.on("uncaughtException", (error) => {+ app.log("error", "uncaught exception", { error: error.stack ?? error.message });+ });+}++main().catch((error) => {+ const code = (error as { errorCode?: string })?.errorCode ?? "INTERNAL";+ process.stderr.write(`${JSON.stringify({ ts: new Date().toISOString(), level: "error", channel: "pi-host", message: "pi-host failed to start", data: { code, error: error instanceof Error ? error.message : String(error) } })}\n`);+ process.stdout.write(`PI_HOST_FAILED ${JSON.stringify({ code })}\n`);+ process.exit(1);+});diff --git a/apps/pi-host/src/config.test.ts b/apps/pi-host/src/config.test.tsnew file mode 100644index 000000000..1063cc327--- /dev/null+++ b/apps/pi-host/src/config.test.ts@@ -0,0 +1,64 @@+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { parseArgs, resolveConfig } from "./config.js";+import { FileCredentialStore, loadOrCreateHostId } from "./credentials.js";++const dirs: string[] = [];+afterEach(async () => {+ for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });+});++async function tempDir(): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), "pi-host-test-"));+ dirs.push(dir);+ return dir;+}++describe("config", () => {+ it("parses flags with and without values and validates the port", () => {+ expect(parseArgs(["--pair", "--port", "4123", "--data-dir=/x", "--host-core", "/bin/hc"])).toEqual({ pair: true, port: "4123", "data-dir": "/x", "host-core": "/bin/hc" });+ const config = resolveConfig({ "data-dir": "/data", port: "4123", "host-core": "/bin/hc", sidecar: "/s.js", pair: true }, {});+ expect(config).toMatchObject({ dataDir: "/data", port: 4123, host: "127.0.0.1", hostCoreBinary: "/bin/hc", sidecarEntry: "/s.js", pair: true, logLevel: "info" });+ expect(() => resolveConfig({ port: "70000", "host-core": "/bin/hc", sidecar: "/s.js" }, {})).toThrow(/invalid port/);+ expect(() => resolveConfig({ "host-core": "/bin/hc", sidecar: "/s.js", port: "abc" }, {})).toThrow(/invalid port/);+ expect(resolveConfig({ "host-core": "/bin/hc", sidecar: "/s.js", "log-level": "warn" }, {}).logLevel).toBe("warn");+ });+});++describe("identity and credentials", () => {+ it("mints the host id once and keeps it across restarts", async () => {+ const dir = await tempDir();+ const first = await loadOrCreateHostId(dir);+ expect(first.startsWith("host_")).toBe(true);+ expect(await loadOrCreateHostId(dir)).toBe(first);+ const info = await stat(join(dir, "pi-host", "identity.json"));+ expect(info.mode & 0o077).toBe(0);+ });++ it("stores devices and pairings hashed, owner-readable, and survives a reload", async () => {+ const dir = await tempDir();+ const store = new FileCredentialStore(dir);+ await store.saveDevice({ deviceId: "dev_1", label: "laptop", roles: ["owner"], tokenHash: "ab".repeat(32), createdAt: "2026-09-18T00:00:00.000Z" });+ await store.savePairing({ tokenHash: "cd".repeat(32), expiresAt: new Date(Date.now() + 60_000).toISOString() });+ await store.savePairing({ tokenHash: "ef".repeat(32), expiresAt: "2000-01-01T00:00:00.000Z" });+ const raw = await readFile(join(dir, "pi-host", "credentials.json"), "utf8");+ expect(raw).not.toContain("pdt1.");+ expect(raw).toContain("ab".repeat(32));+ expect(raw).not.toContain("ef".repeat(32));+ const info = await stat(join(dir, "pi-host", "credentials.json"));+ expect(info.mode & 0o077).toBe(0);++ const reloaded = new FileCredentialStore(dir);+ expect((await reloaded.findDeviceByTokenHash("ab".repeat(32)))?.deviceId).toBe("dev_1");+ expect(await reloaded.consumePairing("cd".repeat(32), "2026-09-18T00:00:01.000Z")).toBe(true);+ expect(await reloaded.consumePairing("cd".repeat(32), "2026-09-18T00:00:02.000Z")).toBe(false);+ expect(await reloaded.revokeDevice("dev_1", "2026-09-18T00:00:03.000Z")).toBe(true);+ expect(await reloaded.revokeDevice("dev_1", "2026-09-18T00:00:04.000Z")).toBe(false);+ const again = new FileCredentialStore(dir);+ expect((await again.listDevices())[0]?.revokedAt).toBe("2026-09-18T00:00:03.000Z");+ expect(await again.findPairing("cd".repeat(32))).toBeNull();+ });+});diff --git a/apps/pi-host/src/config.ts b/apps/pi-host/src/config.tsnew file mode 100644index 000000000..db90d6d02--- /dev/null+++ b/apps/pi-host/src/config.ts@@ -0,0 +1,103 @@+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++export type PiHostConfig = {+ dataDir: string;+ /** Loopback bind address; `pi-host` refuses anything else. */+ host: string;+ /** `0` picks a free port and prints it. */+ port: number;+ hostCoreBinary: string;+ sidecarEntry: string;+ /** The Node executable used for the sidecar; defaults to this process's. */+ nodeBinary: string;+ /** Print a fresh single-use pairing token at start and exit once it is consumed or expired. */+ pair: boolean;+ pairingLifetimeMs: number;+ /** Where the folder picker may browse; defaults to the user's home. */+ browseRoot: string;+ logLevel: "info" | "warn" | "error";+};++const DEFAULT_PORT = 0;+const DEFAULT_PAIRING_LIFETIME_MS = 10 * 60 * 1000;++function here(): string {+ return dirname(fileURLToPath(import.meta.url));+}++/** Locations the bundle and a source checkout keep host-core in, first hit wins. */+export function hostCoreCandidates(root = here()): string[] {+ const exe = process.platform === "win32" ? ".exe" : "";+ return [+ process.env.PI_HOST_CORE_BIN ?? "",+ process.env.PI_DESKTOP_HOST_BIN ?? "",+ join(root, `bin/pi-desktop-host-core${exe}`),+ join(root, `../bin/pi-desktop-host-core${exe}`),+ join(root, `../../../target/release/pi-desktop-host-core${exe}`),+ join(root, `../../../target/debug/pi-desktop-host-core${exe}`),+ ].filter(Boolean);+}++export function sidecarCandidates(root = here()): string[] {+ return [+ process.env.PI_HOST_SIDECAR ?? "",+ join(root, "agent-runtime/sidecar.js"),+ join(root, "../agent-runtime/sidecar.js"),+ join(root, "../../../packages/agent-runtime/dist-bundle/sidecar.js"),+ join(root, "../../../packages/agent-runtime/dist/sidecar.js"),+ ].filter(Boolean);+}++function firstExisting(candidates: string[], what: string): string {+ for (const candidate of candidates) {+ if (candidate && existsSync(candidate)) return resolve(candidate);+ }+ throw Object.assign(new Error(`${what} not found; tried ${candidates.join(", ")}`), { errorCode: "HOST_BOOTSTRAP_FAILED" });+}++export type CliArgs = Record<string, string | boolean>;++export function parseArgs(argv: string[]): CliArgs {+ const args: CliArgs = {};+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index]!;+ if (!arg.startsWith("--")) continue;+ const eq = arg.indexOf("=");+ if (eq > 0) {+ args[arg.slice(2, eq)] = arg.slice(eq + 1);+ continue;+ }+ const next = argv[index + 1];+ if (next !== undefined && !next.startsWith("--")) {+ args[arg.slice(2)] = next;+ index += 1;+ } else {+ args[arg.slice(2)] = true;+ }+ }+ return args;+}++export function resolveConfig(args: CliArgs, env: NodeJS.ProcessEnv = process.env): PiHostConfig {+ const dataDir = resolve(String(args["data-dir"] ?? env.PI_DESKTOP_DATA_DIR ?? join(homedir(), ".pi-desktop")));+ const port = Number(args.port ?? env.PI_HOST_PORT ?? DEFAULT_PORT);+ if (!Number.isInteger(port) || port < 0 || port > 65_535) {+ throw Object.assign(new Error(`invalid port ${String(args.port ?? env.PI_HOST_PORT)}`), { errorCode: "INVALID_ARGUMENT" });+ }+ const level = String(args["log-level"] ?? env.PI_HOST_LOG_LEVEL ?? "info");+ return {+ dataDir,+ host: String(args.host ?? env.PI_HOST_BIND ?? "127.0.0.1"),+ port,+ hostCoreBinary: args["host-core"] ? resolve(String(args["host-core"])) : firstExisting(hostCoreCandidates(), "host-core binary"),+ sidecarEntry: args.sidecar ? resolve(String(args.sidecar)) : firstExisting(sidecarCandidates(), "agent sidecar entry"),+ nodeBinary: String(args.node ?? env.PI_HOST_NODE ?? process.execPath),+ pair: args.pair === true || args.pair === "true",+ pairingLifetimeMs: Number(args["pairing-lifetime-ms"] ?? DEFAULT_PAIRING_LIFETIME_MS),+ browseRoot: resolve(String(args["browse-root"] ?? env.PI_HOST_BROWSE_ROOT ?? homedir())),+ logLevel: level === "warn" || level === "error" ? level : "info",+ };+}diff --git a/apps/pi-host/src/credentials.ts b/apps/pi-host/src/credentials.tsnew file mode 100644index 000000000..6223078a5--- /dev/null+++ b/apps/pi-host/src/credentials.ts@@ -0,0 +1,119 @@+import { randomBytes } from "node:crypto";+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";++import type { DeviceCredentialStore, DeviceRecord, PairingRecord } from "@pi-desktop/racp";++type IdentityFile = { hostId: string; createdAt: string };+type CredentialFile = { devices: DeviceRecord[]; pairings: PairingRecord[] };++const FILE_MODE = 0o600;++async function readJson<T>(path: string): Promise<T | null> {+ try {+ return JSON.parse(await readFile(path, "utf8")) as T;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw error;+ }+}++async function writeJsonAtomic(path: string, value: unknown): Promise<void> {+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });+ const temp = `${path}.${process.pid}.tmp`;+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: FILE_MODE });+ await rename(temp, path);+}++/**+ * The Host's stable identity (D446): minted once at first start and kept+ * beside the data directory. Never derived from hostname, address, or path,+ * so two machines with the same project path are still two Hosts.+ */+export async function loadOrCreateHostId(dataDir: string): Promise<string> {+ const path = join(dataDir, "pi-host", "identity.json");+ const existing = await readJson<IdentityFile>(path);+ if (existing?.hostId) return existing.hostId;+ const created: IdentityFile = { hostId: `host_${randomBytes(12).toString("base64url")}`, createdAt: new Date().toISOString() };+ await writeJsonAtomic(path, created);+ return created.hostId;+}++/**+ * Device and pairing records under `<dataDir>/pi-host/credentials.json`,+ * owner-readable only. Tokens are stored as SHA-256 hashes (security §3.4);+ * the file never holds a usable credential.+ */+export class FileCredentialStore implements DeviceCredentialStore {+ private readonly path: string;+ private state: CredentialFile | null = null;+ private chain = Promise.resolve();++ constructor(dataDir: string) {+ this.path = join(dataDir, "pi-host", "credentials.json");+ }++ private async load(): Promise<CredentialFile> {+ if (!this.state) this.state = (await readJson<CredentialFile>(this.path)) ?? { devices: [], pairings: [] };+ return this.state;+ }++ private async mutate<T>(operation: (state: CredentialFile) => T): Promise<T> {+ let result!: T;+ const run = this.chain.then(async () => {+ const state = await this.load();+ result = operation(state);+ // Expired, consumed pairings are useless after a write; drop them.+ const now = Date.now();+ state.pairings = state.pairings.filter((pairing) => !pairing.consumedAt && Date.parse(pairing.expiresAt) > now);+ await writeJsonAtomic(this.path, state);+ });+ this.chain = run.catch(() => undefined);+ await run;+ return result;+ }++ async findDeviceByTokenHash(tokenHash: string): Promise<DeviceRecord | null> {+ const state = await this.load();+ return state.devices.find((device) => device.tokenHash === tokenHash) ?? null;+ }+ async saveDevice(record: DeviceRecord): Promise<void> {+ await this.mutate((state) => {+ state.devices = [...state.devices.filter((device) => device.deviceId !== record.deviceId), record];+ });+ }+ async touchDevice(deviceId: string, seenAt: string): Promise<void> {+ const state = await this.load();+ const device = state.devices.find((candidate) => candidate.deviceId === deviceId);+ // Last-seen is informational; it does not need a synchronous write per connection.+ if (device) device.lastSeenAt = seenAt;+ }+ async revokeDevice(deviceId: string, revokedAt: string): Promise<boolean> {+ return this.mutate((state) => {+ const device = state.devices.find((candidate) => candidate.deviceId === deviceId);+ if (!device || device.revokedAt) return false;+ device.revokedAt = revokedAt;+ return true;+ });+ }+ async listDevices(): Promise<DeviceRecord[]> {+ return [...(await this.load()).devices];+ }+ async findPairing(tokenHash: string): Promise<PairingRecord | null> {+ const state = await this.load();+ return state.pairings.find((pairing) => pairing.tokenHash === tokenHash) ?? null;+ }+ async savePairing(record: PairingRecord): Promise<void> {+ await this.mutate((state) => {+ state.pairings = [...state.pairings.filter((pairing) => pairing.tokenHash !== record.tokenHash), record];+ });+ }+ async consumePairing(tokenHash: string, consumedAt: string): Promise<boolean> {+ return this.mutate((state) => {+ const pairing = state.pairings.find((candidate) => candidate.tokenHash === tokenHash);+ if (!pairing || pairing.consumedAt) return false;+ pairing.consumedAt = consumedAt;+ return true;+ });+ }+}diff --git a/apps/pi-host/src/host-operations.test.ts b/apps/pi-host/src/host-operations.test.tsnew file mode 100644index 000000000..e077a890b--- /dev/null+++ b/apps/pi-host/src/host-operations.test.ts@@ -0,0 +1,108 @@+import { mkdtemp, realpath, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { RacpError } from "@pi-desktop/agent-host";++import { createHostOperations } from "./host-operations.js";++const dirs: string[] = [];+afterEach(async () => {+ for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });+});++function fakeHost(calls: Array<{ method: string; params: unknown }>, projectPath: string) {+ const sessions = new Map<string, Record<string, unknown>>([["s1", { id: "s1", title: "One", mode: "agent", permissionMode: "ask", projectPath }]]);+ return {+ async call<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {+ calls.push({ method, params });+ switch (method) {+ case "session.list":+ return { sessions: [...sessions.values()] } as T;+ case "session.get":+ return { session: sessions.get(String(params.id)) ?? null } as T;+ case "session.create": {+ const created = { id: "s2", title: params.title ?? "New", mode: params.mode ?? "agent", permissionMode: "ask", projectPath: params.projectPath };+ sessions.set("s2", created);+ return { session: created } as T;+ }+ case "session.configure": {+ const current = sessions.get(String(params.id));+ if (!current) throw Object.assign(new Error("session not found"), { errorCode: "NOT_FOUND" });+ const next = { ...current, ...(params.permissionMode ? { permissionMode: params.permissionMode } : {}), mode: params.mode };+ sessions.set(String(params.id), next);+ return { session: next } as T;+ }+ case "session.rename":+ case "session.delete":+ return { ok: true } as T;+ case "projects.list":+ return { projects: [{ id: 7, path: projectPath, name: "proj" }] } as T;+ case "projects.create":+ return { project: { id: 8, path: params.path, name: "app" } } as T;+ default:+ throw new Error(`unexpected ${method}`);+ }+ },+ };+}++describe("pi-host operations over host-core", () => {+ it("maps sessions, creates under a project id, and refuses configuration while busy", async () => {+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-host-ops-")));+ dirs.push(root);+ const calls: Array<{ method: string; params: unknown }> = [];+ let busy = false;+ const operations = createHostOperations({+ getHost: () => fakeHost(calls, root),+ runtime: { compact: async () => ({ accepted: true }), isBusy: () => busy },+ browseRoot: root,+ });+ const listed = await operations.sessions.list();+ expect(listed[0]).toMatchObject({ id: "s1", workspaceLabel: root.split("/").pop() });+ const created = await operations.sessions.create({ title: "T", projectId: "7", permissionMode: "auto" }, { subject: "d", roles: ["owner"] });+ expect(created.permissionMode).toBe("auto");+ expect(calls.find((call) => call.method === "session.create")?.params).toMatchObject({ projectPath: root });+ await expect(operations.sessions.create({ projectId: "99" }, { subject: "d", roles: ["owner"] })).rejects.toMatchObject({ code: "NOT_FOUND" });+ busy = true;+ await expect(operations.sessions.configure("s1", { mode: "plan" })).rejects.toMatchObject({ code: "CONFLICT" });+ busy = false;+ expect((await operations.sessions.configure("s1", { permissionMode: "accept-edits" })).permissionMode).toBe("accept-edits");+ });++ it("registers only existing directories and browses inside the root only", async () => {+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-host-ops-")));+ dirs.push(root);+ const { mkdir } = await import("node:fs/promises");+ await mkdir(join(root, "work", "app"), { recursive: true });+ await mkdir(join(root, ".hidden"), { recursive: true });+ const operations = createHostOperations({ getHost: () => fakeHost([], root), runtime: { compact: async () => ({ accepted: true }), isBusy: () => false }, browseRoot: root });+ const registered = await operations.projects.register(join(root, "work", "app"));+ expect(registered).toMatchObject({ id: "8", label: "app" });+ await expect(operations.projects.register(join(root, "missing"))).rejects.toMatchObject({ code: "REMOTE_PATH_NOT_FOUND" });+ await expect(operations.projects.register("relative/path")).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });+ const top = await operations.projects.browse();+ expect(top.entries.map((entry) => entry.name)).toEqual(["work"]);+ expect(top.parent).toBeUndefined();+ const nested = await operations.projects.browse(join(root, "work"));+ expect(nested.entries.map((entry) => entry.name)).toEqual(["app"]);+ expect(nested.parent).toBeDefined();+ await expect(operations.projects.browse("/")).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });+ });++ it("serves workspace reads against the session root and refuses escapes", async () => {+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-host-ops-")));+ dirs.push(root);+ const { writeFile } = await import("node:fs/promises");+ await writeFile(join(root, "README.md"), "hello", "utf8");+ const operations = createHostOperations({ getHost: () => fakeHost([], root), runtime: { compact: async () => ({ accepted: true }), isBusy: () => false } });+ expect((await operations.workspace.list("s1", "")).entries.map((entry) => entry.name)).toEqual(["README.md"]);+ expect(await operations.workspace.read("s1", "README.md")).toMatchObject({ kind: "text", content: "hello" });+ await expect(operations.workspace.read("s1", "../../etc/passwd")).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });+ await expect(operations.workspace.read("s1", "nope.txt")).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });+ await expect(operations.workspace.list("s9", "")).rejects.toBeInstanceOf(RacpError);+ const diff = await operations.workspace.diff("s1");+ expect(diff.repo).toBe(false);+ });+});diff --git a/apps/pi-host/src/host-operations.ts b/apps/pi-host/src/host-operations.tsnew file mode 100644index 000000000..12034a4b6--- /dev/null+++ b/apps/pi-host/src/host-operations.ts@@ -0,0 +1,251 @@+import { readdir, realpath, stat } from "node:fs/promises";+import { homedir } from "node:os";+import { basename, dirname, isAbsolute, join, resolve } from "node:path";++import { RacpError, type Principal, type SessionSummary } from "@pi-desktop/agent-host";+import {+ collectWorkspaceDiff,+ listDir,+ readWorkspaceFile,+ toSessionSummary,+ type HostRpc,+ type HostSessionRecord,+ type RuntimeService,+} from "@pi-desktop/host-runtime";+import type { RacpHostOperations, RacpProjectCatalog, RacpSessionCatalog, RacpWorkspaceAccess } from "@pi-desktop/racp";+import type { RacpProjectSummary } from "@pi-desktop/shared";++/** A project row as host-core lists it. */+type ProjectRow = { id: number; path: string; name: string; pinned?: boolean };++/** Directory names never offered by the folder picker. */+const HIDDEN_BROWSE_NAMES = new Set([".git", "node_modules", "__pycache__", ".Trash"]);+const MAX_BROWSE_ENTRIES = 500;++function hostError(error: unknown): never {+ const code = (error as { errorCode?: string; data?: { errorCode?: string } })?.data?.errorCode ?? (error as { errorCode?: string })?.errorCode;+ const message = error instanceof Error ? error.message : String(error);+ if (code === "NOT_FOUND" || code === "SESSION_NOT_FOUND") throw new RacpError("NOT_FOUND", message);+ if (code === "CONFLICT" || (code && code.startsWith("PLAN_"))) throw new RacpError("CONFLICT", message, { details: { code } });+ if (code === "INVALID_PARAMS" || code === "INVALID_ARGUMENT") throw new RacpError("INVALID_ARGUMENT", message);+ if (code === "HOST_UNAVAILABLE") throw new RacpError("AGENT_UNAVAILABLE", message, { retriable: true });+ throw new RacpError("INTERNAL", message, { details: code ? { code } : undefined });+}++function projectSummary(row: ProjectRow): RacpProjectSummary {+ return { id: String(row.id), label: row.name || basename(row.path), archived: false };+}++export type HostOperationsDeps = {+ getHost: () => HostRpc | null;+ runtime: Pick<RuntimeService, "compact" | "isBusy">;+ /** `pi-host` boots the sidecar's session cleanup on delete; the runtime link is optional at boot. */+ disposeSession?: (sessionId: string) => Promise<void>;+ revokeDevice?: (deviceId: string) => Promise<boolean>;+ /** Root the folder picker may not leave; defaults to the user's home directory. */+ browseRoot?: string;+};++function requireHost(getHost: () => HostRpc | null): HostRpc {+ const host = getHost();+ if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host-core is not running", { retriable: true });+ return host;+}++/** Session catalog over host-core RPC. */+export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatalog {+ const { getHost } = deps;+ async function projectPathFor(projectId: string | undefined, host: HostRpc): Promise<string | undefined> {+ if (!projectId) return undefined;+ const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {});+ const project = projects.find((row) => String(row.id) === projectId);+ if (!project) throw new RacpError("NOT_FOUND", `project ${projectId} is unknown`);+ return project.path;+ }+ /**+ * host-core keys a session by its project path; RACP exposes the project id+ * (spec §5.1), so the summary is decorated from the projects table. A path+ * with no row (a session whose project was removed) simply has no id.+ */+ async function withProjectIds(host: HostRpc, records: HostSessionRecord[]): Promise<SessionSummary[]> {+ const needsLookup = records.some((record) => record.projectPath);+ const byPath = new Map<string, string>();+ if (needsLookup) {+ const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ for (const project of projects ?? []) byPath.set(project.path, String(project.id));+ }+ return records.map((record) => {+ const summary = toSessionSummary(record);+ const projectId = record.projectPath ? byPath.get(record.projectPath) : undefined;+ return projectId ? { ...summary, projectId } : summary;+ });+ }+ async function get(host: HostRpc, sessionId: string): Promise<SessionSummary> {+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);+ if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ return (await withProjectIds(host, [result.session]))[0]!;+ }+ return {+ async list() {+ const host = requireHost(getHost);+ const result = await host.call<{ sessions: HostSessionRecord[] }>("session.list", {}).catch(hostError);+ return withProjectIds(host, result.sessions ?? []);+ },+ async create(input, _principal: Principal) {+ const host = requireHost(getHost);+ const projectPath = await projectPathFor(input.projectId, host);+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.create", {+ ...(input.title ? { title: input.title } : {}),+ ...(input.mode ? { mode: input.mode } : {}),+ ...(input.providerId ? { providerId: input.providerId } : {}),+ ...(input.modelId ? { modelId: input.modelId } : {}),+ ...(input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {}),+ ...(projectPath ? { projectPath } : {}),+ })+ .catch(hostError);+ if (!result.session) throw new RacpError("INTERNAL", "session.create returned no session");+ if (input.permissionMode) {+ await host+ .call("session.configure", { id: result.session.id, mode: result.session.mode ?? input.mode ?? "agent", permissionMode: input.permissionMode })+ .catch(hostError);+ }+ return get(host, result.session.id);+ },+ async configure(sessionId, input) {+ const host = requireHost(getHost);+ if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");+ const current = await get(host, sessionId);+ await host+ .call("session.configure", {+ id: sessionId,+ mode: input.mode ?? current.mode,+ ...(input.providerId !== undefined ? { providerId: input.providerId } : {}),+ ...(input.modelId !== undefined ? { modelId: input.modelId } : {}),+ ...(input.thinkingLevel !== undefined ? { thinkingLevel: input.thinkingLevel } : {}),+ ...(input.permissionMode !== undefined ? { permissionMode: input.permissionMode } : {}),+ })+ .catch(hostError);+ return get(host, sessionId);+ },+ async fork(sessionId, input) {+ const host = requireHost(getHost);+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.fork", {+ sessionId,+ ...(input.title ? { title: input.title } : {}),+ ...(input.throughMessageId ? { throughMessageId: input.throughMessageId } : {}),+ })+ .catch(hostError);+ if (!result.session) throw new RacpError("INTERNAL", "session.fork returned no session");+ return get(host, result.session.id);+ },+ async rename(sessionId, title) {+ await requireHost(getHost).call("session.rename", { id: sessionId, title }).catch(hostError);+ },+ async delete(sessionId) {+ if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");+ await requireHost(getHost).call("session.delete", { id: sessionId }).catch(hostError);+ await deps.disposeSession?.(sessionId).catch(() => undefined);+ },+ async compact(sessionId) {+ try {+ return await deps.runtime.compact(sessionId);+ } catch (error) {+ hostError(error);+ }+ },+ };+}++async function canonicalDirectory(path: string): Promise<string> {+ if (!isAbsolute(path)) throw new RacpError("INVALID_ARGUMENT", "path must be absolute");+ let real: string;+ try {+ real = await realpath(path);+ } catch {+ throw new RacpError("REMOTE_PATH_NOT_FOUND", `no such directory: ${path}`);+ }+ const info = await stat(real).catch(() => null);+ if (!info?.isDirectory()) throw new RacpError("REMOTE_PATH_NOT_FOUND", `not a directory: ${path}`);+ return real;+}++/** Projects over host-core: registration canonicalizes on the Host (D446). */+export function createProjectCatalog(deps: HostOperationsDeps): RacpProjectCatalog {+ const { getHost } = deps;+ const browseRoot = resolve(deps.browseRoot ?? homedir());+ return {+ async list() {+ const host = requireHost(getHost);+ const result = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ return (result.projects ?? []).map(projectSummary);+ },+ async register(path) {+ const host = requireHost(getHost);+ const real = await canonicalDirectory(path);+ const result = await host.call<{ project?: ProjectRow | null }>("projects.create", { path: real }).catch(hostError);+ if (!result.project) throw new RacpError("INTERNAL", "projects.create returned no project");+ return { ...projectSummary(result.project), path: result.project.path };+ },+ async browse(path) {+ const target = path ? await canonicalDirectory(path) : browseRoot;+ const rootReal = await realpath(browseRoot).catch(() => browseRoot);+ if (target !== rootReal && !target.startsWith(rootReal.endsWith("/") ? rootReal : `${rootReal}/`)) {+ throw new RacpError("REMOTE_PATH_FORBIDDEN", "path is outside the browsable root");+ }+ const dirents = await readdir(target, { withFileTypes: true }).catch(() => {+ throw new RacpError("REMOTE_PATH_FORBIDDEN", `cannot read ${target}`);+ });+ const entries = dirents+ .filter((dirent) => dirent.isDirectory() && !HIDDEN_BROWSE_NAMES.has(dirent.name) && !dirent.name.startsWith("."))+ .map((dirent) => ({ name: dirent.name, path: join(target, dirent.name) }))+ .sort((a, b) => a.name.localeCompare(b.name))+ .slice(0, MAX_BROWSE_ENTRIES);+ const parent = target === rootReal ? undefined : dirname(target);+ return { path: target, ...(parent ? { parent } : {}), entries };+ },+ };+}++/** Workspace reads against the session's durable root, on the Host's filesystem. */+export function createWorkspaceAccess(deps: HostOperationsDeps): RacpWorkspaceAccess {+ const { getHost } = deps;+ async function sessionRoot(sessionId: string): Promise<string> {+ const host = requireHost(getHost);+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);+ if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ const root = result.session.projectPath?.trim();+ if (!root) throw new RacpError("CONFLICT", "the session has no project root");+ return root;+ }+ const forbidden = (error: unknown): never => {+ const message = error instanceof Error ? error.message : String(error);+ if (/escapes workspace root|outside allowed roots/.test(message)) throw new RacpError("REMOTE_PATH_FORBIDDEN", message);+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") throw new RacpError("REMOTE_PATH_NOT_FOUND", message);+ if (/not a file/.test(message)) throw new RacpError("INVALID_ARGUMENT", message);+ throw new RacpError("INTERNAL", message);+ };+ return {+ async list(sessionId, path) {+ const root = await sessionRoot(sessionId);+ return { entries: await listDir(root, path).catch(forbidden) };+ },+ async read(sessionId, path) {+ const root = await sessionRoot(sessionId);+ return readWorkspaceFile(root, path).catch(forbidden);+ },+ async diff(sessionId) {+ return collectWorkspaceDiff(await sessionRoot(sessionId));+ },+ };+}++export function createHostOperations(deps: HostOperationsDeps): Omit<RacpHostOperations, "terminal"> {+ return {+ sessions: createSessionCatalog(deps),+ projects: createProjectCatalog(deps),+ workspace: createWorkspaceAccess(deps),+ ...(deps.revokeDevice ? { revokeDevice: deps.revokeDevice } : {}),+ };+}diff --git a/apps/pi-host/src/index.ts b/apps/pi-host/src/index.tsnew file mode 100644index 000000000..788af1a8b--- /dev/null+++ b/apps/pi-host/src/index.ts@@ -0,0 +1,6 @@+export * from "./app.js";+export * from "./config.js";+export * from "./credentials.js";+export * from "./host-operations.js";+export * from "./logger.js";+export * from "./terminal.js";diff --git a/apps/pi-host/src/logger.ts b/apps/pi-host/src/logger.tsnew file mode 100644index 000000000..13dc5484e--- /dev/null+++ b/apps/pi-host/src/logger.ts@@ -0,0 +1,54 @@+import { appendFile, mkdir } from "node:fs/promises";+import { join } from "node:path";++export type LogLevel = "info" | "warn" | "error";++const SECRET_KEY_RE = /token|secret|password|apikey|api_key|authorization|credential|cookie/i;++/** Drop secret-looking keys and bound the record; the Host log never carries a credential. */+export function redactLogData(value: unknown, depth = 0): unknown {+ if (value === null || typeof value !== "object") {+ if (typeof value === "string" && value.length > 2_000) return `${value.slice(0, 2_000)}…`;+ return value;+ }+ if (depth > 4) return "[depth]";+ if (Array.isArray(value)) return value.slice(0, 50).map((item) => redactLogData(item, depth + 1));+ const out: Record<string, unknown> = {};+ for (const [key, item] of Object.entries(value as Record<string, unknown>).slice(0, 50)) {+ out[key] = SECRET_KEY_RE.test(key) ? "***" : redactLogData(item, depth + 1);+ }+ return out;+}++export type HostLogger = {+ (level: LogLevel, message: string, data?: Record<string, unknown>): void;+ child: (channel: string) => (text: string) => void;+};++const LEVEL_RANK: Record<LogLevel, number> = { info: 0, warn: 1, error: 2 };++/**+ * Structured NDJSON on stderr, mirrored to `<dataDir>/logs/pi-host.log`.+ * stdout is reserved for the bootstrap handshake (the bound port and the+ * pairing token), so a supervisor can parse it without filtering log lines.+ */+export function createLogger(options: { dataDir: string; minLevel: LogLevel; stderr?: NodeJS.WritableStream }): HostLogger {+ const stderr = options.stderr ?? process.stderr;+ const logDir = join(options.dataDir, "logs");+ const ready = mkdir(logDir, { recursive: true }).catch(() => undefined);+ const write = (record: Record<string, unknown>) => {+ const line = `${JSON.stringify(record)}\n`;+ stderr.write(line);+ void ready.then(() => appendFile(join(logDir, "pi-host.log"), line).catch(() => undefined));+ };+ const log = ((level, message, data) => {+ if (LEVEL_RANK[level] < LEVEL_RANK[options.minLevel]) return;+ write({ ts: new Date().toISOString(), level, channel: "pi-host", message, ...(data ? { data: redactLogData(data) } : {}) });+ }) as HostLogger;+ log.child = (channel) => (text) => {+ const output = text.trimEnd();+ if (!output) return;+ write({ ts: new Date().toISOString(), level: "info", channel, message: "child stderr", data: { output: output.slice(0, 4_000) } });+ };+ return log;+}diff --git a/apps/pi-host/src/terminal.ts b/apps/pi-host/src/terminal.tsnew file mode 100644index 000000000..7eb5d8735--- /dev/null+++ b/apps/pi-host/src/terminal.ts@@ -0,0 +1,154 @@+import { randomUUID } from "node:crypto";+import { createRequire } from "node:module";++import { RacpError } from "@pi-desktop/agent-host";+import type { RacpTerminalAccess, TerminalOpenResult } from "@pi-desktop/racp";+import { RACP_DEFAULT_LIMITS } from "@pi-desktop/shared";++/** The subset of `node-pty` this module uses; the package is loaded lazily. */+type Pty = {+ pid: number;+ write(data: string): void;+ resize(cols: number, rows: number): void;+ kill(signal?: string): void;+ onData(listener: (data: string) => void): { dispose(): void };+ onExit(listener: (event: { exitCode: number; signal?: number }) => void): { dispose(): void };+};++type PtyModule = {+ spawn(file: string, args: string[], options: { name: string; cols: number; rows: number; cwd: string; env: NodeJS.ProcessEnv }): Pty;+};++type TerminalSink = { output: (data: string) => void; exit: (code: number | null) => void };++type TerminalRecord = {+ id: string;+ sessionId: string;+ pty: Pty;+ cols: number;+ rows: number;+ ring: Buffer[];+ ringBytes: number;+ sink: TerminalSink | null;+ exited: number | null;+};++/**+ * Load `node-pty` when it is installed beside the bundle. The Host advertises+ * `terminal: false` when it is not, instead of failing at open time.+ */+export function loadPty(): PtyModule | null {+ try {+ const require = createRequire(import.meta.url);+ return require("node-pty") as PtyModule;+ } catch {+ return null;+ }+}++export type TerminalServiceOptions = {+ pty: PtyModule;+ /** The session's working directory: the Host resolves it, never the client. */+ sessionRoot: (sessionId: string) => Promise<string>;+ shell?: string;+ replayRingBytes?: number;+ maxPerSession?: number;+ log: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;+};++/**+ * Session terminals on the Host machine (spec §6.2, security §7): a pty with+ * the session root as cwd, a bounded replay ring per terminal, and at most+ * two open terminals per session. Output is delivered to whichever+ * connection is attached; a dropped connection keeps the pty alive and the+ * next attach receives the ring.+ */+export class TerminalService implements RacpTerminalAccess {+ private readonly terminals = new Map<string, TerminalRecord>();+ private readonly ringBytes: number;+ private readonly maxPerSession: number;++ constructor(private readonly options: TerminalServiceOptions) {+ this.ringBytes = options.replayRingBytes ?? RACP_DEFAULT_LIMITS.terminalReplayRingBytes;+ this.maxPerSession = options.maxPerSession ?? RACP_DEFAULT_LIMITS.maxOpenTerminalsPerSession;+ }++ private snapshot(record: TerminalRecord): TerminalOpenResult {+ return { terminalId: record.id, replay: Buffer.concat(record.ring).toString("base64"), cols: record.cols, rows: record.rows };+ }++ async open(sessionId: string, size: { cols: number; rows: number }, sink: TerminalSink): Promise<TerminalOpenResult> {+ const open = [...this.terminals.values()].filter((record) => record.sessionId === sessionId && record.exited === null);+ if (open.length >= this.maxPerSession) {+ throw new RacpError("RATE_LIMITED", "terminal limit reached for this session", { details: { limit: this.maxPerSession } });+ }+ const cwd = await this.options.sessionRoot(sessionId);+ const shell = this.options.shell ?? process.env.SHELL ?? "/bin/sh";+ const pty = this.options.pty.spawn(shell, [], { name: "xterm-256color", cols: size.cols, rows: size.rows, cwd, env: { ...process.env, TERM: "xterm-256color" } });+ const record: TerminalRecord = { id: `term_${randomUUID()}`, sessionId, pty, cols: size.cols, rows: size.rows, ring: [], ringBytes: 0, sink, exited: null };+ this.terminals.set(record.id, record);+ pty.onData((data) => {+ const chunk = Buffer.from(data, "utf8");+ record.ring.push(chunk);+ record.ringBytes += chunk.length;+ while (record.ringBytes > this.ringBytes && record.ring.length > 0) {+ const dropped = record.ring.shift()!;+ record.ringBytes -= dropped.length;+ }+ record.sink?.output(Buffer.from(data, "utf8").toString("base64"));+ });+ pty.onExit(({ exitCode }) => {+ record.exited = exitCode;+ record.sink?.exit(exitCode);+ this.terminals.delete(record.id);+ this.options.log("info", "terminal exited", { terminalId: record.id, sessionId, exitCode });+ });+ this.options.log("info", "terminal opened", { terminalId: record.id, sessionId, pid: pty.pid });+ return this.snapshot(record);+ }++ async input(terminalId: string, data: string): Promise<void> {+ this.require(terminalId).pty.write(Buffer.from(data, "base64").toString("utf8"));+ }++ async resize(terminalId: string, cols: number, rows: number): Promise<void> {+ const record = this.require(terminalId);+ record.cols = cols;+ record.rows = rows;+ record.pty.resize(cols, rows);+ }++ async close(terminalId: string): Promise<void> {+ const record = this.terminals.get(terminalId);+ if (!record) return;+ this.terminals.delete(terminalId);+ record.sink = null;+ try {+ record.pty.kill();+ } catch {+ // Already gone.+ }+ }++ async attach(terminalId: string, sink: TerminalSink): Promise<TerminalOpenResult | null> {+ const record = this.terminals.get(terminalId);+ if (!record || record.exited !== null) return null;+ record.sink = sink;+ return this.snapshot(record);+ }++ detach(terminalId: string): void {+ const record = this.terminals.get(terminalId);+ if (record) record.sink = null;+ }++ async closeAll(): Promise<void> {+ for (const id of [...this.terminals.keys()]) await this.close(id);+ }++ private require(terminalId: string): TerminalRecord {+ const record = this.terminals.get(terminalId);+ if (!record || record.exited !== null) throw new RacpError("NOT_FOUND", `terminal ${terminalId} is not open`);+ return record;+ }+}diff --git a/apps/pi-host/tsconfig.json b/apps/pi-host/tsconfig.jsonnew file mode 100644index 000000000..88e6660e6--- /dev/null+++ b/apps/pi-host/tsconfig.json@@ -0,0 +1,19 @@+{+ "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": "../../packages/shared" },+ { "path": "../../packages/agent-host" },+ { "path": "../../packages/agent-runtime" },+ { "path": "../../packages/host-runtime" },+ { "path": "../../packages/racp" }+ ]+}diff --git a/apps/pi-host/vitest.config.ts b/apps/pi-host/vitest.config.tsnew file mode 100644index 000000000..ae847ff6d--- /dev/null+++ b/apps/pi-host/vitest.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ include: ["src/**/*.test.ts"],+ },+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f56cd42b3..05ba7ee6a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -149,6 +149,47 @@ importers:specifier: ^5.0.15version: 5.0.15(@types/[email protected])([email protected])+ apps/pi-host:+ dependencies:+ '@pi-desktop/agent-host':+ specifier: workspace:*+ version: link:../../packages/agent-host+ '@pi-desktop/agent-runtime':+ specifier: workspace:*+ version: link:../../packages/agent-runtime+ '@pi-desktop/host-runtime':+ specifier: workspace:*+ version: link:../../packages/host-runtime+ '@pi-desktop/racp':+ specifier: workspace:*+ version: link:../../packages/racp+ '@pi-desktop/shared':+ specifier: workspace:*+ version: link:../../packages/shared+ 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+ esbuild:+ specifier: ^0.25.12+ version: 0.25.12+ typescript:+ specifier: ^5.9.3+ version: 5.9.3+ vitest:+ specifier: ^4.1.10+ version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))+ optionalDependencies:+ node-pty:+ specifier: 1.1.0+ version: 1.1.0+docs:devDependencies:vitepress:@@ -3305,6 +3346,10 @@ packages:resolution: {integrity: sha512-vLBWCKb+7LWsX+TbfzWOkw0W81m377tyx3hOweBTjO43CXZnRGS1/JPWs20fr0PgZyDXk6ROYrylsEycK8raDA==}engines: {node: '>=22.12.0'}+ resolution: {integrity: sha512-mNcltoe1R8o7STTegSOHdnJNN7s5EUvhoS7ShnTHDyOSd+8H+UdWODq6qSv67PjC8Zc5JRT8+oLAMCr0SIXw7g==}+ engines: {node: ^16 || ^18 || >= 20}+resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}@@ -3325,6 +3370,9 @@ packages:resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}+ resolution: {integrity: sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg==}+resolution: {integrity: sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ==}engines: {node: '>=18'}@@ -7693,6 +7741,9 @@ snapshots:dependencies:semver: 7.8.5+ optional: true+dependencies:semver: 7.8.5@@ -7720,6 +7771,11 @@ snapshots:+ dependencies:+ node-addon-api: 7.1.0+ optional: true+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 8356e1e8b..312db6d1f 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -12,6 +12,7 @@ allowBuilds:'@google/genai': trueprotobufjs: trueelectron-winstaller: true+ node-pty: true# Advisory fixes for transitives whose parents still resolve the vulnerable# version. Drop each one once its parent ships a release that resolves the# patched version on its own.diff --git a/scripts/e2e-remote-host.mjs b/scripts/e2e-remote-host.mjsnew file mode 100644index 000000000..85b8538d7--- /dev/null+++ b/scripts/e2e-remote-host.mjs@@ -0,0 +1,228 @@+#!/usr/bin/env node+/**+ * Headless remote Host E2E (E2E-231 host half): boots a real `pi-host` with+ * the debug host-core and the bundled sidecar on a throwaway data dir, pairs+ * a device over the loopback RACP-WS socket, registers a project, creates a+ * session, reads the workspace, drops the connection, and reconnects by+ * cursor. No model provider is configured, so `turn/start` is expected to+ * fail closed with `MODEL_NOT_CONFIGURED` rather than hang.+ *+ * Prereqs: `pnpm build:js`, `pnpm -C packages/agent-runtime bundle`, and a+ * host-core binary (target/debug or PI_DESKTOP_HOST_BIN).+ */+import { spawn } from "node:child_process";+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { RacpClient, wsClientTransport } from "../packages/racp/dist/index.js";+import { assert, errorCodeOf, shortJson } from "./e2e/assert.mjs";+import { resolveHostBinary } from "./e2e/host.mjs";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const cli = join(root, "apps/pi-host/dist/cli.js");+const sidecar = join(root, "packages/agent-runtime/dist-bundle/sidecar.js");+for (const [label, path] of [["pi-host cli", cli], ["sidecar bundle", sidecar]]) {+ if (!existsSync(path)) {+ console.error(`${label} missing: ${path}`);+ process.exit(1);+ }+}+const hostBin = resolveHostBinary();+const dataDir = mkdtempSync(join(tmpdir(), "pi-host-e2e-"));+const project = join(dataDir, "project");+mkdirSync(project, { recursive: true });+writeFileSync(join(project, "README.md"), "# remote project\n");++const results = [];+const record = (id, ok, detail = "") => {+ results.push({ id, ok });+ console.log(`${ok ? "PASS" : "FAIL"} ${id}${detail ? " — " + detail : ""}`);+};++let child = null;+let stderr = "";+function startHost(extraArgs = []) {+ child = spawn(process.execPath, [cli, "--data-dir", dataDir, "--port", "0", "--host-core", hostBin, "--sidecar", sidecar, "--browse-root", dataDir, "--log-level", "warn", ...extraArgs], {+ stdio: ["ignore", "pipe", "pipe"],+ env: { ...process.env },+ });+ child.stderr.on("data", (chunk) => {+ stderr += String(chunk);+ if (process.env.DEBUG_HOST) process.stderr.write(chunk);+ });+ return new Promise((resolveReady, reject) => {+ let out = "";+ const ready = {};+ const timer = setTimeout(() => reject(new Error("pi-host did not become ready\n" + stderr.slice(-2000))), 60_000);+ child.stdout.on("data", (chunk) => {+ out += String(chunk);+ for (const line of out.split("\n")) {+ if (line.startsWith("PI_HOST_READY ")) ready.info = JSON.parse(line.slice("PI_HOST_READY ".length));+ if (line.startsWith("PI_HOST_PAIRING_TOKEN ")) ready.pairing = JSON.parse(line.slice("PI_HOST_PAIRING_TOKEN ".length));+ if (line.startsWith("PI_HOST_FAILED ")) {+ clearTimeout(timer);+ reject(new Error("pi-host failed: " + line + "\n" + stderr.slice(-2000)));+ }+ }+ if (ready.info && (!extraArgs.includes("--pair") || ready.pairing)) {+ clearTimeout(timer);+ resolveReady(ready);+ }+ });+ child.once("exit", (code) => {+ clearTimeout(timer);+ reject(new Error(`pi-host exited early code=${code}\n${stderr.slice(-2000)}`));+ });+ });+}+async function stopHost() {+ if (!child) return;+ const proc = child;+ child = null;+ await new Promise((resolveExit) => {+ proc.once("exit", resolveExit);+ proc.kill("SIGTERM");+ setTimeout(() => proc.kill("SIGKILL"), 5_000).unref();+ });+}++function client(url, token, options = {}) {+ const events = [];+ const instance = new RacpClient({+ transport: wsClientTransport({ url, token }),+ client: { name: "pi-host-e2e", version: "0.15.0" },+ onEvent: (envelope) => events.push(envelope),+ requestTimeoutMs: 30_000,+ ...options,+ });+ return { client: instance, events };+}++const sleep = (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms));++let exitCode = 0;+try {+ const ready = await startHost(["--pair"]);+ const url = `ws://127.0.0.1:${ready.info.port}/v1/racp/ws`;+ record("host-boots-on-loopback", ready.info.host === "127.0.0.1" && ready.info.port > 0 && typeof ready.info.hostId === "string", shortJson(ready.info));++ // Pairing: the token is single-use and the device token replaces it.+ const pairing = client(url, ready.pairing.token);+ const init = await pairing.client.connect();+ record("pairing-connection-is-unprivileged", init.principal.roles.length === 0 && init.server.hostId === ready.info.hostId);+ const paired = await pairing.client.request("connection/pair", { deviceLabel: "e2e desktop" });+ record("pair-mints-owner-device", paired.roles.includes("owner") && paired.deviceToken.startsWith("pdt1."));+ let secondPair = null;+ try {+ await pairing.client.request("connection/pair", {});+ } catch (error) {+ secondPair = errorCodeOf(error);+ }+ record("pairing-token-is-single-use", secondPair === "PAIRING_FAILED", String(secondPair));+ await pairing.client.close();++ const owner = client(url, paired.deviceToken, { reconnect: { enabled: true, baseDelayMs: 50, maxAttempts: 10 } });+ const ownerInit = await owner.client.connect();+ record("device-token-authenticates-as-owner", ownerInit.principal.roles.includes("owner") && ownerInit.capabilities.remoteHostProfile === true);++ const registered = await owner.client.request("project/register", { path: project });+ record("project-registers-on-host", typeof registered.project.id === "string" && registered.project.label === "project", shortJson(registered));+ let missing = null;+ try {+ await owner.client.request("project/register", { path: join(dataDir, "missing") });+ } catch (error) {+ missing = errorCodeOf(error);+ }+ record("project-register-validates-path-on-host", missing === "REMOTE_PATH_NOT_FOUND", String(missing));+ const browsed = await owner.client.request("project/browse", { path: dataDir });+ record("project-browse-lists-directories", browsed.entries.some((entry) => entry.name === "project"));++ await owner.client.request("events/subscribe", { scope: "host" });+ const created = await owner.client.request("session/create", { title: "Remote E2E", projectId: registered.project.id });+ record("session-creates-under-project", created.session.projectId === registered.project.id && created.session.status === "idle", shortJson(created.session));+ const listed = await owner.client.request("session/list");+ record("session-list-includes-created", listed.sessions.some((session) => session.id === created.session.id));+ const attach = await owner.client.request("session/attach", { sessionId: created.session.id });+ record("attach-returns-snapshot", attach.replayComplete === true && Array.isArray(attach.snapshot.items) && attach.snapshot.queuedTurns.length === 0);+ await owner.client.request("events/subscribe", { scope: "session", sessionId: created.session.id });++ const files = await owner.client.request("workspace/list", { sessionId: created.session.id, path: "" });+ const readme = await owner.client.request("workspace/read", { sessionId: created.session.id, path: "README.md" });+ record("workspace-reads-execute-on-host", files.entries.some((entry) => entry.name === "README.md") && readme.kind === "text" && readme.content.includes("remote project"));+ let escape = null;+ try {+ await owner.client.request("workspace/read", { sessionId: created.session.id, path: "../../etc/passwd" });+ } catch (error) {+ escape = errorCodeOf(error);+ }+ record("workspace-read-refuses-escape", escape === "REMOTE_PATH_FORBIDDEN", String(escape));+ const diff = await owner.client.request("workspace/diff", { sessionId: created.session.id });+ record("workspace-diff-runs-on-host", typeof diff.repo === "boolean");++ // No provider is configured: the turn must fail closed with a typed code and leave the session idle.+ let turnError = null;+ try {+ await owner.client.request("turn/start", { sessionId: created.session.id, input: { text: "hello" }, context: { requestId: "r1", idempotencyKey: "e2e-1" } });+ } catch (error) {+ turnError = errorCodeOf(error);+ }+ record("turn-without-provider-fails-closed", turnError === "MODEL_NOT_CONFIGURED", String(turnError));+ await sleep(200);+ const after = await owner.client.request("session/get", { sessionId: created.session.id });+ record("failed-admission-leaves-session-idle", after.session.status === "idle" && !after.session.activeTurnId, shortJson(after.session));++ const renamed = await owner.client.request("session/rename", { sessionId: created.session.id, title: "Renamed remotely" });+ const configured = await owner.client.request("session/configure", { sessionId: created.session.id, permissionMode: "accept-edits" });+ record("remote-host-profile-mutations", renamed.ok === true && configured.session.permissionMode === "accept-edits");+ await sleep(200);+ const hostKinds = owner.events.filter((event) => event.scope === "host").map((event) => event.kind);+ record("host-scope-events-announce-session-changes", hostKinds.includes("session.created") && hostKinds.includes("session.changed"), hostKinds.join(","));++ // Reconnect by cursor: the desktop-side transport drops, the Host keeps everything.+ const cursor = owner.client.cursorFor(created.session.id);+ const states = [];+ const owner2 = client(url, paired.deviceToken, { onStateChange: (state) => states.push(state) });+ await owner2.client.connect();+ const resumed = await owner2.client.request("session/attach", { sessionId: created.session.id, after: cursor });+ record("reconnect-resumes-by-cursor", resumed.replayComplete === true && resumed.session.title === "Renamed remotely", shortJson({ cursor, title: resumed.session.title }));+ const stale = await owner2.client.request("session/attach", { sessionId: created.session.id, after: { epoch: "ep_old", sequence: 3 } });+ record("stale-epoch-yields-snapshot", stale.replayComplete === false && stale.resyncReason === "epoch" && stale.snapshot !== undefined);+ await owner2.client.close();++ // Viewer role from a second pairing is refused the owner operations.+ let forbidden = null;+ const devices = await owner.client.request("session/revoke", { deviceId: "dev_unknown" });+ record("revoke-unknown-device-is-false", devices.revoked === false);+ try {+ await owner.client.request("host/list", {});+ } catch (error) {+ forbidden = errorCodeOf(error);+ }+ record("host-list-is-gateway-only", forbidden === "METHOD_NOT_FOUND", String(forbidden));++ await owner.client.request("session/delete", { sessionId: created.session.id });+ const gone = await owner.client.request("session/list");+ record("session-delete-removes-on-host", !gone.sessions.some((session) => session.id === created.session.id));+ await owner.client.close();++ // Restart: identity and the paired device survive; a fresh epoch resyncs.+ await stopHost();+ const again = await startHost();+ record("host-identity-is-stable-across-restarts", again.info.hostId === ready.info.hostId, `${ready.info.hostId} vs ${again.info.hostId}`);+ const owner3 = client(`ws://127.0.0.1:${again.info.port}/v1/racp/ws`, paired.deviceToken);+ const init3 = await owner3.client.connect();+ record("device-credential-survives-restart", init3.principal.roles.includes("owner"));+ await owner3.client.close();+} catch (error) {+ record("headless-remote-host-e2e", false, `${error?.message ?? error}\n${stderr.slice(-3000)}`);+} finally {+ await stopHost();+ rmSync(dataDir, { recursive: true, force: true });+}++const failed = results.filter((result) => !result.ok);+console.log(`\n${results.length - failed.length}/${results.length} passed`);+if (failed.length > 0) exitCode = 1;+process.exit(exitCode);