Skip to content

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

refactor(remote): extract headless runtime service

vastsa83487089a6d4
diff --git a/CLAUDE.md b/CLAUDE.md
index 27b4a9477..9cb351577 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -231,6 +231,8 @@ packages/
shared/ IPC/protocol contracts, error codes
i18n/ UI catalogs
agent-runtime/ pi sidecar wrapper
+ agent-host/ headless Agent Host module (admission, queue, approvals, events)
+ host-runtime/ Electron-independent runtime (transports, supervisor, turn lifecycle)
plugin-sdk/ plugin author types/validators
plugin-devkit/ pi-plugin CLI
examples/plugins/ sample plugins
diff --git a/apps/desktop/electron/main/agent-host-bridge.ts b/apps/desktop/electron/main/agent-host-bridge.ts
index a92b75bc0..9b99580ed 100644
--- a/apps/desktop/electron/main/agent-host-bridge.ts
+++ b/apps/desktop/electron/main/agent-host-bridge.ts
@@ -1,20 +1,18 @@
-import { basename } from "node:path";
-
import {
AgentHost,
RacpError,
type ApprovalPort,
- type PendingToolRequest,
type Principal,
type QueueEntryView,
- type QueueStore,
- type QueuedTurnRecord,
type RuntimePort,
- type SessionPort,
- type SessionSummary,
type TurnStartRequest,
type TurnSteerRequest,
} from "@pi-desktop/agent-host";
+import {
+ createHostQueueStore,
+ createHostSessionPort,
+ listPendingToolRequests,
+} from "@pi-desktop/host-runtime";
import type {
AgentEventEnvelope,
AgentQueueChangedEvent,
@@ -22,9 +20,7 @@ import type {
AskToolResolution,
QueuedTurnSummary,
RacpApprovalResult,
- RacpItemSummary,
RacpPermissionMode,
- UiMessage,
} from "@pi-desktop/shared";
import { IPC, isGlobalPermissionMode } from "@pi-desktop/shared";
@@ -53,19 +49,6 @@ export const DESKTOP_PRINCIPAL: Principal = {
pairedDevice: true,
};
-type HostSessionRecord = {
- id: string;
- title?: string;
- projectId?: string;
- projectPath?: string;
- mode?: string;
- permissionMode?: string;
- planningState?: string;
- createdAt?: string;
- updatedAt?: string;
- messages?: UiMessage[];
-};
-
/**
* Electron Main's adapter around the headless Agent Host module (rollout R1,
* D374/D375). The module wraps the existing registered IPC handlers through
@@ -209,77 +192,13 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
resolvingViaModule.delete(input.proposalId);
}
},
- async listPendingTools(sessionId) {
- const host = options.getHost();
- if (!host) return [];
- const result = await host.call<{ requests?: PendingToolRequest[] }>("permissions.pending", {
- ...(sessionId ? { sessionId } : {}),
- });
- return result.requests ?? [];
- },
- };
-
- const sessions: SessionPort = {
- async get(sessionId) {
- const record = await fetchSession(sessionId);
- return record ? toSummary(record) : null;
- },
- async history(sessionId, { limit, beforeItemId }) {
- const record = await fetchSession(sessionId);
- const messages = record?.messages ?? [];
- const end = beforeItemId ? messages.findIndex((message) => message.id === beforeItemId) : messages.length;
- const cut = end === -1 ? messages.length : end;
- const start = Math.max(0, cut - limit);
- return {
- items: messages.slice(start, cut).map(toItem),
- hasMore: start > 0,
- };
- },
+ listPendingTools: (sessionId) => listPendingToolRequests(options.getHost, sessionId),
};
- async function fetchSession(sessionId: string): Promise<HostSessionRecord | null> {
- const host = options.getHost();
- if (!host) return null;
- const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId });
- return result.session ?? null;
- }
-
- /** The Host-owned turn queue persisted by host-core (schema v15, ADR 0213). */
- const queueStore: QueueStore = {
- async listAll() {
- const host = options.getHost();
- if (!host) return [];
- const result = await host.call<{ entries?: HostQueueEntry[] }>("session.queueList", {});
- return (result.entries ?? []).map(fromHostQueueEntry);
- },
- async push(record) {
- await requireHost().call("session.queuePush", {
- id: record.id,
- sessionId: record.sessionId,
- principal: record.principalSubject,
- ...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),
- inputHash: record.inputHash,
- content: record.content,
- ...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),
- ...(record.attachments ? { attachments: record.attachments } : {}),
- permissionMode: record.effectivePermissionMode,
- });
- },
- async remove(id) {
- const result = await requireHost().call<{ removed?: boolean }>("session.queueRemove", { id });
- return result.removed === true;
- },
- async prioritize(id) {
- await requireHost().call("session.queuePrioritize", { id });
- },
- async reorder(id, direction) {
- const result = await requireHost().call<{ moved?: boolean }>("session.queueReorder", {
- id,
- direction,
- });
- return result.moved === true;
- },
- };
+ // Session reads and the persisted turn queue (schema v15, ADR 0213) go
+ // straight to host-core; the same ports serve the headless Host.
+ const sessions = createHostSessionPort(options.getHost);
+ const queueStore = createHostQueueStore(options.getHost);
const agentHost = new AgentHost({
runtime,
@@ -450,71 +369,3 @@ function toQueueSummary(entry: QueueEntryView): QueuedTurnSummary {
createdAt: entry.turn.startedAt ?? new Date().toISOString(),
};
}
-
-type HostQueueEntry = {
- id: string;
- sessionId: string;
- principal: string;
- idempotencyKey?: string;
- inputHash: string;
- content: string;
- sessionMessageId?: string;
- attachments?: unknown;
- permissionMode: string;
- position: number;
- priority?: number;
- createdAt: string;
-};
-
-function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {
- const permissionMode: RacpPermissionMode =
- entry.permissionMode === "accept-edits" || entry.permissionMode === "auto" ? entry.permissionMode : "ask";
- return {
- id: entry.id,
- sessionId: entry.sessionId,
- principalSubject: entry.principal,
- content: entry.content,
- ...(entry.sessionMessageId ? { sessionMessageId: entry.sessionMessageId } : {}),
- ...(Array.isArray(entry.attachments) ? { attachments: entry.attachments as QueuedTurnRecord["attachments"] } : {}),
- effectivePermissionMode: permissionMode,
- ...(entry.idempotencyKey ? { idempotencyKey: entry.idempotencyKey } : {}),
- inputHash: entry.inputHash,
- ...(entry.priority !== undefined ? { priority: entry.priority } : {}),
- createdAt: Date.parse(entry.createdAt) || 0,
- };
-}
-
-function toSummary(record: HostSessionRecord): SessionSummary {
- const mode = record.mode === "plan" || record.mode === "goal" ? record.mode : "agent";
- const permissionMode: RacpPermissionMode =
- record.permissionMode === "accept-edits" || record.permissionMode === "auto" ? record.permissionMode : "ask";
- const planningState =
- record.planningState === "planning" || record.planningState === "awaiting_approval"
- ? record.planningState
- : "inactive";
- return {
- id: record.id,
- title: record.title ?? "",
- ...(record.projectId ? { projectId: record.projectId } : {}),
- ...(record.projectPath ? { workspaceLabel: basename(record.projectPath) } : {}),
- mode,
- permissionMode,
- planningState,
- createdAt: record.createdAt ?? new Date(0).toISOString(),
- updatedAt: record.updatedAt ?? record.createdAt ?? new Date(0).toISOString(),
- };
-}
-
-function toItem(message: UiMessage): RacpItemSummary {
- const turnId = (message as { turnId?: string }).turnId ?? "";
- return {
- id: message.id,
- turnId,
- itemType: "message",
- status: message.status === "streaming" ? "streaming" : "completed",
- createdAt: message.createdAt,
- ...(message.parentToolCallId ? { parentToolCallId: message.parentToolCallId } : {}),
- ...(message.agentName ? { agentName: message.agentName } : {}),
- content: message,
- };
-}
diff --git a/apps/desktop/electron/main/agent-sidecar.ts b/apps/desktop/electron/main/agent-sidecar.ts
index bb486b7d1..3b0daadae 100644
--- a/apps/desktop/electron/main/agent-sidecar.ts
+++ b/apps/desktop/electron/main/agent-sidecar.ts
@@ -1,95 +1,19 @@
-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
-import { randomUUID } from "node:crypto";
-import { join } from "node:path";
import { existsSync } from "node:fs";
-import type { HostProcess, ProcessExitHandler, StderrHandler } from "./host-process";
+import { join } from "node:path";
+import {
+ AgentSidecar as RuntimeAgentSidecar,
+ type StderrHandler,
+} from "@pi-desktop/host-runtime";
import { redactValue } from "./logger";
-import { DEFAULT_RPC_TIMEOUT_MS, readNdjsonLines, rpcTimeoutMs } from "@pi-desktop/shared";
-
-// stderr lines kept per sidecar so an unexpected exit can be reported with the
-// process's last words instead of a bare "agent sidecar exited".
-const SIDECAR_STDERR_TAIL_LINES = 40;
-
-export type SidecarNotificationHandler = (method: string, params: unknown) => void;
-
-/** Result shape the sidecar's tool executor expects from tools.execute. */
-export type LocalToolResult = {
- ok: boolean;
- content: unknown;
- isError?: boolean;
- errorCode?: string;
-};
-
-export type LocalToolHandler = (input: {
- sessionId: string;
- toolCallId: string;
- args: unknown;
-}) => Promise<LocalToolResult>;
-
-export type ProjectInstructionResolver = (input: {
- sessionId: string;
- path: string;
- /** Project root registered by Electron main for this session. */
- projectPath?: string;
-}) => Promise<unknown>;
-
-/**
- * Resolve request auth for a vendor account. Answered by main against the
- * signed-in pi-ai collection; the sidecar names a provider row, never a vendor
- * or a credential, and gets back only a short-lived `ModelAuth`.
- */
-export type VendorAuthResolver = (input: {
- sessionId: string;
- providerId: string;
-}) => Promise<unknown>;
-// The sidecar runs model-directed code paths; it must not be able to pull
-// secrets or mutate configuration through the parent proxy. Tight allowlist
-// of host methods the agent loop legitimately needs.
-//
-// `provider.resolveAuth` is answered by main itself (never forwarded to
-// host-core) and only for a provider row main bound to that same session, so
-// it cannot reach a credential the session was not launched with.
-const HOST_PROXY_ALLOWED = new Set([
- "tools.execute",
- "tools.abort",
- "tools.list",
- "session.get",
- "session.appendMessage",
- "session.appendCompaction",
- "session.replaceMessages",
- "workspace.get",
- "plans.enter",
- "plans.submit",
- "plans.pending",
- "plans.abort",
- "project.instructions.resolve",
- "provider.resolveAuth",
- "provider.resolveSubagentModel",
- "app.health",
- // Trusted extensions (D387): answered by main, plus the session methods
- // the ExtensionAPI reaches (spec 16 §10.1).
- "extensions.commands.publish",
- "extensions.ui.request",
- "extensions.diagnostics.publish",
- "extensions.model.configure",
- "session.rename",
- "session.create",
- "session.fork",
- "session.queuePush",
- "session.queuePrioritize",
-]);
-
-/** Main-side answers for the `extensions.*` proxy methods. */
-export type TrustedExtensionSidecarBridge = {
- publishCommands: (params: Record<string, unknown>) => void;
- publishDiagnostics: (params: Record<string, unknown>) => void;
- requestUi: (params: Record<string, unknown>) => Promise<unknown>;
- configureModel: (params: Record<string, unknown>) => Promise<unknown>;
- /** `sendUserMessage`: the Host-owned queue drains it (D386); host-core alone would only store it. */
- queuePush: (params: Record<string, unknown>) => Promise<unknown>;
- queuePrioritize: (params: Record<string, unknown>) => Promise<unknown>;
-};
+export type {
+ LocalToolHandler,
+ LocalToolResult,
+ ProjectInstructionResolver,
+ SidecarNotificationHandler,
+ TrustedExtensionSidecarBridge,
+ VendorAuthResolver,
+} from "@pi-desktop/host-runtime";
function resolveSidecarEntry(): string {
const candidates = [
@@ -103,543 +27,38 @@ function resolveSidecarEntry(): string {
return join(__dirname, "../../../../packages/agent-runtime/dist/sidecar.js");
}
-export class AgentSidecar {
- private child: ChildProcessWithoutNullStreams;
- private pending = new Map<
- string,
- {
- resolve: (v: any) => void;
- reject: (e: Error) => void;
- timer?: ReturnType<typeof setTimeout>;
- }
- >();
- private handlers = new Set<SidecarNotificationHandler>();
- private exitHandlers = new Set<ProcessExitHandler>();
- private disposed = false;
- private closed = false;
- private exitNotified = false;
- private stderrTail: string[] = [];
- private host: HostProcess | null = null;
- private unsubscribeHost: (() => void) | null = null;
- private unsubscribeHostExit: (() => void) | null = null;
- private stdoutReader?: ReturnType<typeof readNdjsonLines>;
- // Tools served by Electron main itself (e.g. BrowserPreview drives the
- // work panel's WebContentsView) — host-core never sees these.
- private localTools = new Map<string, LocalToolHandler>();
- private localToolTimers = new Set<ReturnType<typeof setTimeout>>();
- private projectInstructionResolver: ProjectInstructionResolver | null = null;
- // The sidecar may request a path, but it never chooses the project root.
- // Electron main registers this binding from the host-owned session record
- // immediately before starting a runtime turn.
- private projectInstructionRoots = new Map<string, string>();
- private vendorAuthResolver: VendorAuthResolver | null = null;
- private trustedExtensionBridge: TrustedExtensionSidecarBridge | null = null;
- // Vendor-account rows this session was launched with. The sidecar can only
- // ask for auth it is already using, and a session that never bound an OAuth
- // row can ask for nothing at all.
- private vendorAuthBindings = new Map<string, Set<string>>();
+function fallbackStderrLogger(text: string): void {
+ console.error(
+ `[agent/runtime] ${JSON.stringify({
+ ts: new Date().toISOString(),
+ level: "info",
+ channel: "agent",
+ category: "runtime",
+ event: "child.process.stderr",
+ message: "child process stderr",
+ data: { output: redactValue(text.trimEnd()) },
+ })}`,
+ );
+}
+/**
+ * The desktop's agent sidecar: the shared stdio transport from
+ * `@pi-desktop/host-runtime`, launched the only way Electron can run Node
+ * code out of process — its own executable with `ELECTRON_RUN_AS_NODE` — on
+ * the sidecar bundle this build ships.
+ */
+export class AgentSidecar extends RuntimeAgentSidecar {
constructor(onStderr?: StderrHandler) {
- const entry = resolveSidecarEntry();
- this.child = spawn(process.execPath, [entry], {
- stdio: ["pipe", "pipe", "pipe"],
- env: {
- ...process.env,
- ELECTRON_RUN_AS_NODE: "1",
+ super({
+ launch: {
+ command: process.execPath,
+ args: [resolveSidecarEntry()],
+ env: {
+ ...process.env,
+ ELECTRON_RUN_AS_NODE: "1",
+ },
},
- });
-
- this.child.stderr.setEncoding("utf8");
- this.child.stderr.on("data", (text: string) => {
- if (!text) return;
- this.recordStderr(text);
- if (onStderr) onStderr(text);
- else {
- console.error(
- `[agent/runtime] ${JSON.stringify({
- ts: new Date().toISOString(),
- level: "info",
- channel: "agent",
- category: "runtime",
- event: "child.process.stderr",
- message: "child process stderr",
- data: { output: redactValue(text.trimEnd()) },
- })}`,
- );
- }
- });
-
- this.child.on("exit", (code, signal) => {
- this.closeTransport(new Error("agent sidecar exited"));
- this.notifyExit({ code, signal, intentional: this.disposed });
- });
- this.child.on("error", (error) => {
- this.closeTransport(error instanceof Error ? error : new Error(String(error)));
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- });
-
- this.stdoutReader = readNdjsonLines(this.child.stdout, (line) =>
- void this.onLine(line),
- );
- }
-
- private recordStderr(text: string) {
- for (const line of text.split(/\r?\n/)) {
- if (!line.trim()) continue;
- this.stderrTail.push(line);
- if (this.stderrTail.length > SIDECAR_STDERR_TAIL_LINES) {
- this.stderrTail.shift();
- }
- }
- }
-
- private closeTransport(error: Error) {
- if (this.closed) return;
- this.closed = true;
- this.unsubscribeHost?.();
- this.unsubscribeHost = null;
- this.unsubscribeHostExit?.();
- this.unsubscribeHostExit = null;
- this.host = null;
- for (const [, p] of this.pending) {
- if (p.timer) clearTimeout(p.timer);
- p.reject(error);
- }
- this.pending.clear();
- for (const timer of this.localToolTimers) clearTimeout(timer);
- this.localToolTimers.clear();
- this.handlers.clear();
- this.stdoutReader?.close();
- this.stdoutReader = undefined;
- this.child.removeAllListeners("exit");
- this.child.removeAllListeners("error");
- this.child.stderr.removeAllListeners("data");
- }
-
- private notifyExit(info: {
- code: number | null;
- signal: NodeJS.Signals | null;
- intentional: boolean;
- }) {
- if (this.exitNotified) return;
- this.exitNotified = true;
- // Snapshot the sidecar's last stderr lines: the dying process emits no
- // stdout, so they are the only context a crash report gets.
- const stderrTail = this.stderrTail.slice();
- for (const h of this.exitHandlers) h({ ...info, stderrTail });
- this.exitHandlers.clear();
- }
-
- private writeToChild(payload: string): boolean {
- if (this.closed || this.disposed) return false;
- if (this.child.stdin.destroyed || !this.child.stdin.writable) {
- const failure = new Error("agent sidecar stdin is unavailable");
- this.closeTransport(failure);
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- return false;
- }
- try {
- this.child.stdin.write(payload, (error) => {
- if (error) {
- this.closeTransport(error);
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- }
- });
- return true;
- } catch (error) {
- const failure = error instanceof Error ? error : new Error(String(error));
- this.closeTransport(failure);
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- return false;
- }
- }
-
- private async runLocalTool(
- handler: LocalToolHandler,
- input: Parameters<LocalToolHandler>[0],
- ): Promise<LocalToolResult> {
- let timer: ReturnType<typeof setTimeout> | undefined;
- try {
- return await Promise.race([
- handler(input),
- new Promise<LocalToolResult>((_, reject) => {
- timer = setTimeout(() => {
- reject(new Error("main-local tool timeout"));
- }, DEFAULT_RPC_TIMEOUT_MS);
- this.localToolTimers.add(timer);
- }),
- ]);
- } finally {
- if (timer) {
- clearTimeout(timer);
- this.localToolTimers.delete(timer);
- }
- }
- }
-
- onExit(handler: ProcessExitHandler): () => void {
- if (this.closed) return () => undefined;
- this.exitHandlers.add(handler);
- return () => this.exitHandlers.delete(handler);
- }
-
- /** Register a tool the sidecar can call that main handles locally. */
- setLocalTool(name: string, handler: LocalToolHandler): void {
- this.localTools.set(name, handler);
- }
-
- setProjectInstructionResolver(resolver: ProjectInstructionResolver): void {
- this.projectInstructionResolver = resolver;
- }
-
- setProjectInstructionRoot(sessionId: string, projectPath?: string): void {
- const id = sessionId.trim();
- if (!id) return;
- const root = projectPath?.trim();
- if (root) this.projectInstructionRoots.set(id, root);
- else this.projectInstructionRoots.delete(id);
- }
-
- clearProjectInstructionRoot(sessionId: string): void {
- this.projectInstructionRoots.delete(sessionId.trim());
- }
-
- setVendorAuthResolver(resolver: VendorAuthResolver): void {
- this.vendorAuthResolver = resolver;
- }
-
- setTrustedExtensionBridge(bridge: TrustedExtensionSidecarBridge): void {
- this.trustedExtensionBridge = bridge;
- }
-
- /**
- * Bind the vendor-account rows a turn may sign requests with. Replaces the
- * session's previous set, so a row dropped from the launch payload — a model
- * switch or account removal — stops being resolvable on the next turn.
- */
- setVendorAuthBindings(
- sessionId: string,
- bindings: ReadonlyArray<{ providerId: string }>,
- ): void {
- const id = sessionId.trim();
- if (!id) return;
- const providerIds = new Set<string>();
- for (const binding of bindings) {
- const providerId = binding.providerId?.trim();
- if (providerId) providerIds.add(providerId);
- }
- if (providerIds.size > 0) this.vendorAuthBindings.set(id, providerIds);
- else this.vendorAuthBindings.delete(id);
- }
-
- clearVendorAuthBindings(sessionId: string): void {
- this.vendorAuthBindings.delete(sessionId.trim());
- }
-
- setHost(host: HostProcess) {
- if (this.closed) return;
- this.host = host;
- this.unsubscribeHost?.();
- this.unsubscribeHostExit?.();
- this.unsubscribeHost = host.onNotification((method, params) => {
- // Forward host notifications to sidecar. permissions.request stays out:
- // the renderer already gets it straight from wireHost, and bouncing it
- // through the sidecar delivered the dialog twice with the full args
- // payload re-serialized across two extra stdio hops.
- if (method === "permissions.request") return;
- const payload =
- JSON.stringify({
- jsonrpc: "2.0",
- method: "host.notification",
- params: { method, params },
- }) + "\n";
- this.writeToChild(payload);
- });
- this.unsubscribeHostExit = host.onExit(() => {
- this.unsubscribeHost?.();
- this.unsubscribeHost = null;
- this.unsubscribeHostExit = null;
- this.host = null;
- });
- }
-
- /**
- * Answer one `provider.resolveAuth` request. Refuses anything the session was
- * not launched with: the provider row has to be in this session's bindings,
- * which main rewrites on every turn.
- */
- private async resolveVendorAuth(
- params: Record<string, unknown>,
- ): Promise<unknown> {
- if (!this.vendorAuthResolver) {
- throw new Error("vendor account auth resolver unavailable");
- }
- const sessionId = String(params.sessionId ?? "").trim();
- const providerId = String(params.providerId ?? "").trim();
- const bound = this.vendorAuthBindings.get(sessionId)?.has(providerId);
- if (!bound) {
- throw Object.assign(
- new Error("provider is not bound to this session"),
- { code: -32000, data: { errorCode: "PROVIDER_NOT_BOUND" } },
- );
- }
- return this.vendorAuthResolver({ sessionId, providerId });
- }
-
- /**
- * On-demand subagent model resolution. The runtime calls this when the
- * parent agent passes a `model` override on Task that was not statically
- * pinned by any definition. Main resolves it against the user's configured
- * providers and the models.dev catalog, respecting the
- * `availableForSubagents` gate on each model binding.
- */
- private subagentModelResolver:
- | ((key: string) => Promise<unknown>)
- | null = null;
-
- setSubagentModelResolver(
- resolver: (key: string) => Promise<unknown>,
- ): void {
- this.subagentModelResolver = resolver;
- }
-
- private async resolveSubagentModel(
- params: Record<string, unknown>,
- ): Promise<unknown> {
- if (!this.subagentModelResolver) {
- throw new Error("subagent model resolver unavailable");
- }
- const key = String(params.key ?? "").trim();
- if (!key || !key.includes("/")) {
- throw Object.assign(
- new Error("invalid model key; expected 'provider/model'"),
- { code: -32602 },
- );
- }
- return this.subagentModelResolver(key);
- }
-
- private async onLine(line: string) {
- if (!line.trim()) return;
- let msg: any;
- try {
- msg = JSON.parse(line);
- } catch {
- console.warn(
- `[RPC] Invalid agent-sidecar NDJSON frame (${Buffer.byteLength(line, "utf8")} bytes)`,
- );
- return;
- }
-
- // Reverse RPC from sidecar → host proxy
- if (msg.method === "host.proxy" && msg.id !== undefined) {
- try {
- const method = String(msg.params?.method || "");
- if (!HOST_PROXY_ALLOWED.has(method)) {
- throw Object.assign(
- new Error(`host method not allowed from sidecar: ${method}`),
- { code: -32601 },
- );
- }
- const params = (msg.params?.params ?? {}) as Record<string, unknown>;
- const requestedToolName = String(params.toolName ?? "");
- const planLocalTool =
- requestedToolName === "Skill" ||
- requestedToolName === "PluginCheck" ||
- requestedToolName === "PluginScaffold" ||
- requestedToolName === "PluginPack" ||
- requestedToolName.startsWith("plugin_");
- if (
- method === "tools.execute" &&
- params.mode === "plan" &&
- planLocalTool &&
- requestedToolName !== "BrowserPreview"
- ) {
- throw Object.assign(
- new Error(`${requestedToolName} is unavailable in Plan mode`),
- { code: -32000, data: { errorCode: "TOOL_DISABLED_IN_PLAN" } },
- );
- }
- if (method === "project.instructions.resolve") {
- if (!this.projectInstructionResolver) {
- throw new Error("project instruction resolver unavailable");
- }
- const sessionId = String(params.sessionId ?? "");
- const result = await this.projectInstructionResolver({
- sessionId,
- path: String(params.path ?? ""),
- projectPath: this.projectInstructionRoots.get(sessionId),
- });
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- return;
- }
- if (method === "provider.resolveAuth") {
- const result = await this.resolveVendorAuth(params);
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- return;
- }
- if (method === "provider.resolveSubagentModel") {
- const result = await this.resolveSubagentModel(params);
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- return;
- }
- if (method.startsWith("extensions.") || method === "session.queuePush" || method === "session.queuePrioritize") {
- const bridge = this.trustedExtensionBridge;
- if (!bridge) throw new Error("trusted extension bridge unavailable");
- let result: unknown = { ok: true };
- if (method === "extensions.commands.publish") bridge.publishCommands(params);
- else if (method === "extensions.diagnostics.publish") bridge.publishDiagnostics(params);
- else if (method === "extensions.model.configure") result = await bridge.configureModel(params);
- else if (method === "session.queuePush") result = await bridge.queuePush(params);
- else if (method === "session.queuePrioritize") result = await bridge.queuePrioritize(params);
- else result = await bridge.requestUi(params);
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- return;
- }
- // Main-local tools short-circuit before host-core (which doesn't
- // know them); everything else proxies through unchanged.
- const localTool =
- method === "tools.execute"
- ? this.localTools.get(requestedToolName)
- : undefined;
- if (localTool) {
- const toolName = requestedToolName;
- // Local tools can bypass host-core's permission boundary. Plan mode
- // therefore permits only the read-only BrowserPreview bridge; every
- // other main-local tool fails closed even if a stale runtime asks for
- // it directly.
- const result =
- params.mode === "plan" && toolName !== "BrowserPreview"
- ? {
- ok: false,
- isError: true,
- errorCode: "TOOL_DISABLED_IN_PLAN",
- content: `${toolName} is unavailable in Plan mode.`,
- }
- : await this.runLocalTool(localTool, {
- sessionId: String(params.sessionId ?? ""),
- toolCallId: String(params.toolCallId ?? ""),
- args: params.args,
- });
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- return;
- }
- if (!this.host) throw new Error("host unavailable");
- const result = await this.host.call(method, params);
- this.writeToChild(
- JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
- );
- } catch (e: any) {
- this.writeToChild(
- JSON.stringify({
- jsonrpc: "2.0",
- id: msg.id,
- error: {
- code: e?.code ?? -32000,
- message: e instanceof Error ? e.message : String(e),
- data: e?.data,
- },
- }) + "\n",
- );
- }
- return;
- }
-
- if (msg.id !== undefined && msg.id !== null && msg.method === undefined) {
- const pending = this.pending.get(String(msg.id));
- if (pending) {
- this.pending.delete(String(msg.id));
- if (pending.timer) clearTimeout(pending.timer);
- if (msg.error) {
- const err = new Error(msg.error.message) as Error & {
- code?: number;
- data?: unknown;
- };
- err.code = msg.error.code;
- err.data = msg.error.data;
- pending.reject(err);
- } else {
- pending.resolve(msg.result);
- }
- }
- return;
- }
-
- if (msg.method) {
- for (const h of this.handlers) h(msg.method, msg.params);
- }
- }
-
- onNotification(handler: SidecarNotificationHandler): () => void {
- if (this.closed) return () => undefined;
- this.handlers.add(handler);
- return () => this.handlers.delete(handler);
- }
-
- async call<T = unknown>(method: string, params: unknown = {}): Promise<T> {
- if (this.closed) throw new Error("agent sidecar is unavailable");
- const id = randomUUID();
- const timeoutMs = rpcTimeoutMs(method, params);
- const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
- return new Promise<T>((resolve, reject) => {
- this.pending.set(id, {
- resolve: resolve as (v: any) => void,
- reject,
- });
- const settle = (settleWith: (pending: {
- resolve: (v: any) => void;
- reject: (e: Error) => void;
- timer?: ReturnType<typeof setTimeout>;
- }) => void) => {
- const pending = this.pending.get(id);
- if (!pending) return;
- this.pending.delete(id);
- if (pending.timer) clearTimeout(pending.timer);
- settleWith(pending);
- };
- if (!this.writeToChild(payload)) {
- settle((pending) => pending.reject(new Error("agent sidecar stdin is unavailable")));
- }
- if (timeoutMs !== undefined) {
- const timer = setTimeout(() => {
- settle((pending) => pending.reject(new Error(`sidecar RPC timeout: ${method}`)));
- }, timeoutMs);
- const pending = this.pending.get(id);
- if (pending) pending.timer = timer;
- }
- });
- }
-
- async dispose(): Promise<void> {
- this.disposed = true;
- this.projectInstructionRoots.clear();
- this.vendorAuthBindings.clear();
- this.closeTransport(new Error("agent sidecar disposed"));
- this.exitHandlers.clear();
- if (this.child.exitCode !== null || this.child.signalCode !== null) return;
- // Wait for the process to actually leave so quit's settle step is real
- // rather than returning while the sidecar is still tearing down.
- await new Promise<void>((resolve) => {
- const timer = setTimeout(resolve, SIDECAR_DISPOSE_GRACE_MS);
- timer.unref?.();
- this.child.once("exit", () => {
- clearTimeout(timer);
- resolve();
- });
- this.child.kill();
+ onStderr: onStderr ?? fallbackStderrLogger,
});
}
}
-
-/** Upper bound on how long `dispose()` waits for the killed sidecar to exit. */
-const SIDECAR_DISPOSE_GRACE_MS = 2_000;
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.ts
index 14e7bb944..761d5d24f 100644
--- a/apps/desktop/electron/main/bootstrap/shutdown.ts
+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts
@@ -3,7 +3,7 @@ import type { CloseBehavior } from "@pi-desktop/shared";
import type { AgentSidecar } from "../agent-sidecar";
import type { BrowserPane } from "../browser-view";
import type { HostProcess } from "../host-process";
-import type { InflightCheckpointer } from "../inflight-checkpoint";
+import type { InflightCheckpointer } from "@pi-desktop/host-runtime";
import type { Logger } from "../logger";
import type { PersistenceOutbox } from "../persistence-outbox";
import type { PluginPanelHost } from "../plugin-panel-host";
diff --git a/apps/desktop/electron/main/host-process.ts b/apps/desktop/electron/main/host-process.ts
index 854125283..5b5a5f138 100644
--- a/apps/desktop/electron/main/host-process.ts
+++ b/apps/desktop/electron/main/host-process.ts
@@ -1,15 +1,11 @@
-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
-import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
- ErrorCodes,
- MAX_HOST_STDIN_LINE_BYTES,
- PROTOCOL_VERSION,
- readNdjsonLines,
- rpcTimeoutMs,
- stripProxyEnv,
-} from "@pi-desktop/shared";
+ HostProcess as RuntimeHostProcess,
+ type DiagnosedHostFailure,
+ type StderrHandler,
+} from "@pi-desktop/host-runtime";
+import { ErrorCodes } from "@pi-desktop/shared";
import {
GlibcUnsupportedError,
glibcMissingSymbol,
@@ -17,30 +13,11 @@ import {
import { DbSchemaTooNewError, parseSchemaTooNew } from "./host-boot-diagnostics";
import { redactValue } from "./logger";
-const HOST_DISPOSE_GRACE_MS = 3_000;
-const HOST_FORCE_KILL_GRACE_MS = 1_000;
-const HOST_OVERLOAD_RETRY_DELAYS_MS = [50, 100, 200, 400] as const;
-
-export type HostNotificationHandler = (method: string, params: unknown) => void;
-export type ProcessExitHandler = (info: {
- code: number | null;
- signal: NodeJS.Signals | null;
- intentional: boolean;
- /** Last child stderr lines before exit; only the agent sidecar fills it. */
- stderrTail?: string[];
-}) => void;
-export type StderrHandler = (text: string) => void;
-
-function isHostOverloaded(error: unknown): boolean {
- const candidate = error as {
- errorCode?: unknown;
- data?: { errorCode?: unknown };
- } | null;
- return (
- candidate?.errorCode === ErrorCodes.HOST_OVERLOADED ||
- candidate?.data?.errorCode === ErrorCodes.HOST_OVERLOADED
- );
-}
+export type {
+ HostNotificationHandler,
+ ProcessExitHandler,
+ StderrHandler,
+} from "@pi-desktop/host-runtime";
function resolveHostBinary(): string {
if (process.env.PI_DESKTOP_HOST_BIN && existsSync(process.env.PI_DESKTOP_HOST_BIN)) {
@@ -81,345 +58,65 @@ function resolveBuiltinPluginsDir(): string | null {
return null;
}
-export class HostProcess {
- private child: ChildProcessWithoutNullStreams;
- private pending = new Map<
- string,
- {
- resolve: (v: any) => void;
- reject: (e: Error) => void;
- timer?: ReturnType<typeof setTimeout>;
- }
- >();
- private handlers = new Set<HostNotificationHandler>();
- private exitHandlers = new Set<ProcessExitHandler>();
- private disposed = false;
- private available = true;
- private closed = false;
- private exitNotified = false;
- private exitObserved = false;
- private exitPromise: Promise<void>;
- private resolveExit!: () => void;
- private disposePromise?: Promise<void>;
- private stdoutReader?: ReturnType<typeof readNdjsonLines>;
- private lastStderr = "";
- readonly binaryPath: string;
- readonly generation = randomUUID();
-
- constructor(dataDir: string, onStderr?: StderrHandler) {
- this.exitPromise = new Promise<void>((resolve) => {
- this.resolveExit = resolve;
- });
- this.binaryPath = resolveHostBinary();
- const builtinPlugins = resolveBuiltinPluginsDir();
- this.child = spawn(this.binaryPath, [], {
- stdio: ["pipe", "pipe", "pipe"],
- env: {
- ...stripProxyEnv(process.env),
- PI_DESKTOP_DATA_DIR: dataDir,
- // Only Electron knows whether this build runs from `resources/` or a
- // source checkout, so it resolves the bundled-plugin directory and
- // host-core simply reconciles its registry against it (ADR 0105).
- ...(builtinPlugins ? { PI_DESKTOP_BUILTIN_PLUGINS_DIR: builtinPlugins } : {}),
- },
- });
-
- this.child.stderr.setEncoding("utf8");
- this.child.stderr.on("data", (text: string) => {
- if (!text) return;
- this.lastStderr = `${this.lastStderr}${text}`.slice(-4_000);
- if (onStderr) onStderr(text);
- else {
- console.error(
- `[host/runtime] ${JSON.stringify({
- ts: new Date().toISOString(),
- level: "info",
- channel: "host",
- category: "runtime",
- event: "child.process.stderr",
- message: "child process stderr",
- data: { output: redactValue(text.trimEnd()) },
- })}`,
- );
- }
- });
-
- this.child.on("exit", (code, signal) => {
- this.available = false;
- this.closeTransport(this.unavailableError("host-core exited"));
- this.exitObserved = true;
- this.resolveExit();
- this.notifyExit({ code, signal, intentional: this.disposed });
- this.cleanupProcessListeners();
- });
- this.child.on("error", (error) => {
- this.available = false;
- const failure = this.unavailableError(
- `host-core process error: ${error.message}`,
- );
- this.closeTransport(failure);
- // A spawn failure never produces an `exit` event, so without settling the
- // exit promise here `dispose()` would wait the full grace period, send a
- // SIGKILL to a process that never started, and wait again.
- if (this.child.pid === undefined || this.child.exitCode !== null) {
- this.exitObserved = true;
- this.resolveExit();
- }
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- if (this.exitObserved) this.cleanupProcessListeners();
- });
-
- this.stdoutReader = readNdjsonLines(this.child.stdout, (line) =>
- this.onLine(line),
- );
- }
-
- private closeTransport(error: Error) {
- if (this.closed) return;
- this.available = false;
- this.closed = true;
- for (const [, p] of this.pending) {
- if (p.timer) clearTimeout(p.timer);
- p.reject(error);
- }
- this.pending.clear();
- this.handlers.clear();
- this.stdoutReader?.close();
- this.stdoutReader = undefined;
- }
-
- private cleanupProcessListeners() {
- this.child.removeAllListeners("exit");
- this.child.removeAllListeners("error");
- this.child.stderr.removeAllListeners("data");
- }
-
- private waitForExit(timeoutMs: number): Promise<boolean> {
- if (this.exitObserved) return Promise.resolve(true);
- return new Promise((resolve) => {
- let settled = false;
- const finish = (observed: boolean) => {
- if (settled) return;
- settled = true;
- if (timer) clearTimeout(timer);
- resolve(observed);
- };
- const timer = setTimeout(() => finish(false), timeoutMs);
- timer.unref?.();
- this.exitPromise.then(() => finish(true));
+/**
+ * Name the two boot refusals the desktop phrases for the user (D380): a data
+ * directory newer than this build, and a glibc below the packaged floor. The
+ * schema refusal is checked first because its stderr line is the more specific
+ * one; anything else stays the generic `HOST_UNAVAILABLE` transport error.
+ */
+export function diagnoseHostFailure({
+ lastStderr,
+ message,
+}: {
+ lastStderr: string;
+ message: string;
+}): DiagnosedHostFailure | null {
+ const schema = parseSchemaTooNew(lastStderr) ?? parseSchemaTooNew(message);
+ if (schema) {
+ return Object.assign(new DbSchemaTooNewError(schema), {
+ errorCode: ErrorCodes.HOST_UNAVAILABLE,
});
}
-
- private notifyExit(info: {
- code: number | null;
- signal: NodeJS.Signals | null;
- intentional: boolean;
- }) {
- if (this.exitNotified) return;
- this.exitNotified = true;
- for (const h of this.exitHandlers) h(info);
- this.exitHandlers.clear();
- }
-
- /**
- * Every rejection that only means "the transport is gone" is built here, so a
- * caller can tell routine teardown from a real failure by the error code
- * rather than by matching message text.
- */
- private unavailableError(message: string): Error & { errorCode: string } {
- const schema = parseSchemaTooNew(this.lastStderr) ?? parseSchemaTooNew(message);
- if (schema) {
- return Object.assign(new DbSchemaTooNewError(schema), {
- errorCode: ErrorCodes.HOST_UNAVAILABLE,
- });
- }
- if (glibcMissingSymbol(this.lastStderr) || glibcMissingSymbol(message)) {
- return Object.assign(new GlibcUnsupportedError(), {
- errorCode: ErrorCodes.HOST_UNAVAILABLE,
- });
- }
- return Object.assign(new Error(message), {
+ if (glibcMissingSymbol(lastStderr) || glibcMissingSymbol(message)) {
+ return Object.assign(new GlibcUnsupportedError(), {
errorCode: ErrorCodes.HOST_UNAVAILABLE,
});
}
+ return null;
+}
- isAvailable(): boolean {
- return (
- this.available &&
- !this.closed &&
- this.child.exitCode === null &&
- !this.child.killed
- );
- }
-
- onExit(handler: ProcessExitHandler): () => void {
- if (this.closed) return () => undefined;
- this.exitHandlers.add(handler);
- return () => this.exitHandlers.delete(handler);
- }
-
- private onLine(line: string) {
- if (!line.trim()) return;
- let msg: any;
- try {
- msg = JSON.parse(line);
- } catch {
- console.warn(
- `[RPC] Invalid host-process NDJSON frame (${Buffer.byteLength(line, "utf8")} bytes)`,
- );
- return;
- }
- if (msg.id !== undefined && msg.id !== null) {
- const pending = this.pending.get(String(msg.id));
- if (pending) {
- this.pending.delete(String(msg.id));
- if (pending.timer) clearTimeout(pending.timer);
- if (msg.error) {
- const err = new Error(msg.error.message) as Error & {
- code?: number;
- data?: unknown;
- errorCode?: string;
- };
- err.code = msg.error.code;
- err.data = msg.error.data;
- const errorCode =
- msg.error.data && typeof msg.error.data.errorCode === "string"
- ? msg.error.data.errorCode
- : undefined;
- if (errorCode) err.errorCode = errorCode;
- pending.reject(err);
- } else {
- pending.resolve(msg.result);
- }
- }
- return;
- }
- if (msg.method) {
- for (const h of this.handlers) h(msg.method, msg.params);
- }
- }
-
- onNotification(handler: HostNotificationHandler): () => void {
- if (this.closed) return () => undefined;
- this.handlers.add(handler);
- return () => this.handlers.delete(handler);
- }
-
- async call<T = unknown>(
- method: string,
- params: unknown = {},
- timeoutOverrideMs?: number,
- ): Promise<T> {
- for (const delayMs of [0, ...HOST_OVERLOAD_RETRY_DELAYS_MS]) {
- if (delayMs > 0) {
- await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
- }
- try {
- return await this.callOnce<T>(method, params, timeoutOverrideMs);
- } catch (error) {
- if (
- !isHostOverloaded(error) ||
- delayMs === HOST_OVERLOAD_RETRY_DELAYS_MS.at(-1)
- ) {
- throw error;
- }
- }
- }
- throw new Error(`host RPC retry exhausted: ${method}`);
- }
+function fallbackStderrLogger(text: string): void {
+ console.error(
+ `[host/runtime] ${JSON.stringify({
+ ts: new Date().toISOString(),
+ level: "info",
+ channel: "host",
+ category: "runtime",
+ event: "child.process.stderr",
+ message: "child process stderr",
+ data: { output: redactValue(text.trimEnd()) },
+ })}`,
+ );
+}
- private async callOnce<T = unknown>(
- method: string,
- params: unknown,
- timeoutOverrideMs?: number,
- ): Promise<T> {
- if (this.closed) throw this.unavailableError("host-core is unavailable");
- if (!this.isAvailable()) {
- throw this.unavailableError(`host RPC unavailable: ${method}`);
- }
- const id = randomUUID();
- const timeoutMs = timeoutOverrideMs ?? rpcTimeoutMs(method, params);
- const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
- if (Buffer.byteLength(payload, "utf8") > MAX_HOST_STDIN_LINE_BYTES) {
- throw Object.assign(new Error("request line exceeds 64 MiB"), {
- errorCode: ErrorCodes.LIMIT_EXCEEDED,
- code: 1002,
- });
- }
- return new Promise<T>((resolve, reject) => {
- let timer: ReturnType<typeof setTimeout> | undefined;
- let settled = false;
- const settle = (finish: () => void) => {
- if (settled) return;
- settled = true;
- this.pending.delete(id);
- if (timer) clearTimeout(timer);
- finish();
- };
- this.pending.set(id, {
- resolve: (value) => settle(() => resolve(value)),
- reject: (error) => settle(() => reject(error)),
- });
- if (!this.isAvailable()) {
- settle(() => reject(this.unavailableError(`host RPC unavailable: ${method}`)));
- return;
- }
- if (timeoutMs !== undefined) {
- timer = setTimeout(
- () => settle(() => reject(new Error(`host RPC timeout: ${method}`))),
- timeoutMs,
- );
- }
- try {
- this.child.stdin.write(payload, (error) => {
- if (!error) return;
- const failure = this.unavailableError(
- `host RPC write failed: ${error.message}`,
- );
- settle(() => reject(failure));
- this.closeTransport(failure);
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- });
- } catch (error) {
- const failure = this.unavailableError(
- `host RPC write failed: ${error instanceof Error ? error.message : String(error)}`,
- );
- settle(() => reject(failure));
- this.closeTransport(failure);
- this.notifyExit({ code: null, signal: null, intentional: this.disposed });
- }
+/**
+ * The desktop's host-core child: the shared stdio transport from
+ * `@pi-desktop/host-runtime` plus the two things only Electron knows — where
+ * this build keeps the binary and its bundled plugins, and how to name the
+ * boot refusals the renderer phrases.
+ */
+export class HostProcess extends RuntimeHostProcess {
+ constructor(dataDir: string, onStderr?: StderrHandler) {
+ const builtinPlugins = resolveBuiltinPluginsDir();
+ super({
+ binaryPath: resolveHostBinary(),
+ dataDir,
+ // Only Electron knows whether this build runs from `resources/` or a
+ // source checkout, so it resolves the bundled-plugin directory and
+ // host-core simply reconciles its registry against it (ADR 0105).
+ env: builtinPlugins ? { PI_DESKTOP_BUILTIN_PLUGINS_DIR: builtinPlugins } : {},
+ onStderr: onStderr ?? fallbackStderrLogger,
+ diagnoseFailure: diagnoseHostFailure,
});
}
-
- async handshake(): Promise<void> {
- await this.call("app.handshake", { protocolVersion: PROTOCOL_VERSION });
- }
-
- async dispose(): Promise<void> {
- if (this.disposePromise) return this.disposePromise;
- this.disposePromise = this.disposeInternal();
- return this.disposePromise;
- }
-
- private async disposeInternal(): Promise<void> {
- this.disposed = true;
- this.available = false;
- // EOF is the graceful host-core shutdown signal. Send it before rejecting
- // transport callers so the runner can clean up active tools first.
- if (!this.child.stdin.destroyed && !this.child.stdin.writableEnded) {
- this.child.stdin.end();
- }
- this.closeTransport(this.unavailableError("host-core disposed"));
- if (this.exitObserved) return;
-
- const exited = await this.waitForExit(HOST_DISPOSE_GRACE_MS);
- if (exited || this.exitObserved) return;
-
- try {
- this.child.kill("SIGKILL");
- } catch {
- // The child may have exited between the grace check and kill fallback.
- }
- await this.waitForExit(HOST_FORCE_KILL_GRACE_MS);
- }
}
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 564642188..480fbeec7 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -50,7 +50,6 @@ import {
shouldShowNativeNotification,
} from "./notification-policy";
import { PersistenceOutbox } from "./persistence-outbox";
-import { InflightCheckpointer } from "./inflight-checkpoint";
import { AgentSidecar } from "./agent-sidecar";
import { Logger, ignoreBrokenStdio } from "./logger";
import { installMainProcessErrorHandlers } from "./main-process-errors";
@@ -89,10 +88,11 @@ import {
type PreparedPromptAttachment,
} from "./prompt-attachments";
import {
+ InflightCheckpointer,
executionFromResponse,
executionListFromResponse,
planExecutionFromUnknown,
-} from "./plan-execution";
+} from "@pi-desktop/host-runtime";
import {
readWindowState,
writeWindowState,
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 5a3fd3d18..f83b69c1f 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -3,8 +3,7 @@ import type { FinishTurn } from "../runtime/plans";
import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";
import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";
import { appendPromptFallbackPaths, durableUserMessageId, preparePromptAttachments, type PreparedPromptAttachment } from "../prompt-attachments";
-import { executionFromResponse } from "../plan-execution";
-import { resolveSessionMessageInput } from "../session-message-input";
+import { executionFromResponse, resolveSessionMessageInput } from "@pi-desktop/host-runtime";
import type { AgentExtensionBridge } from "../agent-extensions";
import type { AgentHostBridge } from "../agent-host-bridge";
import type { AgentSidecar } from "../agent-sidecar";
diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.ts
index 75810d3c8..972dc9fc0 100644
--- a/apps/desktop/electron/main/runtime/event-persistence.ts
+++ b/apps/desktop/electron/main/runtime/event-persistence.ts
@@ -1,7 +1,7 @@
import { applyMessageUpdate, IPC, type AgentEventEnvelope, type UiMessage } from "@pi-desktop/shared";
import type { FinishTurn } from "./plans";
import type { RuntimeState } from "./context";
-import type { InflightCheckpointer } from "../inflight-checkpoint";
+import type { InflightCheckpointer } from "@pi-desktop/host-runtime";
import type { Logger } from "../logger";
import type { PersistenceOutbox } from "../persistence-outbox";
diff --git a/apps/desktop/electron/main/runtime/lifecycle.ts b/apps/desktop/electron/main/runtime/lifecycle.ts
index a693b34f2..d2afdd4cc 100644
--- a/apps/desktop/electron/main/runtime/lifecycle.ts
+++ b/apps/desktop/electron/main/runtime/lifecycle.ts
@@ -19,6 +19,7 @@ import type { Logger } from "../logger";
import type { PluginRuntime } from "../plugin-runtime";
import type { RuntimeState } from "./context";
import { syncPluginDisplayLocale } from "../plugin-display-locale";
+import { RuntimeSupervisor } from "@pi-desktop/host-runtime";
type RestartKind = "host" | "sidecar";
export type RuntimeLifecycleDependencies = {
@@ -66,111 +67,108 @@ export function createRuntimeLifecycle({
runtimeArch: () => ReturnType<typeof detectRuntimeArch>;
bootBackends: () => Promise<void>;
} {
- const restartState = {
- host: { count: 0, windowStart: 0 },
- sidecar: { count: 0, windowStart: 0 },
- };
- const restartInFlight: Record<RestartKind, Promise<void> | null> = {
- host: null,
- sidecar: null,
- };
let runtimeArchCache: ReturnType<typeof detectRuntimeArch> | null = null;
- const superviseRestart = (kind: RestartKind): Promise<void> => {
- const existing = restartInFlight[kind];
- if (existing) return existing;
- const run = superviseRestartLoop(kind).finally(() => {
- if (restartInFlight[kind] === run) restartInFlight[kind] = null;
- });
- restartInFlight[kind] = run;
- return run;
+ /**
+ * Fatal boot refusals a restart can never fix (D380): the schema check comes
+ * first because its stderr line is the more specific one.
+ */
+ const fatalStatusFor = (kind: RestartKind, error: unknown): HostStatusEvent | null => {
+ const schema = schemaTooNewOf(error);
+ if (schema) {
+ logger.app("runtime", "error", "local data schema is newer than this build", {
+ code: ErrorCodes.HOST_UNAVAILABLE,
+ data: schema,
+ });
+ return {
+ ok: false,
+ component: kind,
+ fatal: true,
+ message: DB_SCHEMA_TOO_NEW_STATUS,
+ schema,
+ };
+ }
+ if (isGlibcUnsupportedError(error)) {
+ logger.app("runtime", "error", "linux glibc is below the packaged host floor", {
+ code: ErrorCodes.HOST_UNAVAILABLE,
+ data: String(error),
+ });
+ return {
+ ok: false,
+ component: kind,
+ fatal: true,
+ message: GLIBC_UNSUPPORTED_STATUS,
+ };
+ }
+ return null;
};
- async function superviseRestartLoop(kind: RestartKind): Promise<void> {
- const state = restartState[kind];
- while (!isQuitting()) {
- const now = Date.now();
- if (now - state.windowStart > 120_000) {
- state.windowStart = now;
- state.count = 0;
- }
- state.count += 1;
- if (state.count > 3) {
- logger.app(
- "runtime",
- "error",
- kind + " restart limit reached; giving up",
- { code: ErrorCodes.HOST_UNAVAILABLE },
- );
- sendToRenderer(IPC.event.hostStatus, {
- ok: false,
- component: kind,
- fatal: true,
- });
- return;
- }
- const delay = Math.min(500 * 2 ** (state.count - 1), 4000);
- await new Promise((resolve) => setTimeout(resolve, delay));
- if (isQuitting()) return;
- try {
- if (kind === "host") {
- await startHost();
- const sidecar = runtimeState.sidecar;
- const host = runtimeState.host;
- if (sidecar && host) sidecar.setHost(host);
- // A fresh host process starts in English, so the app language and
- // the language-dependent rows it draws have to be restored here:
- // nothing else re-applies settings after a crash.
- await syncPluginDisplayLocale(host, getDisplayLocale());
- } else {
- await startSidecar();
- }
- await drainApprovedPlanExecutions();
- logger.app("runtime", "warn", kind + " restarted after crash");
- sendToRenderer(IPC.event.hostStatus, {
- ok: true,
- component: kind,
- restarted: true,
- });
- // The plugin rows were drawn from the dead process: re-read them so a
- // restart is invisible in the Extensions page and the launcher.
- sendToRenderer(IPC.event.pluginChanged, { reason: "hostRestart" });
- return;
- } catch (error) {
- const schema = schemaTooNewOf(error);
- if (schema) {
- logger.app("runtime", "error", "local data schema is newer than this build", {
- code: ErrorCodes.HOST_UNAVAILABLE,
- data: schema,
- });
+ // The restart policy itself (backoff, window budget, single flight) is the
+ // shared supervisor; everything renderer- or plugin-facing stays here.
+ const supervisor = new RuntimeSupervisor({
+ start: {
+ host: async () => {
+ await startHost();
+ const sidecar = runtimeState.sidecar;
+ const host = runtimeState.host;
+ if (sidecar && host) sidecar.setHost(host);
+ // A fresh host process starts in English, so the app language and
+ // the language-dependent rows it draws have to be restored here:
+ // nothing else re-applies settings after a crash.
+ await syncPluginDisplayLocale(host, getDisplayLocale());
+ },
+ sidecar: startSidecar,
+ },
+ afterRestart: () => drainApprovedPlanExecutions(),
+ isUnrecoverable: (error) => Boolean(schemaTooNewOf(error)) || isGlibcUnsupportedError(error),
+ isShuttingDown: isQuitting,
+ onEvent: (event) => {
+ const { kind } = event;
+ switch (event.phase) {
+ case "fatal": {
+ if (event.reason === "unrecoverable") {
+ const status = fatalStatusFor(kind, event.error);
+ if (status) sendToRenderer(IPC.event.hostStatus, status);
+ return;
+ }
+ logger.app(
+ "runtime",
+ "error",
+ kind + " restart limit reached; giving up",
+ { code: ErrorCodes.HOST_UNAVAILABLE },
+ );
sendToRenderer(IPC.event.hostStatus, {
ok: false,
component: kind,
fatal: true,
- message: DB_SCHEMA_TOO_NEW_STATUS,
- schema,
});
return;
}
- if (isGlibcUnsupportedError(error)) {
- logger.app("runtime", "error", "linux glibc is below the packaged host floor", {
- code: ErrorCodes.HOST_UNAVAILABLE,
- data: String(error),
- });
+ case "restarted": {
+ logger.app("runtime", "warn", kind + " restarted after crash");
sendToRenderer(IPC.event.hostStatus, {
- ok: false,
+ ok: true,
component: kind,
- fatal: true,
- message: GLIBC_UNSUPPORTED_STATUS,
+ restarted: true,
});
+ // The plugin rows were drawn from the dead process: re-read them so a
+ // restart is invisible in the Extensions page and the launcher.
+ sendToRenderer(IPC.event.pluginChanged, { reason: "hostRestart" });
return;
}
- logger.app("runtime", "error", kind + " restart failed", {
- data: String(error),
- });
+ case "restart_failed":
+ logger.app("runtime", "error", kind + " restart failed", {
+ data: String(event.error),
+ });
+ return;
+ case "restarting":
+ return;
}
- }
- }
+ },
+ });
+
+ const superviseRestart = (kind: RestartKind): Promise<void> =>
+ supervisor.superviseRestart(kind);
/**
* Boot outcome pushed once the renderer has mounted. Known unrecoverable
diff --git a/apps/desktop/electron/main/runtime/plans.ts b/apps/desktop/electron/main/runtime/plans.ts
index be3d59647..5f53b32af 100644
--- a/apps/desktop/electron/main/runtime/plans.ts
+++ b/apps/desktop/electron/main/runtime/plans.ts
@@ -1,5 +1,5 @@
import { ErrorCodes, IPC, type AgentEventEnvelope, type AppNotification, type PlanExecution, type PlanExecutionFinishStatus, type UiMessage } from "@pi-desktop/shared";
-import { executionFromResponse, executionListFromResponse, planExecutionFromUnknown } from "../plan-execution";
+import { executionFromResponse, executionListFromResponse, planExecutionFromUnknown } from "@pi-desktop/host-runtime";
import type { RuntimeState } from "./context";
import type {
SessionCoordination,
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 1d2522db9..685734af0 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -14,7 +14,7 @@ import { AgentSidecar } from "../agent-sidecar";
import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";
import type { AgentExtensionBridge } from "../agent-extensions";
import type { BrowserHost } from "../browser-host";
-import type { InflightCheckpointer } from "../inflight-checkpoint";
+import type { InflightCheckpointer } from "@pi-desktop/host-runtime";
import { summarizeToolResult, type Logger } from "../logger";
import type { ModelsDevCatalog } from "../models-dev-catalog";
import type { PluginRuntime } from "../plugin-runtime";
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 72358616d..e22f8bf46 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -37,6 +37,7 @@
"@earendil-works/pi-ai": "0.85.1",
"@pi-desktop/agent-host": "workspace:*",
"@pi-desktop/agent-runtime": "workspace:*",
+ "@pi-desktop/host-runtime": "workspace:*",
"@pi-desktop/i18n": "workspace:*",
"@pi-desktop/plugin-devkit": "workspace:*",
"@pi-desktop/plugin-sdk": "workspace:*",
diff --git a/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjs
index b42c2f14f..2e4308fb6 100644
--- a/apps/desktop/test/browser-preview-tool.test.mjs
+++ b/apps/desktop/test/browser-preview-tool.test.mjs
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
const sidecarSource = await readFile(
- new URL("../electron/main/agent-sidecar.ts", import.meta.url),
+ new URL("../../../packages/host-runtime/src/agent-sidecar.ts", import.meta.url),
"utf8",
);
const mainSource = await readMainSource();
diff --git a/apps/desktop/test/host-boot-diagnostics.test.mjs b/apps/desktop/test/host-boot-diagnostics.test.mjs
index 62440bb50..017c5e3a7 100644
--- a/apps/desktop/test/host-boot-diagnostics.test.mjs
+++ b/apps/desktop/test/host-boot-diagnostics.test.mjs
@@ -108,20 +108,32 @@ test("an Intel build under Rosetta is a mismatch; native builds are not", () =>
});
test("host-process turns the refusal into a typed error before glibc matching", () => {
- const body = hostSrc.slice(hostSrc.indexOf("private unavailableError("));
- const schemaAt = body.indexOf("parseSchemaTooNew(this.lastStderr)");
- const glibcAt = body.indexOf("glibcMissingSymbol(this.lastStderr)");
+ // The transport lives in @pi-desktop/host-runtime; the desktop only names
+ // the refusals it can phrase, through the injected failure diagnosis.
+ const body = hostSrc.slice(hostSrc.indexOf("export function diagnoseHostFailure("));
+ const schemaAt = body.indexOf("parseSchemaTooNew(lastStderr)");
+ const glibcAt = body.indexOf("glibcMissingSymbol(lastStderr)");
assert.ok(schemaAt > 0 && glibcAt > 0);
assert.ok(schemaAt < glibcAt, "schema refusal must be checked first");
assert.match(body, /new DbSchemaTooNewError\(schema\)/);
+ assert.match(hostSrc, /diagnoseFailure: diagnoseHostFailure,/);
});
test("main stops restarting on a schema refusal and pushes a named status", () => {
- const loop = lifecycleSrc.slice(lifecycleSrc.indexOf("async function superviseRestartLoop("));
- const schemaAt = loop.indexOf("schemaTooNewOf(error)");
- const glibcAt = loop.indexOf("isGlibcUnsupportedError(error)");
+ // The restart policy lives in the shared RuntimeSupervisor; main only names
+ // the two unrecoverable refusals and phrases their status for the renderer.
+ const fatal = lifecycleSrc.slice(
+ lifecycleSrc.indexOf("const fatalStatusFor ="),
+ lifecycleSrc.indexOf("const supervisor = new RuntimeSupervisor("),
+ );
+ const schemaAt = fatal.indexOf("schemaTooNewOf(error)");
+ const glibcAt = fatal.indexOf("isGlibcUnsupportedError(error)");
assert.ok(schemaAt > 0 && schemaAt < glibcAt);
- assert.match(loop.slice(schemaAt, glibcAt), /message: DB_SCHEMA_TOO_NEW_STATUS,\s*schema,\s*\}\);\s*return;/);
+ assert.match(fatal.slice(schemaAt, glibcAt), /message: DB_SCHEMA_TOO_NEW_STATUS,\s*schema,\s*\};/);
+ assert.match(
+ lifecycleSrc,
+ /isUnrecoverable: \(error\) => Boolean\(schemaTooNewOf\(error\)\) \|\| isGlibcUnsupportedError\(error\)/,
+ );
const boot = lifecycleSrc.slice(lifecycleSrc.indexOf("const bootHostStatus ="));
assert.match(boot, /status\.message = DB_SCHEMA_TOO_NEW_STATUS;\s*status\.schema = schema;/);
assert.match(boot, /status\.archMismatch = \{/);
diff --git a/apps/desktop/test/inflight-checkpoint.test.mjs b/apps/desktop/test/inflight-checkpoint.test.mjs
index e3bb428ea..c8ced5254 100644
--- a/apps/desktop/test/inflight-checkpoint.test.mjs
+++ b/apps/desktop/test/inflight-checkpoint.test.mjs
@@ -4,7 +4,7 @@ import test from "node:test";
import {
InflightCheckpointer,
isCheckpointableMessage,
-} from "../electron/main/inflight-checkpoint.ts";
+} from "../../../packages/host-runtime/src/inflight-checkpoint.ts";
const assistant = (id, content, thinking) => ({
id,
diff --git a/apps/desktop/test/network-proxy.test.mjs b/apps/desktop/test/network-proxy.test.mjs
index 9a9dd6af2..6ee0cb5c3 100644
--- a/apps/desktop/test/network-proxy.test.mjs
+++ b/apps/desktop/test/network-proxy.test.mjs
@@ -15,7 +15,7 @@ const nodeProxy = await readFile(
"utf8",
);
const hostProcess = await readFile(
- new URL("../electron/main/host-process.ts", import.meta.url),
+ new URL("../../../packages/host-runtime/src/host-process.ts", import.meta.url),
"utf8",
);
const hostProxy = await readFile(
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index 3a191b7fb..40c107824 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
const sidecarSource = await readFile(
- new URL("../electron/main/agent-sidecar.ts", import.meta.url),
+ new URL("../../../packages/host-runtime/src/agent-sidecar.ts", import.meta.url),
"utf8",
);
const runtimeSidecarSource = await readFile(
@@ -12,7 +12,7 @@ const runtimeSidecarSource = await readFile(
"utf8",
);
const hostSource = await readFile(
- new URL("../electron/main/host-process.ts", import.meta.url),
+ new URL("../../../packages/host-runtime/src/host-process.ts", import.meta.url),
"utf8",
);
const mainSource = await readMainSource();
diff --git a/apps/desktop/test/session-message-input.test.mjs b/apps/desktop/test/session-message-input.test.mjs
index 05050f6c9..5ce7adfff 100644
--- a/apps/desktop/test/session-message-input.test.mjs
+++ b/apps/desktop/test/session-message-input.test.mjs
@@ -4,7 +4,7 @@ import test from "node:test";
import { IPC } from "@pi-desktop/shared";
register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
-const { resolveSessionMessageInput } = await import("../electron/main/session-message-input.ts");
+const { resolveSessionMessageInput } = await import("../../../packages/host-runtime/src/session-message-input.ts");
const { registerAgentIpc } = await import("../electron/main/ipc/agent-ipc.ts");
const message = {
diff --git a/apps/desktop/test/subagent-wiring.test.mjs b/apps/desktop/test/subagent-wiring.test.mjs
index b575b7fb1..6e7085042 100644
--- a/apps/desktop/test/subagent-wiring.test.mjs
+++ b/apps/desktop/test/subagent-wiring.test.mjs
@@ -25,7 +25,7 @@ const hostCollectionSource = await readFile(
"utf8",
);
const hostProcessSource = await readFile(
- new URL("../electron/main/host-process.ts", import.meta.url),
+ new URL("../../../packages/host-runtime/src/host-process.ts", import.meta.url),
"utf8",
);
diff --git a/docs/adr/0282-headless-runtime-boundary.md b/docs/adr/0282-headless-runtime-boundary.md
new file mode 100644
index 000000000..1ffc08750
--- /dev/null
+++ b/docs/adr/0282-headless-runtime-boundary.md
@@ -0,0 +1,118 @@
+# ADR 0282: Headless runtime boundary in `packages/host-runtime`
+
+- Status: Accepted for implementation
+- Date: 2026-09-18
+- Decision: D445
+- Related: ADR 0205 (D373 / D374 / D375), ADR 0213 (D386),
+ `02-architecture/05-remote-agent-control.md` §4 and §11,
+ `03-runtime/07-process-model.md` §4,
+ `06-delivery/07-remote-control-rollout.md` R2
+
+## Context
+
+Rollout R1 delivered the headless Agent Host module (`packages/agent-host`):
+admission, the turn queue, the approval broker, the event log, and the
+snapshot builder run without Electron. Everything underneath it did not. The
+stdio transports to host-core and the agent sidecar, the restart supervisor,
+the durable turn lifecycle (`session.beginTurn` → prompt → `session.endTurn`),
+transcript persistence, the in-flight reply checkpoint, and approved
+Plan/Goal execution all lived in `apps/desktop/electron/main`, and the
+Electron `AgentHost` bridge reached them by invoking the desktop's own IPC
+handlers. `HostProcess` resolved the binary from `process.resourcesPath`, and
+`AgentSidecar` could only start the sidecar as
+`process.execPath` + `ELECTRON_RUN_AS_NODE`.
+
+R2 needs the same runtime on a machine that has no Electron: the `pi-host`
+bundle (`02-architecture/05-remote-agent-control.md` §5.2) must run the Agent
+Host module, the sidecar, and host-core behind a RACP server. Re-implementing
+the turn lifecycle in a second place would create a second source of truth
+for exactly the invariants the desktop spent a year fixing (abort locks,
+stale terminal events, single-flight finalization, queue release after
+durable settlement).
+
+## Decision
+
+1. **A new workspace package, `packages/host-runtime`, owns the
+ Electron-independent runtime layer.** It depends on `shared`,
+ `agent-host`, and `agent-runtime` only, and never on `electron` or on
+ `apps/desktop`. Its modules are:
+ - `HostProcess` and `AgentSidecar`: the stdio NDJSON JSON-RPC transports,
+ moved from Electron main unchanged in behavior. Both take their launch
+ as options — `binaryPath` / `dataDir` / extra `env` for host-core,
+ `{ command, args, env }` for the sidecar — and an `onStderr` sink. The
+ sidecar's `host.proxy` allowlist, local-tool short circuit, Plan-mode
+ gate, vendor-auth binding check, and trusted-extension bridge are
+ unchanged. `HostProcess` accepts an optional `diagnoseFailure` hook so
+ an embedding host can name a boot refusal it can phrase.
+ - `RuntimeSupervisor`: the restart policy of process-model §4 (0.5s → 1s
+ → 2s capped at 4s, three restarts per two-minute window, single flight
+ per child, never during shutdown, stop on the first unrecoverable
+ failure). The embedding host supplies `start`, `afterRestart`,
+ `isUnrecoverable`, and an event sink.
+ - `RuntimeService`: `RuntimePort` for the Agent Host module on top of the
+ two transports — prompt admission with the durable turn row and the
+ user message appended before the sidecar starts, steer, stop, abort
+ with the abort lock, asktool answers, manual compaction, and
+ `finishTurn` with the same claim-before-await rule, stale-terminal
+ guard, and settlement announcement as Electron main.
+ - `TurnEventPipeline` and `TurnPersistence`: the per-event pass
+ (tool-call tracking, D299 checkpoints, terminal events, completed rows)
+ and an in-memory ordered append queue with a bounded retry while
+ host-core restarts. A `pi-host` process ends only with its supervisor,
+ so the desktop's file-backed outbox is not duplicated.
+ - `createHeadlessLaunchResolver`: launch resolution from host-core's own
+ registries (providers and secrets, the effective command shell, project
+ instructions and memory, user skills, subagent definitions). It refuses
+ vendor OAuth accounts and plugin agents, which need the desktop.
+ - `PlanExecutionDispatcher`: approved Plan/Goal execution (D189) with the
+ same claim, no-replay, and finalization rules.
+ - Host-core adapters for the module's `SessionPort`, `QueueStore`
+ (schema v15), and `permissions.pending`, plus the session-message
+ ledger lookup, the inflight checkpointer, and the plan-execution
+ decoders, moved out of Electron main.
+2. **Electron main keeps thin adapters.** `electron/main/host-process.ts`
+ and `agent-sidecar.ts` subclass the package classes and add only what
+ Electron knows: the packaged binary and bundled-plugin locations, the
+ `ELECTRON_RUN_AS_NODE` launch, redacted stderr logging, and the
+ schema-too-new / glibc diagnoses. `runtime/lifecycle.ts` drives the shared
+ supervisor and keeps the renderer status pushes, plugin locale resync,
+ and approved-plan drain. The Agent Host bridge uses the shared host-core
+ ports instead of its own copies. The local prompt path (`agent-ipc.ts`),
+ with its attachments, slash expansion, plugin tools, MCP relay, vendor
+ accounts, and notifications, is unchanged and still owned by the desktop.
+3. **`TurnStartRequest` gains an optional `userMessageId`** so a client can
+ keep its optimistic user row id through the headless runtime, exactly as
+ the renderer does through IPC (D288). Additive; no caller is required to
+ send it.
+4. **No wire contract changes.** Electron IPC, the sidecar JSON-RPC, host-core
+ RPC, and the Plugin SDK are untouched; the desktop's observable behavior,
+ defaults, and persisted data are unchanged.
+
+## Consequences
+
+- `pi-host` (R2) can compose `HostProcess + AgentSidecar + RuntimeService +
+ AgentHost + RuntimeSupervisor` in plain Node; the RACP server binds to the
+ module, never to Electron IPC.
+- The restart policy, the turn lifecycle, and the transports now have unit
+ tests that run without Electron (`packages/host-runtime/src/*.test.ts`).
+- The desktop's source-contract tests that pinned `host-process.ts` and
+ `agent-sidecar.ts` now read the package sources; the renderer-facing
+ status and diagnosis assertions still read the Electron adapters.
+- Local Electron main still runs its own prompt path through IPC. Moving the
+ desktop onto `RuntimeService` for local sessions is a later,
+ behavior-preserving step; it is not required for R2 and is not done here.
+- The headless resolver deliberately supports less than the desktop:
+ no prompt attachments, no plugin tools, no desktop MCP relay, no vendor
+ OAuth. Those return typed errors rather than degrading silently.
+
+## Alternatives considered
+
+- **Extract only the transports and re-implement the turn lifecycle in
+ `pi-host`.** Rejected: the lifecycle invariants are the hard part, and a
+ second copy would drift from the desktop's.
+- **Keep the modules in `apps/desktop/electron/main` and import them from
+ `pi-host`.** Rejected: `packages/*` must not depend on desktop
+ implementation code, and the modules would keep growing Electron imports.
+- **Put the runtime into `packages/agent-host`.** Rejected: the module is the
+ transport-free semantic core with no process or filesystem knowledge, and
+ the RACP server and integrations depend on it staying that way.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 3777f7f90..797c64526 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -308,4 +308,5 @@ Each ADR includes:
| 0279 | [Resumable subagent delegations](0279-resumable-subagent-delegations.md) | Accepted for implementation (amends ADR 0062; ADR 0089; issue #513) |
| 0280 | [Plugin-owned UI localizes from the host locale](0280-plugin-owned-ui-localizes-from-host-locale.md) | Accepted (amends ADR 0267; ADR 0159) |
| 0281 | [Host speech capability](0281-host-speech-capability.md) | Accepted for implementation (amends ADR 0257) |
+| 0282 | [Headless runtime boundary in `packages/host-runtime`](0282-headless-runtime-boundary.md) | Accepted for implementation (D445; ADR 0205 R2 prerequisite) |
| 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 545306715..f3e9f3d8e 100644
--- a/docs/spec/02-architecture/03-repo-structure.md
+++ b/docs/spec/02-architecture/03-repo-structure.md
@@ -36,6 +36,8 @@ PI-Desktop/
│ ├── shared/ # IPC/protocol contracts, error codes, changelog
│ ├── i18n/ # shipped UI catalogs plus locale helpers
│ ├── 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
│ ├── plugin-sdk/ # plugin author types and validators
│ └── plugin-devkit/ # pi-plugin CLI: scaffold, check, pack, publish
├── examples/
diff --git a/docs/spec/03-runtime/07-process-model.md b/docs/spec/03-runtime/07-process-model.md
index d3ae914f6..9066cbd50 100644
--- a/docs/spec/03-runtime/07-process-model.md
+++ b/docs/spec/03-runtime/07-process-model.md
@@ -123,7 +123,9 @@ start its local service. Windows 11 ARM64 systems run this x64 package through
the operating system's x64 emulation; native Windows ARM64 artifacts are not
currently published.
-Supervision parameters (implemented in Electron main):
+Supervision parameters (the transports, restart policy, and turn lifecycle are
+`packages/host-runtime`, ADR 0282; Electron main adapts them and owns the
+renderer-facing status):
- Child exit rejects all in-flight RPCs for that child immediately (no 130s timeout wait).
- An NDJSON request line over 64 MiB is drained and answered with `LIMIT_EXCEEDED`; it does not end the stdin reader (ADR 0216). Electron rejects the same size before writing stdin (ADR 0217).
diff --git a/docs/spec/06-delivery/07-remote-control-rollout.md b/docs/spec/06-delivery/07-remote-control-rollout.md
index 63e5d0ca5..6cb33ea59 100644
--- a/docs/spec/06-delivery/07-remote-control-rollout.md
+++ b/docs/spec/06-delivery/07-remote-control-rollout.md
@@ -402,7 +402,13 @@ Recorded on the `feat/remote-agent-host` branch, 2026-09-10:
graceful stop.
- R1 open: a runtime-level per-turn permission ceiling (a capped turn
currently fails closed in the bridge).
-- R2 and later: not started.
+- R2 started (2026-09-18, D445 / ADR 0282): `packages/host-runtime` holds the
+ Electron-independent runtime layer — the host-core and sidecar stdio
+ transports, the restart supervisor, `RuntimeService` (the module's
+ `RuntimePort` with the durable turn lifecycle), transcript persistence, a
+ headless launch resolver, and approved Plan/Goal dispatch — and Electron
+ main runs on it through thin adapters. The `pi-host` bundle, the RACP-WS
+ transport, 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 6c22ec812..8c4edf7d7 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -22,6 +22,7 @@ This log freezes previously open questions into concrete decisions.
| D010 | First release platform | **macOS arm64 only** | Focus acceptance and packaging |
| D373 | Remote Agent Control host boundary | *(amended by D374 and D375)* **Remote control (post-MVP) runs through a logical Agent Host that owns Sessions, Turns, event cursors, approvals, attachments, workspace policy, and crash recovery; a production Gateway owns identity, routing, rate limits, revocation, and audit, and the Agent Host connects outbound. The existing Electron IPC, `host.proxy`, and host-core stdio boundaries are never exposed.** | A remote surface needs its own boundary rather than a tunnel into local IPC or the host-core stdio contract (ADR 0205, E2E-221 through E2E-230) |
| D374 | Remote Agent Control v1 target amendments | **Amend D373 / ADR 0205: `RACP-WS` is the only normative v1 binding (`RACP-HTTP` is the browser profile, `RACP-GRPC` is reserved); typebox in `packages/shared` is the single contract source; the headless `packages/agent-host` module is the first deliverable and is shared by desktop IPC, local MCP, and RACP; cursors are `{ epoch, sequence }` with ephemeral deltas; the turn queue moves into the Host; host-core exposes `permissions.pending`; remote approvals carry the full local decision vocabulary under a default `ask` ceiling; browser clients use a cookie profile; the first deployment is single-tenant.** | Reviewing the D373 draft against the shipped desktop found the remote approval vocabulary narrower than the local contracts, pending requests held as connection state, per-token deltas exhausting the replay window, and more bindings than v1 can carry (ADR 0205) |
+| D445 | Headless runtime boundary | **Amend ADR 0205 rollout R2 prerequisites (ADR 0282): the Electron-independent runtime layer under the Agent Host module lives in `packages/host-runtime` — the host-core and sidecar stdio transports, the restart supervisor (process-model §4 policy), the durable turn lifecycle (`RuntimeService` as the module's `RuntimePort`: `session.beginTurn` → user row → prompt → `session.endTurn`, abort lock, stale-terminal guard, single-flight finalization), transcript persistence with the D299 checkpoint, a headless launch resolver over host-core's own registries, approved Plan/Goal dispatch (D189), and the host-core adapters for `SessionPort` / `QueueStore` / `permissions.pending`. Electron main keeps thin adapters (binary and bundle locations, `ELECTRON_RUN_AS_NODE`, redacted stderr, schema/glibc diagnoses, renderer status pushes) and its own local prompt path. `TurnStartRequest` gains an optional `userMessageId`. No IPC, sidecar, host-core, Plugin SDK, default, or persisted-data change.** | `pi-host` must run the same lifecycle invariants as the desktop without Electron; a second implementation of abort locks, stale terminal events, and queue release after durable settlement would drift from the one the desktop already fixed |
## 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 237bd1a97..9e9c56fbc 100644
--- a/docs/zh-CN/spec/02-architecture/03-repo-structure.md
+++ b/docs/zh-CN/spec/02-architecture/03-repo-structure.md
@@ -37,6 +37,8 @@ PI-Desktop/
│ ├── shared/ # IPC/协议契约、错误码、更新日志
│ ├── i18n/ # en 与 zh-CN 目录及 locale 辅助函数
│ ├── agent-runtime/ # pi sidecar 与运行时包装(打包进应用)
+│ ├── agent-host/ # 无头 Agent Host 模块:准入、队列、审批、事件日志
+│ ├── host-runtime/ # 与 Electron 无关的运行时:stdio 传输、监督器、回合生命周期
│ ├── plugin-sdk/ # 插件作者类型与校验器
│ └── plugin-devkit/ # pi-plugin CLI:scaffold、check、pack、publish
├── examples/
diff --git a/docs/zh-CN/spec/03-runtime/07-process-model.md b/docs/zh-CN/spec/03-runtime/07-process-model.md
index 80444a43d..7745a3531 100644
--- a/docs/zh-CN/spec/03-runtime/07-process-model.md
+++ b/docs/zh-CN/spec/03-runtime/07-process-model.md
@@ -97,7 +97,7 @@ Windows 安装包目标为 x64。Windows host-core 使用
系统通过操作系统的 x64 模拟运行该 x64 安装包;目前不发布原生 Windows ARM64
工件。
-监管参数(在Electron main中实现):
+监管参数(传输、重启策略与回合生命周期位于 `packages/host-runtime`,ADR 0282;Electron main 适配它们并负责面向渲染层的状态):
- 子进程退出立即拒绝该子进程的所有正在进行的 RPC(无 130 秒超时等待)。
- 超过 64 MiB 的 NDJSON 请求行以 `LIMIT_EXCEEDED` 应答,不结束 stdin 读取器(ADR 0216)。Electron 在写入 stdin 前拒绝同样大小的载荷(ADR 0217)。
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 198cc6764..2dc8a3d7c 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,7 @@ runbook 写明 feature flag、配对撤销路径、远端机器上的数据保
- R1 已交付:renderer 的内存 prompt 队列已退役;composer 经 `agent/queue/push` 推入,
镜像 `agent/event/queueChanged`,“立即发送”即 `turn/prioritize` 加优雅停止。
- R1 未完成:运行时级别的逐回合权限上限(当前被限制的回合在桥接层直接拒绝)。
-- R2 及之后:尚未开始。
+- 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 引导与桌面适配器尚未开始。
## 8. 修订记录
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index 5f8c145c6..f4e29596f 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -25,6 +25,7 @@
| D010 | 首个发布平台 | **仅限 macOS arm64** | 重点验收及包装 |
| D373 | 远程 Agent 控制的 Host 边界 | *(由 D374 与 D375 修订)* **远程控制(MVP 之后)经由一个逻辑 Agent Host 运行,它拥有 Sessions、Turns、事件游标、审批、附件、工作区策略与崩溃恢复;生产 Gateway 拥有身份、路由、限流、吊销与审计,Agent Host 向外连接。现有 Electron IPC、`host.proxy` 与 host-core stdio 边界永不暴露。** | 远程表面需要自己的边界,而不是通往本地 IPC 或 host-core stdio 契约的隧道(ADR 0205,E2E-221 至 E2E-230) |
| D374 | 远程 Agent 控制 v1 目标修订 | **修订 D373 / ADR 0205:`RACP-WS` 是 v1 唯一规范绑定(`RACP-HTTP` 为浏览器 profile,`RACP-GRPC` 保留);`packages/shared` 中的 typebox 是唯一契约来源;无头的 `packages/agent-host` 模块是首个交付物,桌面 IPC、本地 MCP 与 RACP 共同调用;游标为 `{ epoch, sequence }` 且增量为临时数据;回合队列移入 Host;host-core 暴露 `permissions.pending`;远程审批携带完整本地决策词汇并默认 `ask` 上限;浏览器客户端使用 cookie profile;首个部署为单租户。** | 对照已交付桌面审查 D373 草案发现远程审批词汇比本地契约窄、待处理请求被当作连接状态、逐 token 增量会耗尽重放窗口、绑定数量超过 v1 承载能力(ADR 0205) |
+| D445 | 无头运行时边界 | **修订 ADR 0205 里程碑 R2 的前置条件(ADR 0282):Agent Host 模块之下与 Electron 无关的运行时层放入 `packages/host-runtime` —— host-core 与 sidecar 的 stdio 传输、重启监督器(进程模型 §4 的策略)、持久回合生命周期(`RuntimeService` 作为模块的 `RuntimePort`:`session.beginTurn` → 用户行 → prompt → `session.endTurn`、中止锁、过期终态事件守卫、单飞终结)、带 D299 检查点的转录持久化、基于 host-core 自身注册表的无头启动解析器、已批准 Plan/Goal 的派发(D189),以及 `SessionPort` / `QueueStore` / `permissions.pending` 的 host-core 适配器。Electron main 只保留薄适配层(二进制与资源位置、`ELECTRON_RUN_AS_NODE`、脱敏 stderr、schema/glibc 诊断、渲染层状态推送)以及自己的本地 prompt 路径。`TurnStartRequest` 新增可选 `userMessageId`。不改 IPC、sidecar、host-core、插件 SDK、默认值或持久化数据。** | `pi-host` 必须在没有 Electron 的情况下运行与桌面相同的生命周期不变量;第二份中止锁、过期终态事件与持久落库后释放队列的实现会与桌面已修好的那份漂移 |
## B. 辅助实现默认值
diff --git a/packages/README.md b/packages/README.md
index 1627210fc..5307d4634 100644
--- a/packages/README.md
+++ b/packages/README.md
@@ -4,3 +4,5 @@
- `i18n` — English source catalog
- `plugin-sdk` — plugin author types/helpers
- `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)
diff --git a/packages/agent-host/src/ports.ts b/packages/agent-host/src/ports.ts
index 864a20c22..0bd4fe7db 100644
--- a/packages/agent-host/src/ports.ts
+++ b/packages/agent-host/src/ports.ts
@@ -35,6 +35,8 @@ export type TurnStartRequest = {
sessionId: string;
content: string;
sessionMessageId?: string;
+ /** Client-chosen id for the durable user row (D288); the runtime mints one otherwise. */
+ userMessageId?: string;
attachments?: AgentPromptAttachment[];
effectivePermissionMode: RacpPermissionMode;
idempotencyKey?: string;
diff --git a/packages/host-runtime/package.json b/packages/host-runtime/package.json
new file mode 100644
index 000000000..f7c2a3737
--- /dev/null
+++ b/packages/host-runtime/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@pi-desktop/host-runtime",
+ "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/agent-runtime": "workspace:*",
+ "@pi-desktop/shared": "workspace:*"
+ },
+ "devDependencies": {
+ "@types/node": "^24.13.3",
+ "typescript": "^5.9.3",
+ "vitest": "^4.1.10"
+ }
+}
diff --git a/packages/host-runtime/src/agent-sidecar.ts b/packages/host-runtime/src/agent-sidecar.ts
new file mode 100644
index 000000000..b89741ae8
--- /dev/null
+++ b/packages/host-runtime/src/agent-sidecar.ts
@@ -0,0 +1,647 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import { DEFAULT_RPC_TIMEOUT_MS, readNdjsonLines, rpcTimeoutMs } from "@pi-desktop/shared";
+import type { ProcessExitHandler, StderrHandler } from "./host-process.js";
+
+// stderr lines kept per sidecar so an unexpected exit can be reported with the
+// process's last words instead of a bare "agent sidecar exited".
+const SIDECAR_STDERR_TAIL_LINES = 40;
+
+export type SidecarNotificationHandler = (method: string, params: unknown) => void;
+
+/** Result shape the sidecar's tool executor expects from tools.execute. */
+export type LocalToolResult = {
+ ok: boolean;
+ content: unknown;
+ isError?: boolean;
+ errorCode?: string;
+};
+
+export type LocalToolHandler = (input: {
+ sessionId: string;
+ toolCallId: string;
+ args: unknown;
+}) => Promise<LocalToolResult>;
+
+export type ProjectInstructionResolver = (input: {
+ sessionId: string;
+ path: string;
+ /** Project root registered by the embedding host for this session. */
+ projectPath?: string;
+}) => Promise<unknown>;
+
+/**
+ * Resolve request auth for a vendor account. Answered by the embedding host
+ * against the signed-in pi-ai collection; the sidecar names a provider row,
+ * never a vendor or a credential, and gets back only a short-lived `ModelAuth`.
+ */
+export type VendorAuthResolver = (input: {
+ sessionId: string;
+ providerId: string;
+}) => Promise<unknown>;
+
+// The sidecar runs model-directed code paths; it must not be able to pull
+// secrets or mutate configuration through the parent proxy. Tight allowlist
+// of host methods the agent loop legitimately needs.
+//
+// `provider.resolveAuth` is answered by the embedding host itself (never
+// forwarded to host-core) and only for a provider row bound to that same
+// session, so it cannot reach a credential the session was not launched with.
+const HOST_PROXY_ALLOWED = new Set([
+ "tools.execute",
+ "tools.abort",
+ "tools.list",
+ "session.get",
+ "session.appendMessage",
+ "session.appendCompaction",
+ "session.replaceMessages",
+ "workspace.get",
+ "plans.enter",
+ "plans.submit",
+ "plans.pending",
+ "plans.abort",
+ "project.instructions.resolve",
+ "provider.resolveAuth",
+ "provider.resolveSubagentModel",
+ "app.health",
+ // Trusted extensions (D387): answered by the embedding host, plus the
+ // session methods the ExtensionAPI reaches (spec 16 §10.1).
+ "extensions.commands.publish",
+ "extensions.ui.request",
+ "extensions.diagnostics.publish",
+ "extensions.model.configure",
+ "session.rename",
+ "session.create",
+ "session.fork",
+ "session.queuePush",
+ "session.queuePrioritize",
+]);
+
+/** Host-side answers for the `extensions.*` proxy methods. */
+export type TrustedExtensionSidecarBridge = {
+ publishCommands: (params: Record<string, unknown>) => void;
+ publishDiagnostics: (params: Record<string, unknown>) => void;
+ requestUi: (params: Record<string, unknown>) => Promise<unknown>;
+ configureModel: (params: Record<string, unknown>) => Promise<unknown>;
+ /** `sendUserMessage`: the Host-owned queue drains it (D386); host-core alone would only store it. */
+ queuePush: (params: Record<string, unknown>) => Promise<unknown>;
+ queuePrioritize: (params: Record<string, unknown>) => Promise<unknown>;
+};
+
+/** The host-core transport as the sidecar proxy sees it. `HostProcess` satisfies it. */
+export interface SidecarHostLink {
+ call<T = unknown>(method: string, params?: unknown): Promise<T>;
+ onNotification(handler: (method: string, params: unknown) => void): () => void;
+ onExit(handler: ProcessExitHandler): () => void;
+}
+
+/**
+ * How to start the sidecar process. Electron runs its own executable as Node
+ * (`ELECTRON_RUN_AS_NODE=1`); the headless host runs a plain Node binary. The
+ * transport does not care which, so the choice is made by the caller.
+ */
+export type SidecarLaunch = {
+ command: string;
+ args: string[];
+ env?: NodeJS.ProcessEnv;
+ cwd?: string;
+};
+
+export type AgentSidecarOptions = {
+ launch: SidecarLaunch;
+ /** Receives raw stderr text as it arrives; the embedding host owns redaction and logging. */
+ onStderr: StderrHandler;
+};
+
+/**
+ * The Node pi agent sidecar over stdio NDJSON JSON-RPC. Besides plain calls it
+ * answers the sidecar's reverse `host.proxy` requests: an allowlisted subset is
+ * forwarded to host-core, and the rest is served by handlers the embedding
+ * host registers (local tools, project instructions, vendor auth, trusted
+ * extensions).
+ */
+export class AgentSidecar {
+ private child: ChildProcessWithoutNullStreams;
+ private pending = new Map<
+ string,
+ {
+ resolve: (v: any) => void;
+ reject: (e: Error) => void;
+ timer?: ReturnType<typeof setTimeout>;
+ }
+ >();
+ private handlers = new Set<SidecarNotificationHandler>();
+ private exitHandlers = new Set<ProcessExitHandler>();
+ private disposed = false;
+ private closed = false;
+ private exitNotified = false;
+ private stderrTail: string[] = [];
+ private host: SidecarHostLink | null = null;
+ private unsubscribeHost: (() => void) | null = null;
+ private unsubscribeHostExit: (() => void) | null = null;
+ private stdoutReader?: ReturnType<typeof readNdjsonLines>;
+ // Tools served by the embedding host itself (e.g. BrowserPreview drives the
+ // work panel's WebContentsView) — host-core never sees these.
+ private localTools = new Map<string, LocalToolHandler>();
+ private localToolTimers = new Set<ReturnType<typeof setTimeout>>();
+ private projectInstructionResolver: ProjectInstructionResolver | null = null;
+ // The sidecar may request a path, but it never chooses the project root.
+ // The embedding host registers this binding from the host-owned session
+ // record immediately before starting a runtime turn.
+ private projectInstructionRoots = new Map<string, string>();
+ private vendorAuthResolver: VendorAuthResolver | null = null;
+ private trustedExtensionBridge: TrustedExtensionSidecarBridge | null = null;
+ // Vendor-account rows this session was launched with. The sidecar can only
+ // ask for auth it is already using, and a session that never bound an OAuth
+ // row can ask for nothing at all.
+ private vendorAuthBindings = new Map<string, Set<string>>();
+
+ constructor(options: AgentSidecarOptions) {
+ const { launch, onStderr } = options;
+ this.child = spawn(launch.command, launch.args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: launch.env ?? process.env,
+ ...(launch.cwd ? { cwd: launch.cwd } : {}),
+ });
+
+ this.child.stderr.setEncoding("utf8");
+ this.child.stderr.on("data", (text: string) => {
+ if (!text) return;
+ this.recordStderr(text);
+ onStderr(text);
+ });
+
+ this.child.on("exit", (code, signal) => {
+ this.closeTransport(new Error("agent sidecar exited"));
+ this.notifyExit({ code, signal, intentional: this.disposed });
+ });
+ this.child.on("error", (error) => {
+ this.closeTransport(error instanceof Error ? error : new Error(String(error)));
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ });
+
+ this.stdoutReader = readNdjsonLines(this.child.stdout, (line) =>
+ void this.onLine(line),
+ );
+ }
+
+ private recordStderr(text: string) {
+ for (const line of text.split(/\r?\n/)) {
+ if (!line.trim()) continue;
+ this.stderrTail.push(line);
+ if (this.stderrTail.length > SIDECAR_STDERR_TAIL_LINES) {
+ this.stderrTail.shift();
+ }
+ }
+ }
+
+ private closeTransport(error: Error) {
+ if (this.closed) return;
+ this.closed = true;
+ this.unsubscribeHost?.();
+ this.unsubscribeHost = null;
+ this.unsubscribeHostExit?.();
+ this.unsubscribeHostExit = null;
+ this.host = null;
+ for (const [, p] of this.pending) {
+ if (p.timer) clearTimeout(p.timer);
+ p.reject(error);
+ }
+ this.pending.clear();
+ for (const timer of this.localToolTimers) clearTimeout(timer);
+ this.localToolTimers.clear();
+ this.handlers.clear();
+ this.stdoutReader?.close();
+ this.stdoutReader = undefined;
+ this.child.removeAllListeners("exit");
+ this.child.removeAllListeners("error");
+ this.child.stderr.removeAllListeners("data");
+ }
+
+ private notifyExit(info: {
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ intentional: boolean;
+ }) {
+ if (this.exitNotified) return;
+ this.exitNotified = true;
+ // Snapshot the sidecar's last stderr lines: the dying process emits no
+ // stdout, so they are the only context a crash report gets.
+ const stderrTail = this.stderrTail.slice();
+ for (const h of this.exitHandlers) h({ ...info, stderrTail });
+ this.exitHandlers.clear();
+ }
+
+ private writeToChild(payload: string): boolean {
+ if (this.closed || this.disposed) return false;
+ if (this.child.stdin.destroyed || !this.child.stdin.writable) {
+ const failure = new Error("agent sidecar stdin is unavailable");
+ this.closeTransport(failure);
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ return false;
+ }
+ try {
+ this.child.stdin.write(payload, (error) => {
+ if (error) {
+ this.closeTransport(error);
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ }
+ });
+ return true;
+ } catch (error) {
+ const failure = error instanceof Error ? error : new Error(String(error));
+ this.closeTransport(failure);
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ return false;
+ }
+ }
+
+ private async runLocalTool(
+ handler: LocalToolHandler,
+ input: Parameters<LocalToolHandler>[0],
+ ): Promise<LocalToolResult> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ handler(input),
+ new Promise<LocalToolResult>((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error("host-local tool timeout"));
+ }, DEFAULT_RPC_TIMEOUT_MS);
+ this.localToolTimers.add(timer);
+ }),
+ ]);
+ } finally {
+ if (timer) {
+ clearTimeout(timer);
+ this.localToolTimers.delete(timer);
+ }
+ }
+ }
+
+ onExit(handler: ProcessExitHandler): () => void {
+ if (this.closed) return () => undefined;
+ this.exitHandlers.add(handler);
+ return () => this.exitHandlers.delete(handler);
+ }
+
+ /** Register a tool the sidecar can call that the embedding host handles locally. */
+ setLocalTool(name: string, handler: LocalToolHandler): void {
+ this.localTools.set(name, handler);
+ }
+
+ setProjectInstructionResolver(resolver: ProjectInstructionResolver): void {
+ this.projectInstructionResolver = resolver;
+ }
+
+ setProjectInstructionRoot(sessionId: string, projectPath?: string): void {
+ const id = sessionId.trim();
+ if (!id) return;
+ const root = projectPath?.trim();
+ if (root) this.projectInstructionRoots.set(id, root);
+ else this.projectInstructionRoots.delete(id);
+ }
+
+ clearProjectInstructionRoot(sessionId: string): void {
+ this.projectInstructionRoots.delete(sessionId.trim());
+ }
+
+ setVendorAuthResolver(resolver: VendorAuthResolver): void {
+ this.vendorAuthResolver = resolver;
+ }
+
+ setTrustedExtensionBridge(bridge: TrustedExtensionSidecarBridge): void {
+ this.trustedExtensionBridge = bridge;
+ }
+
+ /**
+ * Bind the vendor-account rows a turn may sign requests with. Replaces the
+ * session's previous set, so a row dropped from the launch payload — a model
+ * switch or account removal — stops being resolvable on the next turn.
+ */
+ setVendorAuthBindings(
+ sessionId: string,
+ bindings: ReadonlyArray<{ providerId: string }>,
+ ): void {
+ const id = sessionId.trim();
+ if (!id) return;
+ const providerIds = new Set<string>();
+ for (const binding of bindings) {
+ const providerId = binding.providerId?.trim();
+ if (providerId) providerIds.add(providerId);
+ }
+ if (providerIds.size > 0) this.vendorAuthBindings.set(id, providerIds);
+ else this.vendorAuthBindings.delete(id);
+ }
+
+ clearVendorAuthBindings(sessionId: string): void {
+ this.vendorAuthBindings.delete(sessionId.trim());
+ }
+
+ setHost(host: SidecarHostLink) {
+ if (this.closed) return;
+ this.host = host;
+ this.unsubscribeHost?.();
+ this.unsubscribeHostExit?.();
+ this.unsubscribeHost = host.onNotification((method, params) => {
+ // Forward host notifications to sidecar. permissions.request stays out:
+ // the embedding host already delivers it to its own UI, and bouncing it
+ // through the sidecar delivered the dialog twice with the full args
+ // payload re-serialized across two extra stdio hops.
+ if (method === "permissions.request") return;
+ const payload =
+ JSON.stringify({
+ jsonrpc: "2.0",
+ method: "host.notification",
+ params: { method, params },
+ }) + "\n";
+ this.writeToChild(payload);
+ });
+ this.unsubscribeHostExit = host.onExit(() => {
+ this.unsubscribeHost?.();
+ this.unsubscribeHost = null;
+ this.unsubscribeHostExit = null;
+ this.host = null;
+ });
+ }
+
+ /**
+ * Answer one `provider.resolveAuth` request. Refuses anything the session was
+ * not launched with: the provider row has to be in this session's bindings,
+ * which the embedding host rewrites on every turn.
+ */
+ private async resolveVendorAuth(
+ params: Record<string, unknown>,
+ ): Promise<unknown> {
+ if (!this.vendorAuthResolver) {
+ throw new Error("vendor account auth resolver unavailable");
+ }
+ const sessionId = String(params.sessionId ?? "").trim();
+ const providerId = String(params.providerId ?? "").trim();
+ const bound = this.vendorAuthBindings.get(sessionId)?.has(providerId);
+ if (!bound) {
+ throw Object.assign(
+ new Error("provider is not bound to this session"),
+ { code: -32000, data: { errorCode: "PROVIDER_NOT_BOUND" } },
+ );
+ }
+ return this.vendorAuthResolver({ sessionId, providerId });
+ }
+
+ /**
+ * On-demand subagent model resolution. The runtime calls this when the
+ * parent agent passes a `model` override on Task that was not statically
+ * pinned by any definition. The embedding host resolves it against the
+ * user's configured providers and the model catalog, respecting the
+ * `availableForSubagents` gate on each model binding.
+ */
+ private subagentModelResolver:
+ | ((key: string) => Promise<unknown>)
+ | null = null;
+
+ setSubagentModelResolver(
+ resolver: (key: string) => Promise<unknown>,
+ ): void {
+ this.subagentModelResolver = resolver;
+ }
+
+ private async resolveSubagentModel(
+ params: Record<string, unknown>,
+ ): Promise<unknown> {
+ if (!this.subagentModelResolver) {
+ throw new Error("subagent model resolver unavailable");
+ }
+ const key = String(params.key ?? "").trim();
+ if (!key || !key.includes("/")) {
+ throw Object.assign(
+ new Error("invalid model key; expected 'provider/model'"),
+ { code: -32602 },
+ );
+ }
+ return this.subagentModelResolver(key);
+ }
+
+ private async onLine(line: string) {
+ if (!line.trim()) return;
+ let msg: any;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ console.warn(
+ `[RPC] Invalid agent-sidecar NDJSON frame (${Buffer.byteLength(line, "utf8")} bytes)`,
+ );
+ return;
+ }
+
+ // Reverse RPC from sidecar → host proxy
+ if (msg.method === "host.proxy" && msg.id !== undefined) {
+ try {
+ const method = String(msg.params?.method || "");
+ if (!HOST_PROXY_ALLOWED.has(method)) {
+ throw Object.assign(
+ new Error(`host method not allowed from sidecar: ${method}`),
+ { code: -32601 },
+ );
+ }
+ const params = (msg.params?.params ?? {}) as Record<string, unknown>;
+ const requestedToolName = String(params.toolName ?? "");
+ const planLocalTool =
+ requestedToolName === "Skill" ||
+ requestedToolName === "PluginCheck" ||
+ requestedToolName === "PluginScaffold" ||
+ requestedToolName === "PluginPack" ||
+ requestedToolName.startsWith("plugin_");
+ if (
+ method === "tools.execute" &&
+ params.mode === "plan" &&
+ planLocalTool &&
+ requestedToolName !== "BrowserPreview"
+ ) {
+ throw Object.assign(
+ new Error(`${requestedToolName} is unavailable in Plan mode`),
+ { code: -32000, data: { errorCode: "TOOL_DISABLED_IN_PLAN" } },
+ );
+ }
+ if (method === "project.instructions.resolve") {
+ if (!this.projectInstructionResolver) {
+ throw new Error("project instruction resolver unavailable");
+ }
+ const sessionId = String(params.sessionId ?? "");
+ const result = await this.projectInstructionResolver({
+ sessionId,
+ path: String(params.path ?? ""),
+ projectPath: this.projectInstructionRoots.get(sessionId),
+ });
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ return;
+ }
+ if (method === "provider.resolveAuth") {
+ const result = await this.resolveVendorAuth(params);
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ return;
+ }
+ if (method === "provider.resolveSubagentModel") {
+ const result = await this.resolveSubagentModel(params);
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ return;
+ }
+ if (method.startsWith("extensions.") || method === "session.queuePush" || method === "session.queuePrioritize") {
+ const bridge = this.trustedExtensionBridge;
+ if (!bridge) throw new Error("trusted extension bridge unavailable");
+ let result: unknown = { ok: true };
+ if (method === "extensions.commands.publish") bridge.publishCommands(params);
+ else if (method === "extensions.diagnostics.publish") bridge.publishDiagnostics(params);
+ else if (method === "extensions.model.configure") result = await bridge.configureModel(params);
+ else if (method === "session.queuePush") result = await bridge.queuePush(params);
+ else if (method === "session.queuePrioritize") result = await bridge.queuePrioritize(params);
+ else result = await bridge.requestUi(params);
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ return;
+ }
+ // Host-local tools short-circuit before host-core (which doesn't
+ // know them); everything else proxies through unchanged.
+ const localTool =
+ method === "tools.execute"
+ ? this.localTools.get(requestedToolName)
+ : undefined;
+ if (localTool) {
+ const toolName = requestedToolName;
+ // Local tools can bypass host-core's permission boundary. Plan mode
+ // therefore permits only the read-only BrowserPreview bridge; every
+ // other host-local tool fails closed even if a stale runtime asks for
+ // it directly.
+ const result =
+ params.mode === "plan" && toolName !== "BrowserPreview"
+ ? {
+ ok: false,
+ isError: true,
+ errorCode: "TOOL_DISABLED_IN_PLAN",
+ content: `${toolName} is unavailable in Plan mode.`,
+ }
+ : await this.runLocalTool(localTool, {
+ sessionId: String(params.sessionId ?? ""),
+ toolCallId: String(params.toolCallId ?? ""),
+ args: params.args,
+ });
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ return;
+ }
+ if (!this.host) throw new Error("host unavailable");
+ const result = await this.host.call(method, params);
+ this.writeToChild(
+ JSON.stringify({ jsonrpc: "2.0", id: msg.id, result }) + "\n",
+ );
+ } catch (e: any) {
+ this.writeToChild(
+ JSON.stringify({
+ jsonrpc: "2.0",
+ id: msg.id,
+ error: {
+ code: e?.code ?? -32000,
+ message: e instanceof Error ? e.message : String(e),
+ data: e?.data,
+ },
+ }) + "\n",
+ );
+ }
+ return;
+ }
+
+ if (msg.id !== undefined && msg.id !== null && msg.method === undefined) {
+ const pending = this.pending.get(String(msg.id));
+ if (pending) {
+ this.pending.delete(String(msg.id));
+ if (pending.timer) clearTimeout(pending.timer);
+ if (msg.error) {
+ const err = new Error(msg.error.message) as Error & {
+ code?: number;
+ data?: unknown;
+ };
+ err.code = msg.error.code;
+ err.data = msg.error.data;
+ pending.reject(err);
+ } else {
+ pending.resolve(msg.result);
+ }
+ }
+ return;
+ }
+
+ if (msg.method) {
+ for (const h of this.handlers) h(msg.method, msg.params);
+ }
+ }
+
+ onNotification(handler: SidecarNotificationHandler): () => void {
+ if (this.closed) return () => undefined;
+ this.handlers.add(handler);
+ return () => this.handlers.delete(handler);
+ }
+
+ async call<T = unknown>(method: string, params: unknown = {}): Promise<T> {
+ if (this.closed) throw new Error("agent sidecar is unavailable");
+ const id = randomUUID();
+ const timeoutMs = rpcTimeoutMs(method, params);
+ const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
+ return new Promise<T>((resolve, reject) => {
+ this.pending.set(id, {
+ resolve: resolve as (v: any) => void,
+ reject,
+ });
+ const settle = (settleWith: (pending: {
+ resolve: (v: any) => void;
+ reject: (e: Error) => void;
+ timer?: ReturnType<typeof setTimeout>;
+ }) => void) => {
+ const pending = this.pending.get(id);
+ if (!pending) return;
+ this.pending.delete(id);
+ if (pending.timer) clearTimeout(pending.timer);
+ settleWith(pending);
+ };
+ if (!this.writeToChild(payload)) {
+ settle((pending) => pending.reject(new Error("agent sidecar stdin is unavailable")));
+ }
+ if (timeoutMs !== undefined) {
+ const timer = setTimeout(() => {
+ settle((pending) => pending.reject(new Error(`sidecar RPC timeout: ${method}`)));
+ }, timeoutMs);
+ const pending = this.pending.get(id);
+ if (pending) pending.timer = timer;
+ }
+ });
+ }
+
+ async dispose(): Promise<void> {
+ this.disposed = true;
+ this.projectInstructionRoots.clear();
+ this.vendorAuthBindings.clear();
+ this.closeTransport(new Error("agent sidecar disposed"));
+ this.exitHandlers.clear();
+ if (this.child.exitCode !== null || this.child.signalCode !== null) return;
+ // Wait for the process to actually leave so quit's settle step is real
+ // rather than returning while the sidecar is still tearing down.
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, SIDECAR_DISPOSE_GRACE_MS);
+ timer.unref?.();
+ this.child.once("exit", () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ this.child.kill();
+ });
+ }
+}
+
+/** Upper bound on how long `dispose()` waits for the killed sidecar to exit. */
+const SIDECAR_DISPOSE_GRACE_MS = 2_000;
diff --git a/packages/host-runtime/src/host-ports.test.ts b/packages/host-runtime/src/host-ports.test.ts
new file mode 100644
index 000000000..7ef2d5c84
--- /dev/null
+++ b/packages/host-runtime/src/host-ports.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+
+import { createHostQueueStore, createHostSessionPort, fromHostQueueEntry, toSessionSummary } from "./host-ports.js";
+
+describe("host ports", () => {
+ it("maps a host session record to the Agent Host summary without leaking the absolute path", () => {
+ const summary = toSessionSummary({
+ id: "s1",
+ title: "Fix build",
+ projectId: "proj",
+ projectPath: "/home/user/work/pi",
+ mode: "plan",
+ permissionMode: "accept-edits",
+ planningState: "awaiting_approval",
+ createdAt: "2026-09-18T00:00:00.000Z",
+ });
+ expect(summary).toEqual({
+ id: "s1",
+ title: "Fix build",
+ projectId: "proj",
+ workspaceLabel: "pi",
+ mode: "plan",
+ permissionMode: "accept-edits",
+ planningState: "awaiting_approval",
+ createdAt: "2026-09-18T00:00:00.000Z",
+ updatedAt: "2026-09-18T00:00:00.000Z",
+ });
+ expect(toSessionSummary({ id: "x", mode: "weird", permissionMode: "yolo", planningState: "?" })).toMatchObject({
+ mode: "agent",
+ permissionMode: "ask",
+ planningState: "inactive",
+ });
+ });
+
+ it("pages history backwards from an item id", async () => {
+ const messages = ["m1", "m2", "m3", "m4"].map((id) => ({
+ id,
+ role: "assistant" as const,
+ content: id,
+ createdAt: "2026-09-18T00:00:00.000Z",
+ status: "complete" as const,
+ }));
+ const port = createHostSessionPort(() => ({
+ async call<T>() {
+ return { session: { id: "s1", messages } } as T;
+ },
+ }));
+ const page = await port.history("s1", { limit: 2, beforeItemId: "m4" });
+ expect(page.items.map((item) => item.id)).toEqual(["m2", "m3"]);
+ expect(page.hasMore).toBe(true);
+ const tail = await port.history("s1", { limit: 10 });
+ expect(tail.items.map((item) => item.id)).toEqual(["m1", "m2", "m3", "m4"]);
+ expect(tail.hasMore).toBe(false);
+ expect(await createHostSessionPort(() => null).get("s1")).toBeNull();
+ });
+
+ it("round-trips queue records through the host-core RPC shape", async () => {
+ const calls: Array<{ method: string; params: Record<string, unknown> }> = [];
+ const store = createHostQueueStore(() => ({
+ async call<T>(method: string, params: Record<string, unknown> = {}) {
+ calls.push({ method, params });
+ if (method === "session.queueList") {
+ return {
+ entries: [
+ {
+ id: "q1",
+ sessionId: "s1",
+ principal: "phone",
+ inputHash: "h",
+ content: "later",
+ permissionMode: "auto",
+ position: 1,
+ priority: 2,
+ createdAt: "2026-09-18T00:00:00.000Z",
+ },
+ ],
+ } as T;
+ }
+ if (method === "session.queueRemove") return { removed: true } as T;
+ if (method === "session.queueReorder") return { moved: false } as T;
+ return {} as T;
+ },
+ }));
+ const [record] = await store.listAll();
+ expect(record).toMatchObject({ id: "q1", principalSubject: "phone", effectivePermissionMode: "auto", priority: 2 });
+ expect(record?.createdAt).toBe(Date.parse("2026-09-18T00:00:00.000Z"));
+ await store.push({ ...record!, attachments: [{ path: "/x", name: "x", kind: "file" }] });
+ expect(calls.at(-1)?.params).toMatchObject({ id: "q1", principal: "phone", permissionMode: "auto" });
+ expect(await store.remove("q1")).toBe(true);
+ expect(await store.reorder!("q1", "up")).toBe(false);
+ expect(fromHostQueueEntry({ id: "q", sessionId: "s", principal: "p", inputHash: "h", content: "c", permissionMode: "nope", position: 1, createdAt: "bad" })).toMatchObject({
+ effectivePermissionMode: "ask",
+ createdAt: 0,
+ });
+ });
+
+ it("fails closed when the host is gone", async () => {
+ const store = createHostQueueStore(() => null);
+ expect(await store.listAll()).toEqual([]);
+ await expect(store.remove("q1")).rejects.toMatchObject({ code: "AGENT_UNAVAILABLE" });
+ });
+});
diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.ts
new file mode 100644
index 000000000..8390846fd
--- /dev/null
+++ b/packages/host-runtime/src/host-ports.ts
@@ -0,0 +1,182 @@
+import { basename } from "node:path";
+
+import type {
+ PendingToolRequest,
+ QueueStore,
+ QueuedTurnRecord,
+ SessionPort,
+ SessionSummary,
+} from "@pi-desktop/agent-host";
+import { RacpError } from "@pi-desktop/agent-host";
+import type { RacpItemSummary, RacpPermissionMode, UiMessage } from "@pi-desktop/shared";
+
+/** Rust host-core over stdio JSON-RPC, as the ports below need it. */
+export type HostRpc = {
+ call<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
+};
+
+export type HostSessionRecord = {
+ id: string;
+ title?: string;
+ projectId?: string;
+ projectPath?: string;
+ mode?: string;
+ permissionMode?: string;
+ planningState?: string;
+ createdAt?: string;
+ updatedAt?: string;
+ messages?: UiMessage[];
+};
+
+export function requireHostRpc(getHost: () => HostRpc | null): HostRpc {
+ const host = getHost();
+ if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host is not running", { retriable: true });
+ return host;
+}
+
+export function toSessionSummary(record: HostSessionRecord): SessionSummary {
+ const mode = record.mode === "plan" || record.mode === "goal" ? record.mode : "agent";
+ const permissionMode: RacpPermissionMode =
+ record.permissionMode === "accept-edits" || record.permissionMode === "auto" ? record.permissionMode : "ask";
+ const planningState =
+ record.planningState === "planning" || record.planningState === "awaiting_approval"
+ ? record.planningState
+ : "inactive";
+ return {
+ id: record.id,
+ title: record.title ?? "",
+ ...(record.projectId ? { projectId: record.projectId } : {}),
+ ...(record.projectPath ? { workspaceLabel: basename(record.projectPath) } : {}),
+ mode,
+ permissionMode,
+ planningState,
+ createdAt: record.createdAt ?? new Date(0).toISOString(),
+ updatedAt: record.updatedAt ?? record.createdAt ?? new Date(0).toISOString(),
+ };
+}
+
+export function toRacpItem(message: UiMessage): RacpItemSummary {
+ const turnId = (message as { turnId?: string }).turnId ?? "";
+ return {
+ id: message.id,
+ turnId,
+ itemType: "message",
+ status: message.status === "streaming" ? "streaming" : "completed",
+ createdAt: message.createdAt,
+ ...(message.parentToolCallId ? { parentToolCallId: message.parentToolCallId } : {}),
+ ...(message.agentName ? { agentName: message.agentName } : {}),
+ content: message,
+ };
+}
+
+/** Session metadata and transcript pages straight from host `session.get`. */
+export function createHostSessionPort(getHost: () => HostRpc | null): SessionPort {
+ async function fetchSession(sessionId: string): Promise<HostSessionRecord | null> {
+ const host = getHost();
+ if (!host) return null;
+ const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId });
+ return result.session ?? null;
+ }
+ return {
+ async get(sessionId) {
+ const record = await fetchSession(sessionId);
+ return record ? toSessionSummary(record) : null;
+ },
+ async history(sessionId, { limit, beforeItemId }) {
+ const record = await fetchSession(sessionId);
+ const messages = record?.messages ?? [];
+ const end = beforeItemId ? messages.findIndex((message) => message.id === beforeItemId) : messages.length;
+ const cut = end === -1 ? messages.length : end;
+ const start = Math.max(0, cut - limit);
+ return {
+ items: messages.slice(start, cut).map(toRacpItem),
+ hasMore: start > 0,
+ };
+ },
+ };
+}
+
+export type HostQueueEntry = {
+ id: string;
+ sessionId: string;
+ principal: string;
+ idempotencyKey?: string;
+ inputHash: string;
+ content: string;
+ sessionMessageId?: string;
+ attachments?: unknown;
+ permissionMode: string;
+ position: number;
+ priority?: number;
+ createdAt: string;
+};
+
+export function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {
+ const permissionMode: RacpPermissionMode =
+ entry.permissionMode === "accept-edits" || entry.permissionMode === "auto" ? entry.permissionMode : "ask";
+ return {
+ id: entry.id,
+ sessionId: entry.sessionId,
+ principalSubject: entry.principal,
+ content: entry.content,
+ ...(entry.sessionMessageId ? { sessionMessageId: entry.sessionMessageId } : {}),
+ ...(Array.isArray(entry.attachments) ? { attachments: entry.attachments as QueuedTurnRecord["attachments"] } : {}),
+ effectivePermissionMode: permissionMode,
+ ...(entry.idempotencyKey ? { idempotencyKey: entry.idempotencyKey } : {}),
+ inputHash: entry.inputHash,
+ ...(entry.priority !== undefined ? { priority: entry.priority } : {}),
+ createdAt: Date.parse(entry.createdAt) || 0,
+ };
+}
+
+/** The Host-owned turn queue persisted by host-core (schema v15, ADR 0213). */
+export function createHostQueueStore(getHost: () => HostRpc | null): QueueStore {
+ return {
+ async listAll() {
+ const host = getHost();
+ if (!host) return [];
+ const result = await host.call<{ entries?: HostQueueEntry[] }>("session.queueList", {});
+ return (result.entries ?? []).map(fromHostQueueEntry);
+ },
+ async push(record) {
+ await requireHostRpc(getHost).call("session.queuePush", {
+ id: record.id,
+ sessionId: record.sessionId,
+ principal: record.principalSubject,
+ ...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),
+ inputHash: record.inputHash,
+ content: record.content,
+ ...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),
+ ...(record.attachments ? { attachments: record.attachments } : {}),
+ permissionMode: record.effectivePermissionMode,
+ });
+ },
+ async remove(id) {
+ const result = await requireHostRpc(getHost).call<{ removed?: boolean }>("session.queueRemove", { id });
+ return result.removed === true;
+ },
+ async prioritize(id) {
+ await requireHostRpc(getHost).call("session.queuePrioritize", { id });
+ },
+ async reorder(id, direction) {
+ const result = await requireHostRpc(getHost).call<{ moved?: boolean }>("session.queueReorder", {
+ id,
+ direction,
+ });
+ return result.moved === true;
+ },
+ };
+}
+
+/** Open tool requests as Host state (`permissions.pending`). */
+export async function listPendingToolRequests(
+ getHost: () => HostRpc | null,
+ sessionId?: string,
+): Promise<PendingToolRequest[]> {
+ const host = getHost();
+ if (!host) return [];
+ const result = await host.call<{ requests?: PendingToolRequest[] }>("permissions.pending", {
+ ...(sessionId ? { sessionId } : {}),
+ });
+ return result.requests ?? [];
+}
diff --git a/packages/host-runtime/src/host-process.ts b/packages/host-runtime/src/host-process.ts
new file mode 100644
index 000000000..8729e526b
--- /dev/null
+++ b/packages/host-runtime/src/host-process.ts
@@ -0,0 +1,387 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import {
+ ErrorCodes,
+ MAX_HOST_STDIN_LINE_BYTES,
+ PROTOCOL_VERSION,
+ readNdjsonLines,
+ rpcTimeoutMs,
+ stripProxyEnv,
+} from "@pi-desktop/shared";
+
+const HOST_DISPOSE_GRACE_MS = 3_000;
+const HOST_FORCE_KILL_GRACE_MS = 1_000;
+const HOST_OVERLOAD_RETRY_DELAYS_MS = [50, 100, 200, 400] as const;
+
+export type HostNotificationHandler = (method: string, params: unknown) => void;
+export type ProcessExitHandler = (info: {
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ intentional: boolean;
+ /** Last child stderr lines before exit; only the agent sidecar fills it. */
+ stderrTail?: string[];
+}) => void;
+export type StderrHandler = (text: string) => void;
+
+/** A transport failure the embedding host recognised, e.g. a schema refusal. */
+export type DiagnosedHostFailure = Error & { errorCode: string };
+
+export type HostProcessOptions = {
+ /** Absolute path of the `pi-desktop-host-core` binary to spawn. */
+ binaryPath: string;
+ /** Data directory handed to host-core as `PI_DESKTOP_DATA_DIR`. */
+ dataDir: string;
+ /**
+ * Extra environment for the child. The inherited environment is copied with
+ * proxy variables stripped first, so host-core never sees proxy credentials
+ * (D340); entries here are applied on top.
+ */
+ env?: Record<string, string | undefined>;
+ /** Receives raw stderr text as it arrives; the embedding host owns redaction and logging. */
+ onStderr: StderrHandler;
+ /**
+ * Classify a gone transport from the child's last stderr lines. Returns a
+ * typed error when the failure is one the embedding host names (a data
+ * directory newer than the build, an unsupported glibc), otherwise `null`
+ * and the generic `HOST_UNAVAILABLE` error is used.
+ */
+ diagnoseFailure?: (context: { lastStderr: string; message: string }) => DiagnosedHostFailure | null;
+};
+
+function isHostOverloaded(error: unknown): boolean {
+ const candidate = error as {
+ errorCode?: unknown;
+ data?: { errorCode?: unknown };
+ } | null;
+ return (
+ candidate?.errorCode === ErrorCodes.HOST_OVERLOADED ||
+ candidate?.data?.errorCode === ErrorCodes.HOST_OVERLOADED
+ );
+}
+
+/**
+ * The Rust host-core child over stdio NDJSON JSON-RPC. This class knows how to
+ * spawn, call, observe, and dispose the process; it does not know where the
+ * binary lives or which host embeds it, so Electron Main and the headless
+ * `pi-host` drive the same transport.
+ */
+export class HostProcess {
+ private child: ChildProcessWithoutNullStreams;
+ private pending = new Map<
+ string,
+ {
+ resolve: (v: any) => void;
+ reject: (e: Error) => void;
+ timer?: ReturnType<typeof setTimeout>;
+ }
+ >();
+ private handlers = new Set<HostNotificationHandler>();
+ private exitHandlers = new Set<ProcessExitHandler>();
+ private disposed = false;
+ private available = true;
+ private closed = false;
+ private exitNotified = false;
+ private exitObserved = false;
+ private exitPromise: Promise<void>;
+ private resolveExit!: () => void;
+ private disposePromise?: Promise<void>;
+ private stdoutReader?: ReturnType<typeof readNdjsonLines>;
+ private lastStderr = "";
+ private readonly diagnoseFailure?: HostProcessOptions["diagnoseFailure"];
+ readonly binaryPath: string;
+ readonly generation = randomUUID();
+
+ constructor(options: HostProcessOptions) {
+ this.exitPromise = new Promise<void>((resolve) => {
+ this.resolveExit = resolve;
+ });
+ this.binaryPath = options.binaryPath;
+ this.diagnoseFailure = options.diagnoseFailure;
+ const onStderr = options.onStderr;
+ this.child = spawn(this.binaryPath, [], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...stripProxyEnv(process.env),
+ PI_DESKTOP_DATA_DIR: options.dataDir,
+ ...(options.env ?? {}),
+ },
+ });
+
+ this.child.stderr.setEncoding("utf8");
+ this.child.stderr.on("data", (text: string) => {
+ if (!text) return;
+ this.lastStderr = `${this.lastStderr}${text}`.slice(-4_000);
+ onStderr(text);
+ });
+
+ this.child.on("exit", (code, signal) => {
+ this.available = false;
+ this.closeTransport(this.unavailableError("host-core exited"));
+ this.exitObserved = true;
+ this.resolveExit();
+ this.notifyExit({ code, signal, intentional: this.disposed });
+ this.cleanupProcessListeners();
+ });
+ this.child.on("error", (error) => {
+ this.available = false;
+ const failure = this.unavailableError(
+ `host-core process error: ${error.message}`,
+ );
+ this.closeTransport(failure);
+ // A spawn failure never produces an `exit` event, so without settling the
+ // exit promise here `dispose()` would wait the full grace period, send a
+ // SIGKILL to a process that never started, and wait again.
+ if (this.child.pid === undefined || this.child.exitCode !== null) {
+ this.exitObserved = true;
+ this.resolveExit();
+ }
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ if (this.exitObserved) this.cleanupProcessListeners();
+ });
+
+ this.stdoutReader = readNdjsonLines(this.child.stdout, (line) =>
+ this.onLine(line),
+ );
+ }
+
+ private closeTransport(error: Error) {
+ if (this.closed) return;
+ this.available = false;
+ this.closed = true;
+ for (const [, p] of this.pending) {
+ if (p.timer) clearTimeout(p.timer);
+ p.reject(error);
+ }
+ this.pending.clear();
+ this.handlers.clear();
+ this.stdoutReader?.close();
+ this.stdoutReader = undefined;
+ }
+
+ private cleanupProcessListeners() {
+ this.child.removeAllListeners("exit");
+ this.child.removeAllListeners("error");
+ this.child.stderr.removeAllListeners("data");
+ }
+
+ private waitForExit(timeoutMs: number): Promise<boolean> {
+ if (this.exitObserved) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ let settled = false;
+ const finish = (observed: boolean) => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ resolve(observed);
+ };
+ const timer = setTimeout(() => finish(false), timeoutMs);
+ timer.unref?.();
+ this.exitPromise.then(() => finish(true));
+ });
+ }
+
+ private notifyExit(info: {
+ code: number | null;
+ signal: NodeJS.Signals | null;
+ intentional: boolean;
+ }) {
+ if (this.exitNotified) return;
+ this.exitNotified = true;
+ for (const h of this.exitHandlers) h(info);
+ this.exitHandlers.clear();
+ }
+
+ /**
+ * Every rejection that only means "the transport is gone" is built here, so a
+ * caller can tell routine teardown from a real failure by the error code
+ * rather than by matching message text. The embedding host may recognise the
+ * failure from the last stderr lines and return a more specific typed error.
+ */
+ private unavailableError(message: string): Error & { errorCode: string } {
+ const diagnosed = this.diagnoseFailure?.({ lastStderr: this.lastStderr, message });
+ if (diagnosed) return diagnosed;
+ return Object.assign(new Error(message), {
+ errorCode: ErrorCodes.HOST_UNAVAILABLE,
+ });
+ }
+
+ isAvailable(): boolean {
+ return (
+ this.available &&
+ !this.closed &&
+ this.child.exitCode === null &&
+ !this.child.killed
+ );
+ }
+
+ onExit(handler: ProcessExitHandler): () => void {
+ if (this.closed) return () => undefined;
+ this.exitHandlers.add(handler);
+ return () => this.exitHandlers.delete(handler);
+ }
+
+ private onLine(line: string) {
+ if (!line.trim()) return;
+ let msg: any;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ console.warn(
+ `[RPC] Invalid host-process NDJSON frame (${Buffer.byteLength(line, "utf8")} bytes)`,
+ );
+ return;
+ }
+ if (msg.id !== undefined && msg.id !== null) {
+ const pending = this.pending.get(String(msg.id));
+ if (pending) {
+ this.pending.delete(String(msg.id));
+ if (pending.timer) clearTimeout(pending.timer);
+ if (msg.error) {
+ const err = new Error(msg.error.message) as Error & {
+ code?: number;
+ data?: unknown;
+ errorCode?: string;
+ };
+ err.code = msg.error.code;
+ err.data = msg.error.data;
+ const errorCode =
+ msg.error.data && typeof msg.error.data.errorCode === "string"
+ ? msg.error.data.errorCode
+ : undefined;
+ if (errorCode) err.errorCode = errorCode;
+ pending.reject(err);
+ } else {
+ pending.resolve(msg.result);
+ }
+ }
+ return;
+ }
+ if (msg.method) {
+ for (const h of this.handlers) h(msg.method, msg.params);
+ }
+ }
+
+ onNotification(handler: HostNotificationHandler): () => void {
+ if (this.closed) return () => undefined;
+ this.handlers.add(handler);
+ return () => this.handlers.delete(handler);
+ }
+
+ async call<T = unknown>(
+ method: string,
+ params: unknown = {},
+ timeoutOverrideMs?: number,
+ ): Promise<T> {
+ for (const delayMs of [0, ...HOST_OVERLOAD_RETRY_DELAYS_MS]) {
+ if (delayMs > 0) {
+ await new Promise<void>((resolve) => setTimeout(resolve, delayMs));
+ }
+ try {
+ return await this.callOnce<T>(method, params, timeoutOverrideMs);
+ } catch (error) {
+ if (
+ !isHostOverloaded(error) ||
+ delayMs === HOST_OVERLOAD_RETRY_DELAYS_MS.at(-1)
+ ) {
+ throw error;
+ }
+ }
+ }
+ throw new Error(`host RPC retry exhausted: ${method}`);
+ }
+
+ private async callOnce<T = unknown>(
+ method: string,
+ params: unknown,
+ timeoutOverrideMs?: number,
+ ): Promise<T> {
+ if (this.closed) throw this.unavailableError("host-core is unavailable");
+ if (!this.isAvailable()) {
+ throw this.unavailableError(`host RPC unavailable: ${method}`);
+ }
+ const id = randomUUID();
+ const timeoutMs = timeoutOverrideMs ?? rpcTimeoutMs(method, params);
+ const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n";
+ if (Buffer.byteLength(payload, "utf8") > MAX_HOST_STDIN_LINE_BYTES) {
+ throw Object.assign(new Error("request line exceeds 64 MiB"), {
+ errorCode: ErrorCodes.LIMIT_EXCEEDED,
+ code: 1002,
+ });
+ }
+ return new Promise<T>((resolve, reject) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let settled = false;
+ const settle = (finish: () => void) => {
+ if (settled) return;
+ settled = true;
+ this.pending.delete(id);
+ if (timer) clearTimeout(timer);
+ finish();
+ };
+ this.pending.set(id, {
+ resolve: (value) => settle(() => resolve(value)),
+ reject: (error) => settle(() => reject(error)),
+ });
+ if (!this.isAvailable()) {
+ settle(() => reject(this.unavailableError(`host RPC unavailable: ${method}`)));
+ return;
+ }
+ if (timeoutMs !== undefined) {
+ timer = setTimeout(
+ () => settle(() => reject(new Error(`host RPC timeout: ${method}`))),
+ timeoutMs,
+ );
+ }
+ try {
+ this.child.stdin.write(payload, (error) => {
+ if (!error) return;
+ const failure = this.unavailableError(
+ `host RPC write failed: ${error.message}`,
+ );
+ settle(() => reject(failure));
+ this.closeTransport(failure);
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ });
+ } catch (error) {
+ const failure = this.unavailableError(
+ `host RPC write failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ settle(() => reject(failure));
+ this.closeTransport(failure);
+ this.notifyExit({ code: null, signal: null, intentional: this.disposed });
+ }
+ });
+ }
+
+ async handshake(): Promise<void> {
+ await this.call("app.handshake", { protocolVersion: PROTOCOL_VERSION });
+ }
+
+ async dispose(): Promise<void> {
+ if (this.disposePromise) return this.disposePromise;
+ this.disposePromise = this.disposeInternal();
+ return this.disposePromise;
+ }
+
+ private async disposeInternal(): Promise<void> {
+ this.disposed = true;
+ this.available = false;
+ // EOF is the graceful host-core shutdown signal. Send it before rejecting
+ // transport callers so the runner can clean up active tools first.
+ if (!this.child.stdin.destroyed && !this.child.stdin.writableEnded) {
+ this.child.stdin.end();
+ }
+ this.closeTransport(this.unavailableError("host-core disposed"));
+ if (this.exitObserved) return;
+
+ const exited = await this.waitForExit(HOST_DISPOSE_GRACE_MS);
+ if (exited || this.exitObserved) return;
+
+ try {
+ this.child.kill("SIGKILL");
+ } catch {
+ // The child may have exited between the grace check and kill fallback.
+ }
+ await this.waitForExit(HOST_FORCE_KILL_GRACE_MS);
+ }
+}
diff --git a/packages/host-runtime/src/index.ts b/packages/host-runtime/src/index.ts
new file mode 100644
index 000000000..55720460b
--- /dev/null
+++ b/packages/host-runtime/src/index.ts
@@ -0,0 +1,12 @@
+export * from "./host-process.js";
+export * from "./agent-sidecar.js";
+export * from "./runtime-supervisor.js";
+export * from "./host-ports.js";
+export * from "./launch-resolver.js";
+export * from "./session-message-input.js";
+export * from "./inflight-checkpoint.js";
+export * from "./plan-execution.js";
+export * from "./turn-persistence.js";
+export * from "./turn-events.js";
+export * from "./runtime-service.js";
+export * from "./plan-dispatch.js";
diff --git a/apps/desktop/electron/main/inflight-checkpoint.ts b/packages/host-runtime/src/inflight-checkpoint.ts
similarity index 100%
rename from apps/desktop/electron/main/inflight-checkpoint.ts
rename to packages/host-runtime/src/inflight-checkpoint.ts
diff --git a/packages/host-runtime/src/launch-resolver.test.ts b/packages/host-runtime/src/launch-resolver.test.ts
new file mode 100644
index 000000000..a58ca4902
--- /dev/null
+++ b/packages/host-runtime/src/launch-resolver.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from "vitest";
+
+import { createHeadlessLaunchResolver, type HostProviderRecord } from "./launch-resolver.js";
+
+type Call = { method: string; params: Record<string, unknown> };
+
+function hostWith(providers: HostProviderRecord[], secrets: Record<string, string> = {}) {
+ const calls: Call[] = [];
+ return {
+ calls,
+ host: {
+ async call<T>(method: string, params: Record<string, unknown> = {}): Promise<T> {
+ calls.push({ method, params });
+ switch (method) {
+ case "commandShells.list":
+ return {
+ configuredId: null,
+ effective: { id: "bash", label: "bash", available: true, dialect: "posix", isDefault: true },
+ fallback: true,
+ choices: [{ id: "bash", label: "bash", available: true, dialect: "posix", isDefault: true }],
+ } as T;
+ case "providers.list":
+ return { providers } as T;
+ case "providers.getSecret":
+ return { value: secrets[String(params.id)] } as T;
+ case "skills.active":
+ return { skills: [{ id: "review", name: "Review", enabled: true, description: "Review code" }] } as T;
+ case "agents.active":
+ return { subagents: [] } as T;
+ case "agents.disabledBuiltins":
+ return { disabled: [] } as T;
+ case "project.group.context":
+ return { context: null } as T;
+ case "project.memory.get":
+ return { memory: { content: "remember me" } } as T;
+ default:
+ throw new Error(`unexpected ${method}`);
+ }
+ },
+ },
+ };
+}
+
+const provider: HostProviderRecord = {
+ id: "p1",
+ name: "OpenAI",
+ vendorKey: "openai",
+ baseUrl: "https://api.openai.com/v1",
+ models: [
+ { id: "gpt-a", contextWindow: 128_000, maxTokens: 8_192, thinkingLevels: ["off"], defaultThinkingLevel: null, availableForSubagents: false },
+ ],
+ authKind: "api_key",
+ hasSecret: true,
+ enabled: true,
+};
+
+describe("createHeadlessLaunchResolver", () => {
+ it("resolves the session's provider, its secret, the shell, skills and project memory", async () => {
+ const { host, calls } = hostWith([provider], { p1: "sk-test" });
+ const resolver = createHeadlessLaunchResolver({ getHost: () => host, dataDir: "/data", log: () => undefined });
+ const launch = await resolver.resolve(
+ "s1",
+ { providerId: "p1", modelId: "gpt-a", projectPath: "/work/project" },
+ { defaultMode: "agent" },
+ );
+ expect(launch.providerId).toBe("p1");
+ expect(launch.modelId).toBe("gpt-a");
+ expect(launch.projectPath).toBe("/work/project");
+ expect(launch.sidecarParams.provider.apiKey).toBe("sk-test");
+ expect(launch.sidecarParams.provider.modelConfig?.name).toBe("gpt-a");
+ expect(launch.sidecarParams.scratchDir).toBe("/data/scratch/s1");
+ expect(launch.sidecarParams.pluginSkills).toEqual([{ id: "review", name: "Review", description: "Review code" }]);
+ expect(launch.sidecarParams.pluginTools).toEqual([]);
+ expect(launch.sidecarParams.projectMemory).toBe("remember me");
+ expect(launch.sidecarParams.commandShell).toMatchObject({ id: "bash" });
+ expect(calls.some((call) => call.method === "providers.getSecret")).toBe(true);
+ });
+
+ it("falls back to the default provider and refuses a provider without a secret", async () => {
+ const { host } = hostWith([provider, { ...provider, id: "p2", name: "Other", hasSecret: false }], { p1: "sk" });
+ const resolver = createHeadlessLaunchResolver({ getHost: () => host, dataDir: "/data", log: () => undefined });
+ const launch = await resolver.resolve("s1", {}, { defaultProviderId: "p1", defaultModelId: "gpt-a" });
+ expect(launch.providerId).toBe("p1");
+ await expect(resolver.resolve("s1", { providerId: "p2", modelId: "gpt-a" }, {})).rejects.toMatchObject({
+ errorCode: "PROVIDER_SECRET_MISSING",
+ });
+ });
+
+ it("refuses vendor accounts and plugin agents, which need the desktop", async () => {
+ const { host } = hostWith([{ ...provider, authKind: "oauth" }]);
+ const resolver = createHeadlessLaunchResolver({ getHost: () => host, dataDir: "/data", log: () => undefined });
+ await expect(resolver.resolve("s1", { providerId: "p1" }, {})).rejects.toMatchObject({ errorCode: "MODEL_NOT_CONFIGURED" });
+ await expect(resolver.resolve("s1", { providerId: "extension-agent:plugin.x%2Fagent" }, {})).rejects.toMatchObject({
+ errorCode: "MODEL_NOT_CONFIGURED",
+ });
+ });
+
+ it("fails with a typed error when no provider exists or the host is gone", async () => {
+ const { host } = hostWith([]);
+ const resolver = createHeadlessLaunchResolver({ getHost: () => host, dataDir: "/data", log: () => undefined });
+ await expect(resolver.resolve("s1", {}, {})).rejects.toMatchObject({ errorCode: "MODEL_NOT_CONFIGURED" });
+ const offline = createHeadlessLaunchResolver({ getHost: () => null, dataDir: "/data", log: () => undefined });
+ await expect(offline.resolve("s1", {}, {})).rejects.toMatchObject({ errorCode: "HOST_UNAVAILABLE" });
+ });
+});
diff --git a/packages/host-runtime/src/launch-resolver.ts b/packages/host-runtime/src/launch-resolver.ts
new file mode 100644
index 000000000..1beefe90d
--- /dev/null
+++ b/packages/host-runtime/src/launch-resolver.ts
@@ -0,0 +1,409 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import {
+ ErrorCodes,
+ OAUTH_AUTH_KIND,
+ isActiveInProject,
+ isCommandShellCatalog,
+ normalizeMode,
+ resolveBindingContextWindow,
+ trustedExtensionAgentKeyFromProviderId,
+ type CommandShellCatalog,
+ type ModelBinding,
+ type Mode,
+ type ThinkingLevel,
+ type UserSkillRecord,
+ type UserSubagentRecord,
+} from "@pi-desktop/shared";
+import {
+ capabilitiesFromModelConfig,
+ clampThinkingLevel,
+ genericModelConfig,
+ loadInstructionChain,
+ loadSubagentDefinitions,
+ modelConfigWithBinding,
+ optionalProviderHeaders,
+ resolveSubagentProviders,
+ visionFromModelConfig,
+ type RuntimeProviderConfig,
+ type UserSubagentDocument,
+} from "@pi-desktop/agent-runtime";
+
+import type { HostRpc } from "./host-ports.js";
+
+/** A provider row as `providers.list` returns it. */
+export type HostProviderRecord = {
+ id: string;
+ name: string;
+ vendorKey?: string;
+ baseUrl?: string;
+ modelId?: string;
+ models?: ModelBinding[];
+ defaultModelId?: string;
+ authKind?: string;
+ apiStyle?: string;
+ hasSecret?: boolean;
+ hasOauth?: boolean;
+ headers?: Record<string, string>;
+ enabled?: boolean;
+};
+
+export type LaunchOverrides = {
+ mode?: Mode;
+ turnId?: string;
+ providerId?: string;
+ modelId?: string;
+ thinkingLevel?: ThinkingLevel;
+};
+
+/** What a turn needs to start: the provider identity and the sidecar payload. */
+export type ResolvedLaunch = {
+ providerId: string;
+ modelId: string;
+ projectPath?: string;
+ sidecarParams: Record<string, unknown> & {
+ sessionId: string;
+ mode: Mode;
+ provider: RuntimeProviderConfig & { supportsVision?: boolean };
+ };
+};
+
+export interface LaunchResolver {
+ resolve(
+ sessionId: string,
+ session: Record<string, unknown>,
+ settings: Record<string, unknown>,
+ overrides?: LaunchOverrides,
+ ): Promise<ResolvedLaunch>;
+}
+
+export type ModelCatalogPort = {
+ /** Catalog metadata for a provider model, or `undefined` for a generic shape. */
+ modelConfig(
+ provider: Pick<HostProviderRecord, "vendorKey" | "baseUrl">,
+ modelId: string,
+ ): ReturnType<typeof genericModelConfig> | undefined;
+};
+
+export type HeadlessLaunchResolverOptions = {
+ getHost: () => HostRpc | null;
+ dataDir: string;
+ log: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;
+ /** Optional models.dev snapshot; without it every model runs on the generic transport shape. */
+ catalog?: ModelCatalogPort;
+};
+
+const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
+
+function normalizeThinkingLevel(value: unknown): ThinkingLevel {
+ return typeof value === "string" && THINKING_LEVELS.includes(value as ThinkingLevel)
+ ? (value as ThinkingLevel)
+ : "off";
+}
+
+function launchError(message: string, errorCode: string): Error {
+ return Object.assign(new Error(message), { errorCode });
+}
+
+function isHostUnavailable(error: unknown): boolean {
+ return (error as { errorCode?: string } | null)?.errorCode === ErrorCodes.HOST_UNAVAILABLE;
+}
+
+/**
+ * Launch resolution for a headless Host. It is the desktop's
+ * `resolveAgentRuntimeLaunch` minus the surfaces a headless machine does not
+ * have: no plugin tools, no user MCP relay, no plugin agents, no vendor OAuth
+ * accounts. Everything else — provider rows and secrets, the effective
+ * command shell, project instructions and memory, the user's skills and
+ * subagent definitions — comes from the same host-core registries.
+ */
+export function createHeadlessLaunchResolver(options: HeadlessLaunchResolverOptions): LaunchResolver {
+ const { getHost, dataDir, log } = options;
+
+ function requireHost(): HostRpc {
+ const host = getHost();
+ if (!host) throw launchError("host unavailable", ErrorCodes.HOST_UNAVAILABLE);
+ return host;
+ }
+
+ async function activeUserSkills(projectPath: string | undefined): Promise<UserSkillRecord[]> {
+ try {
+ const result = await requireHost().call<{ skills: UserSkillRecord[] }>("skills.active", {
+ projectPath: projectPath ?? null,
+ });
+ return result.skills ?? [];
+ } catch (error) {
+ if (!isHostUnavailable(error)) log("warn", "skills list failed", { error: String(error) });
+ return [];
+ }
+ }
+
+ async function activeUserSubagentDocuments(projectPath: string | undefined): Promise<UserSubagentDocument[]> {
+ let records: UserSubagentRecord[] = [];
+ try {
+ const result = await requireHost().call<{ subagents: UserSubagentRecord[] }>("agents.active", {
+ projectPath: projectPath ?? null,
+ });
+ records = result.subagents ?? [];
+ } catch (error) {
+ if (!isHostUnavailable(error)) log("warn", "subagent list failed", { error: String(error) });
+ return [];
+ }
+ const documents: UserSubagentDocument[] = [];
+ for (const record of records) {
+ try {
+ documents.push({ id: record.id, document: await readFile(record.path, "utf8"), filePath: record.path });
+ } catch (error) {
+ log("warn", "subagent document unreadable", { id: record.id, error: String(error) });
+ }
+ }
+ return documents;
+ }
+
+ async function disabledBuiltinSubagents(): Promise<string[]> {
+ try {
+ const result = await requireHost().call<{ disabled: string[] }>("agents.disabledBuiltins");
+ return result.disabled ?? [];
+ } catch (error) {
+ if (!isHostUnavailable(error)) log("warn", "builtin subagent state failed", { error: String(error) });
+ return [];
+ }
+ }
+
+ async function resolveEffectiveCommandShell(): Promise<CommandShellCatalog> {
+ const catalog = await requireHost().call<CommandShellCatalog>("commandShells.list");
+ if (!isCommandShellCatalog(catalog)) {
+ throw launchError("Host returned an invalid command shell catalog", "COMMAND_SHELL_INVALID");
+ }
+ if (!catalog.effective || !catalog.effective.available) {
+ throw launchError("No available command shell is configured for this session", "SHELL_NOT_FOUND");
+ }
+ return catalog;
+ }
+
+ function catalogModelConfig(provider: HostProviderRecord, modelId: string, baseUrl: string | undefined) {
+ return options.catalog?.modelConfig({ vendorKey: provider.vendorKey, baseUrl }, modelId)
+ ?? genericModelConfig(modelId, baseUrl ?? "");
+ }
+
+ function bindingForModel(provider: Pick<HostProviderRecord, "models">, modelId: string): ModelBinding | undefined {
+ return provider.models?.find((binding) => binding.id === modelId);
+ }
+
+ function effectiveModelConfig(provider: HostProviderRecord, modelId: string, baseUrl: string | undefined) {
+ const storedModel = bindingForModel(provider, modelId);
+ const resolvedLimits = resolveBindingContextWindow(catalogModelConfig(provider, modelId, baseUrl), storedModel);
+ const modelConfig = modelConfigWithBinding(resolvedLimits.catalogConfig, resolvedLimits.binding);
+ return { modelConfig, capabilities: capabilitiesFromModelConfig(modelConfig), storedModel };
+ }
+
+ async function getSecret(providerId: string): Promise<string | undefined> {
+ const secret = await requireHost().call<{ value?: string }>("providers.getSecret", { id: providerId });
+ return secret?.value;
+ }
+
+ async function resolve(
+ sessionId: string,
+ session: Record<string, unknown>,
+ settings: Record<string, unknown>,
+ overrides: LaunchOverrides = {},
+ ): Promise<ResolvedLaunch> {
+ const host = requireHost();
+ const commandShell = (await resolveEffectiveCommandShell()).effective!;
+ const providers = await host.call<{ providers: HostProviderRecord[] }>("providers.list", {
+ includeDisabled: false,
+ });
+ const sessionProviderId = typeof session.providerId === "string" ? session.providerId : undefined;
+ const sessionModelId = typeof session.modelId === "string" ? session.modelId : undefined;
+ const requestedProviderId = overrides.providerId ?? sessionProviderId;
+ if (requestedProviderId && trustedExtensionAgentKeyFromProviderId(requestedProviderId)) {
+ throw launchError("Plugin agents are not available on a headless host", ErrorCodes.MODEL_NOT_CONFIGURED);
+ }
+ const defaultProviderId = typeof settings.defaultProviderId === "string" ? settings.defaultProviderId : undefined;
+ const defaultModelId = typeof settings.defaultModelId === "string" ? settings.defaultModelId : undefined;
+ const provider =
+ providers.providers.find((item) => item.id === requestedProviderId) ||
+ providers.providers.find((item) => item.id === defaultProviderId) ||
+ providers.providers.find((item) => item.hasSecret || item.authKind === "none") ||
+ providers.providers[0];
+ if (!provider) throw launchError("No provider configured", ErrorCodes.MODEL_NOT_CONFIGURED);
+ if (provider.authKind === OAUTH_AUTH_KIND) {
+ throw launchError(
+ "Vendor account sign-in is not available on a headless host; configure an API key provider",
+ ErrorCodes.MODEL_NOT_CONFIGURED,
+ );
+ }
+ const secretValue = provider.authKind === "none" ? undefined : await getSecret(provider.id);
+ if (!secretValue && provider.authKind !== "none") {
+ throw launchError("Provider API key missing", ErrorCodes.PROVIDER_SECRET_MISSING);
+ }
+ const modelId =
+ (provider.id === requestedProviderId ? overrides.modelId ?? sessionModelId : undefined) ||
+ (provider.id === defaultProviderId ? defaultModelId : undefined) ||
+ provider.models?.[0]?.id ||
+ provider.defaultModelId;
+ if (!modelId) throw launchError("No model selected for provider", ErrorCodes.MODEL_NOT_CONFIGURED);
+
+ const { modelConfig, capabilities, storedModel } = effectiveModelConfig(provider, modelId, provider.baseUrl);
+ const thinkingLevel = clampThinkingLevel(
+ capabilities,
+ normalizeThinkingLevel(
+ overrides.thinkingLevel ??
+ (provider.id === requestedProviderId ? session.thinkingLevel : undefined) ??
+ storedModel?.defaultThinkingLevel,
+ ),
+ );
+ const projectPath =
+ typeof session.projectPath === "string" && session.projectPath.trim() ? session.projectPath.trim() : undefined;
+ let projectInstructions = await loadInstructionChain(projectPath);
+ let projectMemory: string | undefined;
+ if (projectPath) {
+ try {
+ const result = await host.call<{
+ context?: { roots?: Array<{ path?: string }>; instructions?: string; memory?: { content?: string } } | null;
+ }>("project.group.context", { path: projectPath });
+ const groupRoots = result.context?.roots ?? [];
+ const groupRootGuide =
+ groupRoots.length > 1
+ ? [
+ `Primary root: ${groupRoots[0]?.path ?? projectPath}`,
+ ...groupRoots.slice(1).map((root) => `Additional root: ${root.path}`),
+ "Use an absolute path when reading or editing an additional root.",
+ ].join("\n")
+ : "";
+ const groupInstructions = result.context?.instructions?.trim();
+ if (groupRootGuide || groupInstructions) {
+ projectInstructions = {
+ entries: [
+ ...(projectInstructions?.entries ?? []),
+ ...(groupRootGuide ? [{ source: "ChatGPT Project folders", content: groupRootGuide }] : []),
+ ...(groupInstructions ? [{ source: "ChatGPT Project instructions", content: groupInstructions }] : []),
+ ],
+ };
+ }
+ const groupMemory = result.context?.memory?.content?.trim();
+ if (groupMemory) projectMemory = groupMemory;
+ if (!result.context) {
+ const legacy = await host.call<{ memory?: { content?: string } }>("project.memory.get", { path: projectPath });
+ const content = legacy.memory?.content?.trim();
+ if (content) projectMemory = content;
+ }
+ } catch {
+ try {
+ const legacy = await host.call<{ memory?: { content?: string } }>("project.memory.get", { path: projectPath });
+ const content = legacy.memory?.content?.trim();
+ if (content) projectMemory = content;
+ } catch {
+ // Project memory is best effort; it must never prevent a session launch.
+ }
+ }
+ }
+
+ const userSkills = (await activeUserSkills(projectPath)).filter((skill) => isActiveInProject(skill, projectPath ?? null));
+ const pluginSkills = userSkills.map((skill) => ({ id: skill.id, name: skill.name, description: skill.description }));
+
+ const subagentCatalog = await loadSubagentDefinitions(projectPath, {
+ userDocuments: await activeUserSubagentDocuments(projectPath),
+ disabledBuiltins: await disabledBuiltinSubagents(),
+ });
+ const subagentBindings = await resolveSubagentProviders({
+ definitions: subagentCatalog.definitions,
+ providers: providers.providers,
+ getSecret,
+ resolveModel: async (pinned, pinnedModelId) => {
+ const row = providers.providers.find((candidate) => candidate.id === pinned.id);
+ const resolved = effectiveModelConfig(row ?? { ...pinned, models: [] }, pinnedModelId, pinned.baseUrl);
+ return { modelConfig: resolved.modelConfig, capabilities: resolved.capabilities };
+ },
+ });
+ const subagentModelKeys: string[] = [];
+ for (const row of providers.providers) {
+ if (!row.enabled) continue;
+ for (const binding of row.models ?? []) {
+ if (!binding.availableForSubagents) continue;
+ let key = `${row.vendorKey ?? row.name}/${binding.id}`;
+ if (subagentBindings.providers[key]?.id && subagentBindings.providers[key].id !== row.id) {
+ key = `${row.id}/${binding.id}`;
+ }
+ if (subagentBindings.providers[key]) {
+ subagentModelKeys.push(key);
+ continue;
+ }
+ if (row.authKind === OAUTH_AUTH_KIND) continue;
+ let apiKey = "";
+ if (row.authKind !== "none") {
+ try {
+ apiKey = (await getSecret(row.id)) ?? "";
+ } catch {
+ continue;
+ }
+ if (!apiKey) continue;
+ }
+ const effective = effectiveModelConfig(row, binding.id, row.baseUrl);
+ subagentBindings.providers[key] = {
+ id: row.id,
+ name: row.name,
+ ...(row.vendorKey ? { vendorKey: row.vendorKey } : {}),
+ ...(row.baseUrl ? { baseUrl: row.baseUrl } : {}),
+ modelId: binding.id,
+ apiKey,
+ ...(row.authKind ? { authKind: row.authKind } : {}),
+ ...(row.apiStyle ? { apiStyle: row.apiStyle } : {}),
+ ...optionalProviderHeaders(row.headers),
+ supportsReasoning: effective.capabilities.supportsReasoning,
+ supportedThinkingLevels: [...effective.capabilities.supportedThinkingLevels],
+ modelConfig: effective.modelConfig,
+ };
+ subagentModelKeys.push(key);
+ }
+ }
+ const subagentDiagnostics = [...subagentCatalog.diagnostics, ...subagentBindings.diagnostics];
+ if (subagentDiagnostics.length > 0) {
+ log("warn", "subagent definitions have problems", { sessionId, diagnostics: subagentDiagnostics });
+ }
+
+ const sessionMode = typeof session.mode === "string" ? session.mode : undefined;
+ const defaultMode = typeof settings.defaultMode === "string" ? settings.defaultMode : undefined;
+ return {
+ providerId: provider.id,
+ modelId,
+ projectPath,
+ sidecarParams: {
+ sessionId,
+ mode: normalizeMode(overrides.mode ?? sessionMode ?? defaultMode ?? "agent"),
+ ...(overrides.turnId ? { turnId: overrides.turnId } : {}),
+ thinkingLevel,
+ commandShell,
+ scratchDir: join(dataDir, "scratch", sessionId),
+ attachmentsDir: join(dataDir, "attachments"),
+ projectPath,
+ projectInstructions,
+ projectMemory,
+ provider: {
+ id: provider.id,
+ name: provider.name,
+ vendorKey: provider.vendorKey,
+ baseUrl: provider.baseUrl,
+ modelId,
+ apiKey: secretValue || "",
+ authKind: provider.authKind,
+ apiStyle: provider.apiStyle,
+ ...optionalProviderHeaders(provider.headers),
+ supportsReasoning: capabilities.supportsReasoning,
+ supportsVision: visionFromModelConfig(modelConfig),
+ supportedThinkingLevels: [...capabilities.supportedThinkingLevels],
+ modelConfig,
+ },
+ pluginTools: [],
+ pluginSkills,
+ trustedExtensions: [],
+ subagents: subagentCatalog.definitions,
+ subagentProviders: subagentBindings.providers,
+ subagentModelKeys,
+ },
+ };
+ }
+
+ return { resolve };
+}
diff --git a/packages/host-runtime/src/plan-dispatch.ts b/packages/host-runtime/src/plan-dispatch.ts
new file mode 100644
index 000000000..b5b0521b9
--- /dev/null
+++ b/packages/host-runtime/src/plan-dispatch.ts
@@ -0,0 +1,208 @@
+import { ErrorCodes, type PlanExecution, type PlanExecutionFinishStatus } from "@pi-desktop/shared";
+
+import type { HostRpc } from "./host-ports.js";
+import type { LaunchResolver } from "./launch-resolver.js";
+import { executionFromResponse, executionListFromResponse, planExecutionFromUnknown } from "./plan-execution.js";
+import type { RuntimeLogger, RuntimeService, RuntimeSidecarLink } from "./runtime-service.js";
+
+export type PlanExecutionDispatcherOptions = {
+ getHost: () => HostRpc | null;
+ getSidecar: () => RuntimeSidecarLink | null;
+ launch: LaunchResolver;
+ runtime: Pick<RuntimeService, "withSessionOperation" | "beginTurn" | "finishTurn" | "activeTurnId" | "onTurnEnded">;
+ log: RuntimeLogger;
+ sleep?: (ms: number) => Promise<void>;
+};
+
+/**
+ * Approved Plan/Goal executions on a headless Host (D189). host-core owns the
+ * approval row and its execution state; this dispatcher claims a queued
+ * execution, opens the turn that runs it, hands it to the sidecar, and closes
+ * the execution when that turn ends. Nothing is replayed: a row the host
+ * already reports as running belongs to a previous process.
+ */
+export class PlanExecutionDispatcher {
+ private readonly approvedExecutionIdsBySession = new Map<string, string>();
+ private readonly executionTurns = new Map<string, { sessionId: string; turnId: string }>();
+ private readonly started = new Set<string>();
+ private readonly finished = new Set<string>();
+ private readonly dispatching = new Set<string>();
+ private readonly inFlightFinishes = new Set<string>();
+ private readonly pendingFinishes = new Map<string, { status: PlanExecutionFinishStatus; errorCode?: string }>();
+ private drain: Promise<void> | null = null;
+ private readonly detach: () => void;
+
+ constructor(private readonly options: PlanExecutionDispatcherOptions) {
+ this.detach = options.runtime.onTurnEnded((info) => {
+ const executionId = this.approvedExecutionIdsBySession.get(info.sessionId);
+ if (!executionId) return;
+ const turn = this.executionTurns.get(executionId);
+ if (turn?.turnId !== info.turnId) return;
+ void this.finishApprovedExecution(
+ executionId,
+ info.reason === "completed" ? "completed" : "interrupted",
+ info.reason === "completed" ? undefined : info.errorCode ?? "PLAN_EXECUTION_INTERRUPTED",
+ );
+ });
+ }
+
+ dispose(): void {
+ this.detach();
+ }
+
+ /** The execution a session is currently running, if any. */
+ executionForSession(sessionId: string): string | undefined {
+ return this.approvedExecutionIdsBySession.get(sessionId);
+ }
+
+ async finishApprovedExecution(
+ executionId: string,
+ status: PlanExecutionFinishStatus,
+ errorCode?: string,
+ ): Promise<void> {
+ if (this.finished.has(executionId) || this.inFlightFinishes.has(executionId)) return;
+ if (!this.pendingFinishes.has(executionId)) this.pendingFinishes.set(executionId, { status, errorCode });
+ this.inFlightFinishes.add(executionId);
+ const host = this.options.getHost();
+ if (!host) {
+ this.inFlightFinishes.delete(executionId);
+ return;
+ }
+ try {
+ const pending = this.pendingFinishes.get(executionId) ?? { status, errorCode };
+ await host.call("plans.finishExecution", {
+ executionId,
+ status: pending.status,
+ ...(pending.errorCode ? { errorCode: pending.errorCode } : {}),
+ });
+ this.finished.add(executionId);
+ this.started.delete(executionId);
+ this.pendingFinishes.delete(executionId);
+ const turn = this.executionTurns.get(executionId);
+ if (turn && this.approvedExecutionIdsBySession.get(turn.sessionId) === executionId) {
+ this.approvedExecutionIdsBySession.delete(turn.sessionId);
+ }
+ this.executionTurns.delete(executionId);
+ } catch (error) {
+ this.options.log("warn", "approved plan execution finalization failed", { executionId, error: String(error) });
+ } finally {
+ this.inFlightFinishes.delete(executionId);
+ }
+ }
+
+ async dispatchApprovedPlan(rawExecution: unknown): Promise<void> {
+ const initial = planExecutionFromUnknown(rawExecution);
+ if (!initial) {
+ this.options.log("warn", "approved plan execution descriptor was invalid");
+ return;
+ }
+ await this.options.runtime.withSessionOperation(initial.sessionId, async () => {
+ if (
+ initial.state !== "queued" ||
+ this.started.has(initial.id) ||
+ this.finished.has(initial.id) ||
+ this.dispatching.has(initial.id)
+ ) {
+ return;
+ }
+ const host = this.options.getHost();
+ const sidecar = this.options.getSidecar();
+ if (!host || !sidecar) return;
+ if (this.options.runtime.activeTurnId(initial.sessionId)) {
+ // The submitting turn is still finalizing; look again shortly.
+ const timer = setTimeout(() => void this.dispatchApprovedPlan(initial), 250);
+ timer.unref?.();
+ return;
+ }
+ this.dispatching.add(initial.id);
+ let claimed = false;
+ let turnId: string | undefined;
+ try {
+ const claimResponse = await host.call("plans.claimExecution", { executionId: initial.id });
+ const claimedExecution = executionFromResponse(claimResponse);
+ if (claimedExecution && claimedExecution.state !== "running") {
+ // Interrupted or completed rows are durable outcomes, never replayed.
+ return;
+ }
+ const execution: PlanExecution = { ...(claimedExecution ?? initial), state: "running" };
+ claimed = true;
+ const [settings, sessionResult] = await Promise.all([
+ host.call<Record<string, unknown>>("settings.get"),
+ host.call<{ session?: Record<string, unknown> | null }>("session.get", { id: execution.sessionId }),
+ ]);
+ if (!sessionResult.session) {
+ throw Object.assign(new Error("Session not found"), { errorCode: ErrorCodes.NOT_FOUND });
+ }
+ const launch = await this.options.launch.resolve(execution.sessionId, sessionResult.session, settings ?? {}, {
+ mode: "agent",
+ });
+ turnId = await this.options.runtime.beginTurn(execution.sessionId, launch.providerId, launch.modelId);
+ this.approvedExecutionIdsBySession.set(execution.sessionId, execution.id);
+ this.executionTurns.set(execution.id, { sessionId: execution.sessionId, turnId });
+ this.started.add(execution.id);
+ sidecar.setProjectInstructionRoot(execution.sessionId, launch.projectPath);
+ const accepted = await sidecar.call<{ accepted: boolean }>("agent.executeApprovedPlan", {
+ ...launch.sidecarParams,
+ mode: "agent",
+ turnId,
+ execution,
+ });
+ if (accepted?.accepted !== true) throw new Error("approved plan execution was not accepted");
+ this.options.log("info", "approved plan execution started", {
+ sessionId: execution.sessionId,
+ executionId: execution.id,
+ turnId,
+ });
+ } catch (error) {
+ const errorCode =
+ (error as { data?: { errorCode?: string } })?.data?.errorCode ||
+ (error as { errorCode?: string })?.errorCode ||
+ "PLAN_EXECUTION_INTERRUPTED";
+ if (turnId) await this.options.runtime.finishTurn(initial.sessionId, "error", errorCode, { turnId });
+ if (claimed) await this.finishApprovedExecution(initial.id, "interrupted", errorCode);
+ this.options.log("warn", "approved plan execution failed to start", {
+ sessionId: initial.sessionId,
+ executionId: initial.id,
+ error: String(error),
+ });
+ } finally {
+ this.dispatching.delete(initial.id);
+ }
+ });
+ }
+
+ /** Dispatch every queued execution the host restored, once, on boot or after a restart. */
+ async drainApprovedPlanExecutions(): Promise<void> {
+ if (this.drain) return this.drain;
+ this.drain = (async () => {
+ const host = this.options.getHost();
+ if (!host || !this.options.getSidecar()) return;
+ for (const [executionId, finish] of this.pendingFinishes) {
+ await this.finishApprovedExecution(executionId, finish.status, finish.errorCode);
+ }
+ const response = await host.call("plans.queuedExecutions");
+ for (const execution of executionListFromResponse(response)) {
+ if (execution.state !== "queued") continue;
+ await this.dispatchApprovedPlan(execution);
+ }
+ })();
+ try {
+ await this.drain;
+ } finally {
+ this.drain = null;
+ }
+ }
+
+ /** After an approval resolved, run the execution it produced. */
+ async dispatchExecutionForProposal(proposalId: string): Promise<void> {
+ const host = this.options.getHost();
+ if (!host) return;
+ try {
+ const response = await host.call("plans.queuedExecutions");
+ const execution = executionListFromResponse(response).find((candidate) => candidate.proposalId === proposalId);
+ if (execution?.state === "queued") await this.dispatchApprovedPlan(execution);
+ } catch (error) {
+ this.options.log("warn", "approved plan lookup after resolution failed", { proposalId, error: String(error) });
+ }
+ }
+}
diff --git a/apps/desktop/electron/main/plan-execution.ts b/packages/host-runtime/src/plan-execution.ts
similarity index 100%
rename from apps/desktop/electron/main/plan-execution.ts
rename to packages/host-runtime/src/plan-execution.ts
diff --git a/packages/host-runtime/src/runtime-service.test.ts b/packages/host-runtime/src/runtime-service.test.ts
new file mode 100644
index 000000000..40bd8985e
--- /dev/null
+++ b/packages/host-runtime/src/runtime-service.test.ts
@@ -0,0 +1,319 @@
+import { describe, expect, it } from "vitest";
+import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
+
+import type { LaunchResolver } from "./launch-resolver.js";
+import { RuntimeService, type RuntimeHostLink, type RuntimeSidecarLink, type TurnEndedInfo } from "./runtime-service.js";
+
+type Call = { method: string; params: Record<string, unknown> };
+
+class FakeHost implements RuntimeHostLink {
+ calls: Call[] = [];
+ notify: ((method: string, params: unknown) => void) | null = null;
+ available = true;
+ private turnCounter = 0;
+ messages = new Map<string, UiMessage[]>();
+ failAppend = false;
+ session: Record<string, unknown> = { id: "s1", mode: "agent", permissionMode: "ask", providerId: "p1", modelId: "m1" };
+
+ async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
+ this.calls.push({ method, params });
+ switch (method) {
+ case "settings.get":
+ return {} as T;
+ case "session.get":
+ return { session: { ...this.session, id: params.id, messages: this.messages.get(String(params.id)) ?? [] } } as T;
+ case "session.beginTurn":
+ this.turnCounter += 1;
+ return { turnId: `turn-${this.turnCounter}` } as T;
+ case "session.appendMessage": {
+ if (this.failAppend) throw Object.assign(new Error("disk full"), { errorCode: "INTERNAL" });
+ const list = this.messages.get(String(params.sessionId)) ?? [];
+ list.push(params.message as UiMessage);
+ this.messages.set(String(params.sessionId), list);
+ return {} as T;
+ }
+ case "session.endTurn":
+ return { ok: true } as T;
+ case "session.saveInflightMessage":
+ return { ok: true } as T;
+ case "plans.abort":
+ return {} as T;
+ default:
+ throw new Error(`unexpected host call ${method}`);
+ }
+ }
+ isAvailable(): boolean {
+ return this.available;
+ }
+ onNotification(handler: (method: string, params: unknown) => void): () => void {
+ this.notify = handler;
+ return () => {
+ this.notify = null;
+ };
+ }
+ onExit(): () => void {
+ return () => undefined;
+ }
+}
+
+class FakeSidecar implements RuntimeSidecarLink {
+ calls: Call[] = [];
+ notify: ((method: string, params: unknown) => void) | null = null;
+ exit: ((info: { intentional: boolean; code: number | null; signal: NodeJS.Signals | null }) => void) | null = null;
+ roots = new Map<string, string | undefined>();
+ rejectPrompt = false;
+ running = false;
+
+ async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
+ this.calls.push({ method, params });
+ switch (method) {
+ case "agent.prompt":
+ if (this.rejectPrompt) throw Object.assign(new Error("model not configured"), { data: { errorCode: "MODEL_NOT_CONFIGURED" } });
+ this.running = true;
+ return { accepted: true, turnId: params.turnId } as T;
+ case "agent.steeringContext":
+ return { supportsVision: false } as T;
+ case "agent.steer":
+ return { accepted: true, turnId: params.expectedTurnId } as T;
+ case "agent.abort":
+ return { ok: true } as T;
+ case "agent.stop":
+ return { requested: this.running } as T;
+ case "agent.getStatus":
+ return { status: { sessionId: params.sessionId, isRunning: this.running, pendingToolConfirmations: 0 } } as T;
+ case "asktool.resolve":
+ return { ok: true } as T;
+ default:
+ throw new Error(`unexpected sidecar call ${method}`);
+ }
+ }
+ onNotification(handler: (method: string, params: unknown) => void): () => void {
+ this.notify = handler;
+ return () => {
+ this.notify = null;
+ };
+ }
+ onExit(handler: (info: { intentional: boolean; code: number | null; signal: NodeJS.Signals | null }) => void): () => void {
+ this.exit = handler;
+ return () => {
+ this.exit = null;
+ };
+ }
+ setProjectInstructionRoot(sessionId: string, projectPath?: string): void {
+ this.roots.set(sessionId, projectPath);
+ }
+ clearProjectInstructionRoot(): void {}
+ clearVendorAuthBindings(): void {}
+}
+
+const launch: LaunchResolver = {
+ async resolve(sessionId, session) {
+ return {
+ providerId: String(session.providerId ?? "p1"),
+ modelId: String(session.modelId ?? "m1"),
+ projectPath: "/work/project",
+ sidecarParams: {
+ sessionId,
+ mode: "agent",
+ provider: { id: "p1", name: "P1", modelId: "m1", apiKey: "k", supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ },
+ };
+ },
+};
+
+function build() {
+ const host = new FakeHost();
+ const sidecar = new FakeSidecar();
+ const events: AgentEventEnvelope[] = [];
+ const ended: TurnEndedInfo[] = [];
+ const logs: Array<{ level: string; message: string }> = [];
+ const service = new RuntimeService({
+ getHost: () => host,
+ getSidecar: () => sidecar,
+ launch,
+ log: (level, message) => logs.push({ level, message }),
+ now: () => Date.parse("2026-09-18T00:00:00.000Z"),
+ });
+ service.attachHost(host);
+ service.attachSidecar(sidecar);
+ service.onEvent((envelope) => events.push(envelope));
+ service.onTurnEnded((info) => ended.push(info));
+ return { host, sidecar, service, events, ended, logs };
+}
+
+const owner = { subject: "desktop", roles: ["owner" as const], pairedDevice: true };
+
+async function settle(): Promise<void> {
+ for (let index = 0; index < 5; index += 1) await new Promise((resolve) => setImmediate(resolve));
+}
+
+describe("RuntimeService prompt lifecycle", () => {
+ it("opens a durable turn, persists the user row, then starts the runtime under that turn id", async () => {
+ const { host, sidecar, service, events } = build();
+ const { turnId } = await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ expect(turnId).toBe("turn-1");
+ const methods = host.calls.map((call) => call.method);
+ expect(methods.indexOf("session.beginTurn")).toBeLessThan(methods.indexOf("session.appendMessage"));
+ const prompt = sidecar.calls.find((call) => call.method === "agent.prompt");
+ expect(prompt?.params.turnId).toBe("turn-1");
+ expect(prompt?.params.content).toBe("hello");
+ expect(sidecar.roots.get("s1")).toBe("/work/project");
+ expect(service.isBusy("s1")).toBe(true);
+ expect(service.activeTurnId("s1")).toBe("turn-1");
+ // The user row is announced to subscribers before the runtime answers.
+ expect(events.map((event) => event.event.type)).toEqual(["message_start", "message_end"]);
+ const userRow = (events[0]!.event as { message: UiMessage }).message;
+ expect(userRow.role).toBe("user");
+ expect(host.messages.get("s1")?.[0]?.id).toBe(userRow.id);
+ });
+
+ it("keeps a client-chosen UUID as the durable user row id", async () => {
+ const { host, service } = build();
+ const id = "6f1c1e2a-3b4d-4c5e-8f6a-7b8c9d0e1f2a";
+ await service.prompt({ sessionId: "s1", content: "x", userMessageId: id, effectivePermissionMode: "ask", principal: owner });
+ expect(host.messages.get("s1")?.[0]?.id).toBe(id);
+ });
+
+ it("refuses a second prompt while the turn runs and settles the turn on agent_end", async () => {
+ const { host, sidecar, service, ended } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ await expect(
+ service.prompt({ sessionId: "s1", content: "again", effectivePermissionMode: "ask", principal: owner }),
+ ).rejects.toMatchObject({ errorCode: "AGENT_BUSY" });
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-1", ts: 1, event: { type: "agent_end", messageIds: [] } });
+ await settle();
+ const end = host.calls.find((call) => call.method === "session.endTurn");
+ expect(end?.params).toMatchObject({ turnId: "turn-1", status: "completed" });
+ expect(ended).toEqual([{ sessionId: "s1", turnId: "turn-1", reason: "completed", settled: true }]);
+ expect(service.isBusy("s1")).toBe(false);
+ });
+
+ it("closes the turn as failed when the runtime rejects the prompt", async () => {
+ const { host, sidecar, service, ended } = build();
+ sidecar.rejectPrompt = true;
+ await expect(
+ service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner }),
+ ).rejects.toThrow("model not configured");
+ const end = host.calls.find((call) => call.method === "session.endTurn");
+ expect(end?.params).toMatchObject({ turnId: "turn-1", status: "error", errorCode: "MODEL_NOT_CONFIGURED" });
+ expect(ended[0]).toMatchObject({ reason: "error", errorCode: "MODEL_NOT_CONFIGURED" });
+ expect(service.isBusy("s1")).toBe(false);
+ });
+
+ it("never starts a runtime turn when the user row could not be appended", async () => {
+ const { host, sidecar, service } = build();
+ host.failAppend = true;
+ await expect(
+ service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner }),
+ ).rejects.toThrow("disk full");
+ expect(sidecar.calls.some((call) => call.method === "agent.prompt")).toBe(false);
+ expect(host.calls.find((call) => call.method === "session.endTurn")?.params).toMatchObject({ status: "error" });
+ });
+
+ it("records an abort before the cancel request so a late agent_end cannot restate it as completed", async () => {
+ const { host, sidecar, service, ended } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ await service.abort("s1");
+ expect(sidecar.calls.some((call) => call.method === "agent.abort")).toBe(true);
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-1", ts: 1, event: { type: "agent_end", messageIds: [] } });
+ await settle();
+ const ends = host.calls.filter((call) => call.method === "session.endTurn");
+ expect(ends).toHaveLength(1);
+ expect(ends[0]?.params).toMatchObject({ status: "aborted", errorCode: "TURN_ABORTED" });
+ expect(ended).toHaveLength(1);
+ expect(ended[0]?.reason).toBe("aborted");
+ });
+
+ it("ignores a terminal event that names a turn which no longer owns the session", async () => {
+ const { host, sidecar, service, events } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ events.length = 0;
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-0", ts: 1, event: { type: "agent_end", messageIds: [] } });
+ sidecar.notify?.("agent.event", { sessionId: "s1", ts: 1, event: { type: "agent_end", messageIds: [] } });
+ await settle();
+ expect(events).toHaveLength(0);
+ expect(host.calls.some((call) => call.method === "session.endTurn")).toBe(false);
+ expect(service.isBusy("s1")).toBe(true);
+ });
+
+ it("persists completed assistant and tool rows under the owning turn", async () => {
+ const { host, sidecar, service } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ const assistant: UiMessage = { id: "a1", role: "assistant", content: "done", createdAt: "2026-09-18T00:00:00.000Z", status: "complete" };
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-1", ts: 1, event: { type: "tool_start", toolCallId: "c1", toolName: "Read", args: { path: "a" } } });
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-1", ts: 2, event: { type: "tool_end", toolCallId: "c1", result: "ok" } });
+ sidecar.notify?.("agent.event", { sessionId: "s1", turnId: "turn-1", ts: 3, event: { type: "message_end", message: assistant } });
+ await settle();
+ const appended = host.calls.filter((call) => call.method === "session.appendMessage").map((call) => call.params);
+ expect(appended.map((params) => (params.message as UiMessage).id)).toEqual([expect.any(String), "c1", "a1"]);
+ expect(appended[1]).toMatchObject({ turnId: "turn-1" });
+ expect((appended[1]!.message as UiMessage).toolName).toBe("Read");
+ expect(appended[2]).toMatchObject({ turnId: "turn-1" });
+ });
+
+ it("turns a host permission request into an agent event that names the asking delegate", async () => {
+ const { host, sidecar, service, events } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ sidecar.notify?.("agent.event", {
+ sessionId: "s1",
+ turnId: "turn-1",
+ ts: 1,
+ parentToolCallId: "task-1",
+ agentName: "reviewer",
+ event: { type: "tool_start", toolCallId: "c9", toolName: "Bash", args: {} },
+ });
+ events.length = 0;
+ host.notify?.("permissions.request", {
+ requestId: "req-1",
+ sessionId: "s1",
+ toolCallId: "c9",
+ toolName: "Bash",
+ argsPreview: "rm",
+ risk: "high",
+ reason: "shell",
+ });
+ expect(events).toHaveLength(1);
+ expect(events[0]?.turnId).toBe("turn-1");
+ expect(events[0]?.event).toMatchObject({
+ type: "tool_permission_request",
+ request: { requestId: "req-1", agentName: "reviewer", parentToolCallId: "task-1" },
+ });
+ });
+
+ it("settles every running turn as aborted when the sidecar dies", async () => {
+ const { host, sidecar, service, ended } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ sidecar.exit?.({ intentional: false, code: 1, signal: null });
+ await settle();
+ expect(host.calls.find((call) => call.method === "session.endTurn")?.params).toMatchObject({
+ status: "aborted",
+ recoverInflight: true,
+ });
+ expect(ended[0]?.reason).toBe("aborted");
+ expect(service.isBusy("s1")).toBe(false);
+ });
+
+ it("steers only the live turn and refuses once it ended", async () => {
+ const { sidecar, service } = build();
+ await service.prompt({ sessionId: "s1", content: "hello", effectivePermissionMode: "ask", principal: owner });
+ expect(await service.steer({ sessionId: "s1", turnId: "turn-1", content: "also", principal: owner })).toEqual({ accepted: true });
+ expect(sidecar.calls.at(-1)?.params).toMatchObject({ expectedTurnId: "turn-1", content: "also" });
+ expect(await service.steer({ sessionId: "s1", turnId: "turn-9", content: "no", principal: owner })).toEqual({ accepted: false });
+ });
+
+ it("refuses native Pi sessions and attachments the headless runtime cannot serve", async () => {
+ const { service } = build();
+ await expect(
+ service.prompt({ sessionId: "native-pi:x", content: "hi", effectivePermissionMode: "ask", principal: owner }),
+ ).rejects.toMatchObject({ errorCode: "NATIVE_PI_UNSUPPORTED" });
+ await expect(
+ service.prompt({
+ sessionId: "s1",
+ content: "hi",
+ attachments: [{ path: "/tmp/a.png", name: "a.png", kind: "image" }],
+ effectivePermissionMode: "ask",
+ principal: owner,
+ }),
+ ).rejects.toMatchObject({ errorCode: "INVALID_ARGUMENT" });
+ });
+});
diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.ts
new file mode 100644
index 000000000..78e2fedb8
--- /dev/null
+++ b/packages/host-runtime/src/runtime-service.ts
@@ -0,0 +1,646 @@
+import { randomUUID } from "node:crypto";
+
+import type { RuntimePort, TurnStartRequest, TurnSteerRequest } from "@pi-desktop/agent-host";
+import {
+ ErrorCodes,
+ type AgentEventEnvelope,
+ type AgentStatus,
+ type AskToolResolution,
+ type Risk,
+ type UiMessage,
+} from "@pi-desktop/shared";
+
+import type { LaunchResolver } from "./launch-resolver.js";
+import { resolveSessionMessageInput } from "./session-message-input.js";
+import { TurnEventPipeline } from "./turn-events.js";
+
+/** host-core as the turn lifecycle drives it. `HostProcess` satisfies it. */
+export type RuntimeHostLink = {
+ call<T = unknown>(method: string, params?: unknown): Promise<T>;
+ isAvailable(): boolean;
+ onNotification(handler: (method: string, params: unknown) => void): () => void;
+ onExit(handler: (info: { intentional: boolean }) => void): () => void;
+};
+
+/** The agent sidecar as the turn lifecycle drives it. `AgentSidecar` satisfies it. */
+export type RuntimeSidecarLink = {
+ call<T = unknown>(method: string, params?: unknown): Promise<T>;
+ onNotification(handler: (method: string, params: unknown) => void): () => void;
+ onExit(handler: (info: { intentional: boolean; code: number | null; signal: NodeJS.Signals | null }) => void): () => void;
+ setProjectInstructionRoot(sessionId: string, projectPath?: string): void;
+ clearProjectInstructionRoot(sessionId: string): void;
+ clearVendorAuthBindings(sessionId: string): void;
+};
+
+/**
+ * Terminal state of one host turn. `aborted` is reserved for a turn the host
+ * cancelled; a graceful stop still ends as `completed` (the runtime owns that
+ * boundary decision), and `error` covers a failed turn.
+ */
+export type TurnEndReason = "completed" | "aborted" | "error";
+
+export type TurnEndedInfo = {
+ sessionId: string;
+ turnId: string;
+ reason: TurnEndReason;
+ errorCode?: string;
+ /** Whether host-core acknowledged the durable end of this turn. */
+ settled: boolean;
+};
+
+export type RuntimeLogger = (
+ level: "info" | "warn" | "error",
+ message: string,
+ data?: Record<string, unknown>,
+) => void;
+
+export type RuntimeServiceOptions = {
+ getHost: () => RuntimeHostLink | null;
+ getSidecar: () => RuntimeSidecarLink | null;
+ launch: LaunchResolver;
+ log: RuntimeLogger;
+ now?: () => number;
+ /**
+ * Rewrite the prompt text before it is persisted and sent, e.g. slash
+ * command expansion. Returns `null` to keep the text as typed.
+ */
+ expandPrompt?: (input: {
+ sessionId: string;
+ content: string;
+ projectPath?: string;
+ }) => Promise<{ content: string; command?: string } | null>;
+ checkpointIntervalMs?: number;
+};
+
+type FinishTurnOptions = { turnId: string; recoverInflight?: boolean };
+
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** Keep the renderer-chosen id when it is a UUID the session does not hold (D288). */
+export function durableUserMessageId(
+ requested: unknown,
+ existing: ReadonlyArray<{ id?: unknown }>,
+): string {
+ if (typeof requested === "string" && UUID_PATTERN.test(requested) && !existing.some((message) => message?.id === requested)) {
+ return requested;
+ }
+ return randomUUID();
+}
+
+function typedError(message: string, errorCode: string): Error {
+ return Object.assign(new Error(message), { errorCode });
+}
+
+function errorCodeOf(error: unknown): string | undefined {
+ const candidate = error as { data?: { errorCode?: unknown }; errorCode?: unknown } | null;
+ const nested = candidate?.data?.errorCode;
+ if (typeof nested === "string") return nested;
+ return typeof candidate?.errorCode === "string" ? candidate.errorCode : undefined;
+}
+
+/**
+ * The turn lifecycle of a headless Host: prompt admission, the durable turn
+ * row, turn ownership and finalization, and the runtime control calls the
+ * Agent Host module needs (`RuntimePort`). It knows host-core and the sidecar
+ * only through their stdio links, so it runs wherever those two processes
+ * run; the per-event persistence pass lives in `TurnEventPipeline`.
+ */
+export class RuntimeService implements RuntimePort {
+ private readonly activeTurns = new Map<string, string>();
+ private readonly turnFinalizations = new Map<string, Promise<void>>();
+ private readonly pendingAbortReasons = new Map<string, TurnEndReason>();
+ private readonly sessionOperations = new Map<string, Promise<void>>();
+ private readonly listeners = new Set<(envelope: AgentEventEnvelope) => void>();
+ private readonly turnEndListeners = new Set<(info: TurnEndedInfo) => void>();
+ private readonly events: TurnEventPipeline;
+ private readonly detachers: Array<() => void> = [];
+ private readonly now: () => number;
+ private disposed = false;
+
+ constructor(private readonly options: RuntimeServiceOptions) {
+ this.now = options.now ?? (() => Date.now());
+ this.events = new TurnEventPipeline({
+ getHost: () => options.getHost(),
+ ownership: {
+ activeTurnId: (sessionId) => this.activeTurns.get(sessionId),
+ isStaleTerminalEvent: (envelope) => this.isStaleTerminalEvent(envelope),
+ finishTurn: (sessionId, status, errorCode, finishOptions) =>
+ this.finishTurn(sessionId, status, errorCode, finishOptions),
+ },
+ emit: (envelope) => this.emit(envelope),
+ log: options.log,
+ now: this.now,
+ checkpointIntervalMs: options.checkpointIntervalMs,
+ });
+ }
+
+ // -------------------------------------------------------------------------
+ // Wiring
+ // -------------------------------------------------------------------------
+
+ /** Observe a (re)started host-core: permission requests become agent events. */
+ attachHost(host: RuntimeHostLink): void {
+ const off = host.onNotification((method, params) => {
+ if (this.options.getHost() !== host) return;
+ if (method !== "permissions.request") return;
+ const permission = params as {
+ requestId: string;
+ sessionId: string;
+ toolCallId: string;
+ toolName: string;
+ argsPreview: string;
+ risk: Risk;
+ reason: string;
+ };
+ // A delegate's call is already tracked by the time the host asks: the
+ // sidecar forwards tool_start before it executes the tool.
+ const asking = this.events.toolCall(permission.sessionId, permission.toolCallId);
+ const turnId = asking?.turnId ?? this.activeTurns.get(permission.sessionId);
+ this.options.log("info", "permission requested", {
+ requestId: permission.requestId,
+ sessionId: permission.sessionId,
+ turnId,
+ toolCallId: permission.toolCallId,
+ toolName: permission.toolName,
+ risk: permission.risk,
+ });
+ this.emit({
+ sessionId: permission.sessionId,
+ ...(turnId ? { turnId } : {}),
+ ts: this.now(),
+ event: {
+ type: "tool_permission_request",
+ request: {
+ requestId: permission.requestId,
+ sessionId: permission.sessionId,
+ toolCallId: permission.toolCallId,
+ toolName: permission.toolName,
+ argsPreview: permission.argsPreview,
+ risk: permission.risk,
+ reason: permission.reason,
+ ...(asking?.agentName ? { agentName: asking.agentName } : {}),
+ ...(asking?.parentToolCallId ? { parentToolCallId: asking.parentToolCallId } : {}),
+ },
+ },
+ });
+ });
+ this.detachers.push(off);
+ }
+
+ /** Observe a (re)started sidecar: its agent events feed the lifecycle. */
+ attachSidecar(sidecar: RuntimeSidecarLink): void {
+ const offEvents = sidecar.onNotification((method, params) => {
+ if (this.options.getSidecar() !== sidecar) return;
+ if (method !== "agent.event") return;
+ this.events.handle(params as AgentEventEnvelope);
+ });
+ const offExit = sidecar.onExit(({ intentional, code, signal }) => {
+ if (this.options.getSidecar() !== sidecar) return;
+ const interrupted = this.events.onSidecarExit();
+ if (intentional || this.disposed) return;
+ for (const tool of interrupted) {
+ this.options.log("error", "tool execution interrupted", {
+ sessionId: tool.sessionId,
+ turnId: tool.turnId,
+ toolCallId: tool.toolCallId,
+ toolName: tool.toolName,
+ reason: "agent_sidecar_exit",
+ exitCode: code,
+ signal,
+ });
+ }
+ for (const sessionId of [...this.activeTurns.keys()]) {
+ const crashedTurnId = this.activeTurns.get(sessionId);
+ if (!crashedTurnId) continue;
+ void this.settleCrashedSession(sessionId, crashedTurnId).catch((error: unknown) => {
+ this.options.log("warn", "crashed-turn settlement failed", { sessionId, error: String(error) });
+ });
+ }
+ });
+ this.detachers.push(offEvents, offExit);
+ }
+
+ onEvent(listener: (envelope: AgentEventEnvelope) => void): () => void {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ }
+
+ onTurnEnded(listener: (info: TurnEndedInfo) => void): () => void {
+ this.turnEndListeners.add(listener);
+ return () => this.turnEndListeners.delete(listener);
+ }
+
+ /** Transcript rows still waiting for host-core. */
+ pendingWrites(): number {
+ return this.events.pendingWrites();
+ }
+
+ async dispose(): Promise<void> {
+ this.disposed = true;
+ for (const detach of this.detachers.splice(0)) detach();
+ await this.events.dispose();
+ this.listeners.clear();
+ this.turnEndListeners.clear();
+ }
+
+ // -------------------------------------------------------------------------
+ // RuntimePort
+ // -------------------------------------------------------------------------
+
+ async prompt(request: TurnStartRequest): Promise<{ turnId: string }> {
+ const sessionId = request.sessionId.trim();
+ if (!sessionId) throw typedError("sessionId required", ErrorCodes.INVALID_ARGUMENT);
+ if (sessionId.startsWith("native-pi:")) {
+ throw typedError("Native Pi sessions are not available on a headless host", "NATIVE_PI_UNSUPPORTED");
+ }
+ if (request.attachments?.length) {
+ throw typedError("Prompt attachments are not supported by the headless runtime yet", ErrorCodes.INVALID_ARGUMENT);
+ }
+ try {
+ return await this.withSessionOperation(sessionId, () => this.startTurn(sessionId, request));
+ } catch (error) {
+ if (request.sessionMessageId) {
+ const host = this.options.getHost();
+ await host
+ ?.call("session.collaboration.fail", {
+ messageId: request.sessionMessageId,
+ error: error instanceof Error ? error.message : String(error),
+ })
+ .catch((persistenceError: unknown) => {
+ this.options.log("warn", "collaboration dispatch failure persistence failed", {
+ sessionId,
+ messageId: request.sessionMessageId,
+ error: String(persistenceError),
+ });
+ });
+ }
+ throw error;
+ }
+ }
+
+ private async startTurn(sessionId: string, request: TurnStartRequest): Promise<{ turnId: string }> {
+ const host = this.requireHost();
+ const sidecar = this.requireSidecar();
+ const sessionMessage = await resolveSessionMessageInput(host, {
+ sessionId,
+ ...(request.sessionMessageId !== undefined ? { sessionMessageId: request.sessionMessageId } : {}),
+ });
+ const settings = await host.call<Record<string, unknown>>("settings.get");
+ const detail = await host.call<{ session?: Record<string, unknown> | null }>("session.get", {
+ id: sessionId,
+ messageLimit: 1,
+ });
+ const session = detail.session;
+ if (!session) throw typedError("Session not found", ErrorCodes.NOT_FOUND);
+ if (this.activeTurns.has(sessionId)) {
+ throw typedError("Session already has an active turn", ErrorCodes.AGENT_BUSY);
+ }
+ const launch = await this.options.launch.resolve(sessionId, session, settings ?? {});
+ sidecar.setProjectInstructionRoot(sessionId, launch.projectPath);
+
+ const turnId = await this.beginTurn(sessionId, launch.providerId, launch.modelId, sessionMessage?.origin.messageId);
+
+ let content = sessionMessage?.content ?? request.content;
+ let command: string | undefined;
+ if (!sessionMessage && this.options.expandPrompt && content.startsWith("/")) {
+ try {
+ const expanded = await this.options.expandPrompt({ sessionId, content, projectPath: launch.projectPath });
+ if (expanded) {
+ content = expanded.content;
+ command = expanded.command;
+ }
+ } catch (error) {
+ this.options.log("warn", "slash expansion failed; sending literal text", { sessionId, error: String(error) });
+ }
+ }
+ const existing = Array.isArray(session.messages) ? (session.messages as Array<{ id?: unknown }>) : [];
+ const userMessage: UiMessage = {
+ id: durableUserMessageId(request.userMessageId, existing),
+ role: "user",
+ content,
+ ...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),
+ createdAt: new Date(this.now()).toISOString(),
+ status: "complete",
+ ...(command ? { command } : {}),
+ };
+ try {
+ await host.call("session.appendMessage", { sessionId, message: userMessage, turnId });
+ } catch (error) {
+ await this.finishTurn(sessionId, "error", errorCodeOf(error), { turnId });
+ // A turn whose user message could not be appended must not be started:
+ // running it would execute a prompt the transcript does not contain.
+ throw error;
+ }
+ this.emit({ sessionId, turnId, ts: this.now(), event: { type: "message_start", message: userMessage } });
+ this.emit({ sessionId, turnId, ts: this.now(), event: { type: "message_end", message: userMessage } });
+
+ let result: { accepted: boolean; turnId: string };
+ try {
+ result = await sidecar.call<{ accepted: boolean; turnId: string }>("agent.prompt", {
+ ...launch.sidecarParams,
+ // The host-created durable turn is the approval identity used by
+ // Rust. The runtime must not replace it with a provider-local UUID.
+ turnId,
+ content,
+ ...(sessionMessage ? { sessionMessage: sessionMessage.origin } : {}),
+ attachments: [],
+ userMessageId: userMessage.id,
+ });
+ } catch (error) {
+ await this.finishTurn(sessionId, "error", errorCodeOf(error), { turnId });
+ throw error;
+ }
+ this.options.log("info", "prompt accepted", {
+ sessionId,
+ turnId: result.turnId,
+ providerId: launch.providerId,
+ modelId: launch.modelId,
+ });
+ return { turnId };
+ }
+
+ async steer(request: TurnSteerRequest): Promise<{ accepted: boolean }> {
+ const sessionId = request.sessionId.trim();
+ if (!this.isTurnDispatchable(sessionId, request.turnId)) return { accepted: false };
+ try {
+ const host = this.requireHost();
+ const sidecar = this.requireSidecar();
+ await sidecar.call("agent.steeringContext", { sessionId, expectedTurnId: request.turnId });
+ const detail = await host.call<{ session?: { messages?: UiMessage[] } }>("session.get", {
+ id: sessionId,
+ messageLimit: 1,
+ });
+ const message: UiMessage = {
+ id: durableUserMessageId(request.sessionMessageId, detail.session?.messages ?? []),
+ role: "user",
+ content: request.content,
+ status: "complete",
+ createdAt: new Date(this.now()).toISOString(),
+ steering: true,
+ };
+ const result = await sidecar.call<{ accepted?: boolean }>("agent.steer", {
+ sessionId,
+ expectedTurnId: request.turnId,
+ message,
+ content: request.content,
+ attachments: [],
+ });
+ return { accepted: result?.accepted !== false };
+ } catch (error) {
+ this.options.log("warn", "steer failed", { sessionId, turnId: request.turnId, error: String(error) });
+ return { accepted: false };
+ }
+ }
+
+ async stop(sessionId: string): Promise<{ requested: boolean }> {
+ const sidecar = this.requireSidecar();
+ this.options.log("info", "prompt graceful stop requested", { sessionId });
+ // The runtime owns the boundary decision: agent_end arrives after the
+ // current reply/tool batch completes and finishes it as a completed turn.
+ const result = await sidecar.call<{ requested?: boolean }>("agent.stop", { sessionId });
+ return { requested: result?.requested ?? false };
+ }
+
+ async abort(sessionId: string, turnId?: string): Promise<void> {
+ const sidecar = this.requireSidecar();
+ const abortedTurnId = this.activeTurns.get(sessionId);
+ if (turnId && abortedTurnId !== turnId) return;
+ this.options.log("info", "prompt aborted", { sessionId });
+ // Lock the abort reason before the first await: the cancel RPC can take a
+ // while, and a terminal event arriving in that window must not settle the
+ // turn as completed.
+ this.lockAbortReason(sessionId, abortedTurnId);
+ try {
+ await sidecar.call("agent.abort", { sessionId, ...(turnId ? { turnId } : {}) });
+ } finally {
+ if (abortedTurnId) {
+ await this.finishTurn(sessionId, "aborted", "TURN_ABORTED", { turnId: abortedTurnId });
+ }
+ }
+ }
+
+ async respondInput(resolution: AskToolResolution): Promise<void> {
+ const sessionId = String(resolution.sessionId ?? "").trim();
+ const requestId = String(resolution.requestId ?? "").trim();
+ if (!sessionId || !requestId) throw typedError("asktool resolution identity required", ErrorCodes.INVALID_ARGUMENT);
+ await this.requireSidecar().call("asktool.resolve", { ...resolution, sessionId, requestId });
+ }
+
+ /** Manual context checkpoint on an idle session. */
+ async compact(sessionId: string): Promise<{ accepted: boolean }> {
+ if (this.activeTurns.has(sessionId)) throw typedError("Session already has an active turn", ErrorCodes.AGENT_BUSY);
+ const host = this.requireHost();
+ const sidecar = this.requireSidecar();
+ const settings = await host.call<Record<string, unknown>>("settings.get");
+ const detail = await host.call<{ session?: Record<string, unknown> | null }>("session.get", { id: sessionId });
+ if (!detail.session) throw typedError("Session not found", ErrorCodes.NOT_FOUND);
+ const launch = await this.options.launch.resolve(sessionId, detail.session, settings ?? {});
+ sidecar.setProjectInstructionRoot(sessionId, launch.projectPath);
+ const result = await sidecar.call<{ accepted?: boolean }>("agent.compact", launch.sidecarParams);
+ return { accepted: result?.accepted !== false };
+ }
+
+ async getStatus(sessionId: string): Promise<AgentStatus> {
+ const result = await this.requireSidecar().call<{ status?: AgentStatus }>("agent.getStatus", { sessionId });
+ return result?.status ?? { sessionId, isRunning: false, pendingToolConfirmations: 0 };
+ }
+
+ isBusy(sessionId: string): boolean {
+ const id = sessionId.trim();
+ if (!id) return false;
+ if (this.activeTurns.has(id)) return true;
+ const prefix = `${id}:`;
+ for (const key of this.turnFinalizations.keys()) {
+ if (key.startsWith(prefix)) return true;
+ }
+ return false;
+ }
+
+ activeTurnId(sessionId: string): string | undefined {
+ return this.activeTurns.get(sessionId);
+ }
+
+ // -------------------------------------------------------------------------
+ // Turn ownership
+ // -------------------------------------------------------------------------
+
+ /** Serialize turn admission and abort per session. */
+ async withSessionOperation<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
+ const id = sessionId.trim();
+ const previous = this.sessionOperations.get(id) ?? Promise.resolve();
+ const result = previous.then(operation);
+ const settled = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ this.sessionOperations.set(id, settled);
+ try {
+ return await result;
+ } finally {
+ if (this.sessionOperations.get(id) === settled) this.sessionOperations.delete(id);
+ }
+ }
+
+ /** Open a durable turn row and take ownership of the session for it. */
+ async beginTurn(sessionId: string, providerId: string, modelId: string, sessionMessageId?: string): Promise<string> {
+ const turn = await this.requireHost().call<{ turnId?: string }>("session.beginTurn", {
+ sessionId,
+ providerId,
+ modelId,
+ ...(sessionMessageId ? { sessionMessageId } : {}),
+ });
+ const turnId = String(turn?.turnId ?? "").trim();
+ if (!turnId) throw new Error("session.beginTurn returned no turn");
+ this.activeTurns.set(sessionId, turnId);
+ this.events.resetTurnUsage(sessionId);
+ return turnId;
+ }
+
+ private isActiveTurn(sessionId: string, turnId: string | null | undefined): boolean {
+ if (typeof turnId !== "string") return false;
+ const id = sessionId.trim();
+ const turn = turnId.trim();
+ if (!id || !turn) return false;
+ return this.activeTurns.get(id) === turn;
+ }
+
+ private isTurnDispatchable(sessionId: string, turnId: string | null | undefined): boolean {
+ if (!this.isActiveTurn(sessionId, turnId)) return false;
+ const key = turnKey(sessionId.trim(), String(turnId).trim());
+ return !this.pendingAbortReasons.has(key) && !this.turnFinalizations.has(key);
+ }
+
+ private lockAbortReason(sessionId: string, turnId: string | null | undefined): void {
+ if (!this.isActiveTurn(sessionId, turnId)) return;
+ this.pendingAbortReasons.set(turnKey(sessionId.trim(), String(turnId).trim()), "aborted");
+ }
+
+ private isStaleTerminalEvent(envelope: AgentEventEnvelope): boolean {
+ const type = envelope.event.type;
+ if (type !== "agent_end" && type !== "error") return false;
+ // A delegate's terminal event settles the delegate, never its parent's turn.
+ if (envelope.parentToolCallId) return true;
+ return !this.isActiveTurn(envelope.sessionId, envelope.turnId);
+ }
+
+ /**
+ * Settle one host turn: attempt its durable end, release local ownership,
+ * then announce it. Ownership is claimed and the terminal reason frozen
+ * synchronously, before any await, so a concurrent terminal event joins this
+ * finalization instead of starting a second one, and a cancellation recorded
+ * earlier cannot be restated as a completion later.
+ */
+ finishTurn(
+ sessionId: string,
+ status: TurnEndReason,
+ errorCode: string | undefined,
+ options: FinishTurnOptions,
+ ): Promise<void> {
+ const id = sessionId.trim();
+ const turnId = String(options.turnId ?? "").trim();
+ if (!id || !turnId) return Promise.resolve();
+ const key = turnKey(id, turnId);
+ const existing = this.turnFinalizations.get(key);
+ if (existing) return existing;
+ if (!this.isActiveTurn(id, turnId)) {
+ this.pendingAbortReasons.delete(key);
+ return Promise.resolve();
+ }
+ const reason = this.pendingAbortReasons.get(key) ?? status;
+ const turnUsage = this.events.takeTurnUsage(id);
+ const recoverInflight = options.recoverInflight === true;
+ let settled = false;
+
+ const run = async (): Promise<void> => {
+ try {
+ const host = this.options.getHost();
+ if (host) {
+ try {
+ const result = await host.call<{ ok: boolean; recovered?: UiMessage }>("session.endTurn", {
+ turnId,
+ status: reason,
+ errorCode,
+ createNotification: false,
+ ...(turnUsage ? { usage: turnUsage } : {}),
+ ...(recoverInflight ? { recoverInflight: true } : {}),
+ });
+ settled = true;
+ if (result.recovered) {
+ this.emit({ sessionId: id, turnId, ts: this.now(), event: { type: "message_end", message: result.recovered } });
+ }
+ } catch (error) {
+ this.options.log("warn", "endTurn failed", { sessionId: id, turnId, error: String(error) });
+ }
+ }
+ } finally {
+ if (this.activeTurns.get(id) === turnId) this.activeTurns.delete(id);
+ this.events.scheduleToolCallCleanup(id, turnId);
+ }
+ };
+ const release = (): void => {
+ if (this.turnFinalizations.get(key) !== record) return;
+ this.turnFinalizations.delete(key);
+ this.pendingAbortReasons.delete(key);
+ const info: TurnEndedInfo = { sessionId: id, turnId, reason, ...(errorCode ? { errorCode } : {}), settled };
+ for (const listener of this.turnEndListeners) {
+ try {
+ listener(info);
+ } catch (error) {
+ this.options.log("warn", "turn end listener failed", { sessionId: id, turnId, error: String(error) });
+ }
+ }
+ };
+ const record: Promise<void> = Promise.resolve().then(run).finally(release);
+ this.turnFinalizations.set(key, record);
+ return record;
+ }
+
+ private async settleCrashedSession(sessionId: string, crashedTurnId: string): Promise<void> {
+ const host = this.options.getHost();
+ if (host) await host.call("plans.abort", { sessionId }).catch(() => undefined);
+ if (this.activeTurns.get(sessionId) !== crashedTurnId) return;
+ // No final row is coming from a dead sidecar: keep whatever the reply had
+ // streamed so far as an aborted transcript row (D299).
+ await this.events.flushCheckpoint(sessionId);
+ if (this.activeTurns.get(sessionId) !== crashedTurnId) return;
+ this.events.settleCheckpoint(sessionId);
+ await this.finishTurn(sessionId, "aborted", "PLAN_APPROVAL_INTERRUPTED", {
+ turnId: crashedTurnId,
+ recoverInflight: true,
+ });
+ }
+
+ // -------------------------------------------------------------------------
+ // Events
+ // -------------------------------------------------------------------------
+
+ private emit(envelope: AgentEventEnvelope): void {
+ for (const listener of this.listeners) {
+ try {
+ listener(envelope);
+ } catch (error) {
+ this.options.log("warn", "agent event listener failed", {
+ sessionId: envelope.sessionId,
+ type: envelope.event.type,
+ error: String(error),
+ });
+ }
+ }
+ }
+
+ private requireHost(): RuntimeHostLink {
+ const host = this.options.getHost();
+ if (!host) throw typedError("host unavailable", ErrorCodes.HOST_UNAVAILABLE);
+ return host;
+ }
+
+ private requireSidecar(): RuntimeSidecarLink {
+ const sidecar = this.options.getSidecar();
+ if (!sidecar) throw typedError("sidecar unavailable", ErrorCodes.AGENT_UNAVAILABLE);
+ return sidecar;
+ }
+}
+
+function turnKey(sessionId: string, turnId: string): string {
+ return `${sessionId}:${turnId}`;
+}
diff --git a/packages/host-runtime/src/runtime-supervisor.test.ts b/packages/host-runtime/src/runtime-supervisor.test.ts
new file mode 100644
index 000000000..ff1de1e7e
--- /dev/null
+++ b/packages/host-runtime/src/runtime-supervisor.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from "vitest";
+
+import { DEFAULT_RESTART_POLICY, RuntimeSupervisor, type SupervisorEvent } from "./runtime-supervisor.js";
+
+function harness(options: {
+ hostStarts?: Array<() => Promise<void>>;
+ isUnrecoverable?: (error: unknown) => boolean;
+ shuttingDown?: () => boolean;
+ now?: () => number;
+} = {}) {
+ const events: SupervisorEvent[] = [];
+ const sleeps: number[] = [];
+ const starts = { host: 0, sidecar: 0 };
+ const hostStarts = options.hostStarts ?? [];
+ const supervisor = new RuntimeSupervisor({
+ start: {
+ host: async () => {
+ const index = starts.host;
+ starts.host += 1;
+ const step = hostStarts[index];
+ if (step) await step();
+ },
+ sidecar: async () => {
+ starts.sidecar += 1;
+ },
+ },
+ isUnrecoverable: options.isUnrecoverable,
+ isShuttingDown: options.shuttingDown,
+ onEvent: (event) => events.push(event),
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ },
+ now: options.now ?? (() => 1_000),
+ });
+ return { supervisor, events, sleeps, starts };
+}
+
+describe("RuntimeSupervisor", () => {
+ it("restarts with the documented exponential backoff and reports success", async () => {
+ const { supervisor, events, sleeps, starts } = harness();
+ await supervisor.superviseRestart("sidecar");
+ expect(starts.sidecar).toBe(1);
+ expect(sleeps).toEqual([DEFAULT_RESTART_POLICY.baseDelayMs]);
+ expect(events.map((event) => event.phase)).toEqual(["restarting", "restarted"]);
+ });
+
+ it("keeps retrying with a capped delay until the child comes back", async () => {
+ const failing = () => Promise.reject(new Error("still down"));
+ const { supervisor, events, sleeps, starts } = harness({
+ hostStarts: [failing, failing, async () => undefined],
+ });
+ await supervisor.superviseRestart("host");
+ expect(starts.host).toBe(3);
+ expect(sleeps).toEqual([500, 1000, 2000]);
+ expect(events.filter((event) => event.phase === "restart_failed")).toHaveLength(2);
+ expect(events.at(-1)?.phase).toBe("restarted");
+ expect(supervisor.delayForAttempt(10)).toBe(DEFAULT_RESTART_POLICY.maxDelayMs);
+ });
+
+ it("gives up after the per-window budget and reports a fatal limit", async () => {
+ const failing = () => Promise.reject(new Error("still down"));
+ const { supervisor, events, starts } = harness({
+ hostStarts: [failing, failing, failing, failing],
+ });
+ await supervisor.superviseRestart("host");
+ expect(starts.host).toBe(DEFAULT_RESTART_POLICY.maxRestartsPerWindow);
+ expect(events.at(-1)).toEqual({ kind: "host", phase: "fatal", reason: "limit" });
+ });
+
+ it("resets the budget once the window elapsed", async () => {
+ let clock = 0;
+ const failing = () => Promise.reject(new Error("still down"));
+ const { supervisor, events } = harness({
+ hostStarts: [failing, failing, failing, failing, failing, async () => undefined],
+ now: () => clock,
+ });
+ await supervisor.superviseRestart("host");
+ expect(events.at(-1)?.phase).toBe("fatal");
+ clock = DEFAULT_RESTART_POLICY.windowMs + 1;
+ events.length = 0;
+ await supervisor.superviseRestart("host");
+ // A fresh window admits three more attempts; the third one succeeds.
+ expect(events.filter((event) => event.phase === "restarting")).toHaveLength(3);
+ expect(events.at(-1)?.phase).toBe("restarted");
+ });
+
+ it("stops on the first unrecoverable failure instead of burning the budget", async () => {
+ const refusal = Object.assign(new Error("schema too new"), { fatal: true });
+ const { supervisor, events, starts } = harness({
+ hostStarts: [() => Promise.reject(refusal), async () => undefined],
+ isUnrecoverable: (error) => (error as { fatal?: boolean })?.fatal === true,
+ });
+ await supervisor.superviseRestart("host");
+ expect(starts.host).toBe(1);
+ expect(events.at(-1)).toEqual({ kind: "host", phase: "fatal", reason: "unrecoverable", error: refusal });
+ });
+
+ it("joins a concurrent request for the same child and never restarts during shutdown", async () => {
+ let shuttingDown = false;
+ const { supervisor, starts, events } = harness({ shuttingDown: () => shuttingDown });
+ const first = supervisor.superviseRestart("sidecar");
+ const second = supervisor.superviseRestart("sidecar");
+ expect(second).toBe(first);
+ await first;
+ expect(starts.sidecar).toBe(1);
+ shuttingDown = true;
+ await supervisor.superviseRestart("sidecar");
+ expect(starts.sidecar).toBe(1);
+ expect(events.filter((event) => event.phase === "restarting")).toHaveLength(1);
+ });
+});
diff --git a/packages/host-runtime/src/runtime-supervisor.ts b/packages/host-runtime/src/runtime-supervisor.ts
new file mode 100644
index 000000000..a2e9e1cd4
--- /dev/null
+++ b/packages/host-runtime/src/runtime-supervisor.ts
@@ -0,0 +1,134 @@
+/**
+ * Restart supervision for the two runtime children (host-core, agent sidecar).
+ *
+ * The policy is the one Electron Main has always applied (spec 07 §4):
+ * exponential backoff `0.5s → 1s → 2s` capped at 4s, at most three restarts
+ * per two-minute window per child, single-flight per child, and never after
+ * shutdown began. The supervisor owns only the loop; how a child is started,
+ * what happens after it came back, and how an outcome is reported belong to
+ * the embedding host, so Electron Main and the headless `pi-host` share one
+ * implementation of the policy without sharing their renderer or logger.
+ */
+export type SupervisedKind = "host" | "sidecar";
+
+export type RestartPolicy = {
+ /** Restarts allowed inside one window before the child is declared fatal. */
+ maxRestartsPerWindow: number;
+ windowMs: number;
+ baseDelayMs: number;
+ maxDelayMs: number;
+};
+
+export const DEFAULT_RESTART_POLICY: RestartPolicy = {
+ maxRestartsPerWindow: 3,
+ windowMs: 120_000,
+ baseDelayMs: 500,
+ maxDelayMs: 4_000,
+};
+
+export type SupervisorEvent =
+ | { kind: SupervisedKind; phase: "restarting"; attempt: number; delayMs: number }
+ | { kind: SupervisedKind; phase: "restart_failed"; attempt: number; error: unknown }
+ | { kind: SupervisedKind; phase: "restarted"; attempt: number }
+ | { kind: SupervisedKind; phase: "fatal"; reason: "limit" | "unrecoverable"; error?: unknown };
+
+export type RuntimeSupervisorOptions = {
+ /** Start (or restart) one child and leave it wired; rejects when it cannot come up. */
+ start: Record<SupervisedKind, () => Promise<void>>;
+ /** Runs after a successful start inside the same attempt; a failure counts as a failed restart. */
+ afterRestart?: (kind: SupervisedKind) => Promise<void> | void;
+ /**
+ * True when an error means the child can never come back on its own (a data
+ * directory newer than the build, an unsupported glibc). The loop stops on
+ * the first such failure instead of burning the restart budget.
+ */
+ isUnrecoverable?: (error: unknown) => boolean;
+ isShuttingDown?: () => boolean;
+ onEvent?: (event: SupervisorEvent) => void;
+ policy?: Partial<RestartPolicy>;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+};
+
+type WindowState = { count: number; windowStart: number };
+
+export class RuntimeSupervisor {
+ private readonly policy: RestartPolicy;
+ private readonly windows: Record<SupervisedKind, WindowState> = {
+ host: { count: 0, windowStart: 0 },
+ sidecar: { count: 0, windowStart: 0 },
+ };
+ private readonly inFlight: Record<SupervisedKind, Promise<void> | null> = {
+ host: null,
+ sidecar: null,
+ };
+ private readonly sleep: (ms: number) => Promise<void>;
+ private readonly now: () => number;
+
+ constructor(private readonly options: RuntimeSupervisorOptions) {
+ this.policy = { ...DEFAULT_RESTART_POLICY, ...options.policy };
+ this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
+ this.now = options.now ?? (() => Date.now());
+ }
+
+ /** Bring one child back. Concurrent calls for the same child join the running loop. */
+ superviseRestart(kind: SupervisedKind): Promise<void> {
+ const existing = this.inFlight[kind];
+ if (existing) return existing;
+ const run = this.loop(kind).finally(() => {
+ if (this.inFlight[kind] === run) this.inFlight[kind] = null;
+ });
+ this.inFlight[kind] = run;
+ return run;
+ }
+
+ /** The delay before restart attempt `attempt` (1-based) under the policy. */
+ delayForAttempt(attempt: number): number {
+ return Math.min(this.policy.baseDelayMs * 2 ** (attempt - 1), this.policy.maxDelayMs);
+ }
+
+ private shuttingDown(): boolean {
+ return this.options.isShuttingDown?.() ?? false;
+ }
+
+ private emit(event: SupervisorEvent): void {
+ try {
+ this.options.onEvent?.(event);
+ } catch {
+ // A reporting failure must not stop the child from coming back.
+ }
+ }
+
+ private async loop(kind: SupervisedKind): Promise<void> {
+ const state = this.windows[kind];
+ while (!this.shuttingDown()) {
+ const now = this.now();
+ if (now - state.windowStart > this.policy.windowMs) {
+ state.windowStart = now;
+ state.count = 0;
+ }
+ state.count += 1;
+ if (state.count > this.policy.maxRestartsPerWindow) {
+ this.emit({ kind, phase: "fatal", reason: "limit" });
+ return;
+ }
+ const attempt = state.count;
+ const delayMs = this.delayForAttempt(attempt);
+ this.emit({ kind, phase: "restarting", attempt, delayMs });
+ await this.sleep(delayMs);
+ if (this.shuttingDown()) return;
+ try {
+ await this.options.start[kind]();
+ await this.options.afterRestart?.(kind);
+ this.emit({ kind, phase: "restarted", attempt });
+ return;
+ } catch (error) {
+ if (this.options.isUnrecoverable?.(error)) {
+ this.emit({ kind, phase: "fatal", reason: "unrecoverable", error });
+ return;
+ }
+ this.emit({ kind, phase: "restart_failed", attempt, error });
+ }
+ }
+ }
+}
diff --git a/apps/desktop/electron/main/session-message-input.ts b/packages/host-runtime/src/session-message-input.ts
similarity index 88%
rename from apps/desktop/electron/main/session-message-input.ts
rename to packages/host-runtime/src/session-message-input.ts
index b2c7b5970..c23e3b357 100644
--- a/apps/desktop/electron/main/session-message-input.ts
+++ b/packages/host-runtime/src/session-message-input.ts
@@ -14,10 +14,16 @@ export type SessionMessageInput = {
origin: SessionMessageOrigin;
};
+/** The subset of a prompt request the ledger lookup needs. */
+export type SessionMessagePromptRequest = Pick<
+ AgentPromptRequest,
+ "sessionId" | "sessionMessageId" | "attachments" | "messageId" | "truncateBefore" | "truncateFromMessageId"
+>;
+
/** Resolve provenance and content only from the host ledger, never a caller. */
export async function resolveSessionMessageInput(
host: CollaborationHost,
- request: AgentPromptRequest,
+ request: SessionMessagePromptRequest,
): Promise<SessionMessageInput | undefined> {
if (request.sessionMessageId === undefined) return undefined;
const messageId = typeof request.sessionMessageId === "string"
diff --git a/packages/host-runtime/src/turn-events.ts b/packages/host-runtime/src/turn-events.ts
new file mode 100644
index 000000000..1b74953e2
--- /dev/null
+++ b/packages/host-runtime/src/turn-events.ts
@@ -0,0 +1,330 @@
+import {
+ addUsage,
+ applyMessageUpdate,
+ type AgentEventEnvelope,
+ type MessageUsage,
+ type UiMessage,
+} from "@pi-desktop/shared";
+
+import { InflightCheckpointer } from "./inflight-checkpoint.js";
+import { TurnPersistence } from "./turn-persistence.js";
+
+export type TurnEventLogger = (
+ level: "info" | "warn" | "error",
+ message: string,
+ data?: Record<string, unknown>,
+) => void;
+
+export type ActiveToolCall = {
+ sessionId: string;
+ toolCallId: string;
+ toolName: string;
+ args: unknown;
+ createdAt: string;
+ startedAtMs: number;
+ turnId?: string;
+ parentToolCallId?: string;
+ agentName?: string;
+};
+
+/** What the pipeline needs to know about turn ownership; the runtime service owns it. */
+export type TurnOwnership = {
+ activeTurnId(sessionId: string): string | undefined;
+ /** A root terminal event naming a turn that no longer owns its session. */
+ isStaleTerminalEvent(envelope: AgentEventEnvelope): boolean;
+ finishTurn(
+ sessionId: string,
+ status: "completed" | "aborted" | "error",
+ errorCode: string | undefined,
+ options: { turnId: string },
+ ): Promise<void>;
+};
+
+export type TurnEventPipelineOptions = {
+ getHost: () => { call<T = unknown>(method: string, params?: unknown): Promise<T>; isAvailable?(): boolean } | null;
+ ownership: TurnOwnership;
+ /** Fan-out of every live event, after the stale-terminal guard. */
+ emit: (envelope: AgentEventEnvelope) => void;
+ log: TurnEventLogger;
+ now?: () => number;
+ checkpointIntervalMs?: number;
+};
+
+/**
+ * The per-event pass of a headless Host: track tool calls, checkpoint the
+ * streaming reply (D299), close the turn on its terminal event, and persist
+ * every completed row through host-core. The desktop runs the same pass in
+ * Electron Main against its file-backed outbox; here the outbox is process
+ * memory with a bounded retry, because a `pi-host` ends only with its
+ * supervisor.
+ */
+export class TurnEventPipeline {
+ private readonly activeToolCalls = new Map<string, ActiveToolCall>();
+ private readonly steeringReplies = new Set<string>();
+ private readonly inflightSnapshots = new Map<string, UiMessage>();
+ private readonly activeTurnUsages = new Map<string, MessageUsage>();
+ private readonly persistence: TurnPersistence;
+ private readonly checkpointer: InflightCheckpointer;
+ private readonly now: () => number;
+
+ constructor(private readonly options: TurnEventPipelineOptions) {
+ this.now = options.now ?? (() => Date.now());
+ this.persistence = new TurnPersistence({
+ getHost: () => options.getHost(),
+ log: (level, message, data) => options.log(level, message, data),
+ });
+ this.checkpointer = new InflightCheckpointer(
+ async (checkpoint) => {
+ const host = options.getHost();
+ if (!host) return;
+ await host.call("session.saveInflightMessage", {
+ sessionId: checkpoint.sessionId,
+ ...(checkpoint.turnId ? { turnId: checkpoint.turnId } : {}),
+ message: checkpoint.message,
+ });
+ },
+ options.checkpointIntervalMs,
+ this.now,
+ );
+ }
+
+ /** The tool call a permission request refers to, if the sidecar announced it. */
+ toolCall(sessionId: string, toolCallId: string): ActiveToolCall | undefined {
+ return this.activeToolCalls.get(toolKey(sessionId, toolCallId));
+ }
+
+ /** Usage accumulated by the session's current turn, then forget it. */
+ takeTurnUsage(sessionId: string): MessageUsage | undefined {
+ const usage = this.activeTurnUsages.get(sessionId);
+ this.activeTurnUsages.delete(sessionId);
+ return usage;
+ }
+
+ resetTurnUsage(sessionId: string): void {
+ this.activeTurnUsages.delete(sessionId);
+ }
+
+ /** Write the session's pending reply checkpoint now; the last text before a crash. */
+ flushCheckpoint(sessionId: string): Promise<void> {
+ return this.checkpointer.flush(sessionId);
+ }
+
+ settleCheckpoint(sessionId: string): void {
+ this.checkpointer.settle(sessionId);
+ }
+
+ /**
+ * A host tool can finish shortly after its turn was aborted. Keep the
+ * metadata long enough for a late tool_end to persist a readable row, then
+ * drop only the calls of that turn.
+ */
+ scheduleToolCallCleanup(sessionId: string, turnId: string, delayMs = 5 * 60 * 1000): void {
+ const prefix = `${sessionId}:`;
+ const timer = setTimeout(() => {
+ for (const [key, call] of this.activeToolCalls) {
+ if (key.startsWith(prefix) && call.turnId === turnId) this.activeToolCalls.delete(key);
+ }
+ }, delayMs);
+ timer.unref?.();
+ }
+
+ /** The sidecar died: every open tool call is interrupted and no reply will finish. */
+ onSidecarExit(): ActiveToolCall[] {
+ const interrupted = [...this.activeToolCalls.values()];
+ this.activeToolCalls.clear();
+ this.steeringReplies.clear();
+ return interrupted;
+ }
+
+ pendingWrites(): number {
+ return this.persistence.size();
+ }
+
+ async dispose(): Promise<void> {
+ await this.checkpointer.flushAll();
+ this.checkpointer.dispose();
+ await this.persistence.flush();
+ this.persistence.dispose();
+ }
+
+ /** One event from the sidecar: fan it out, then apply its persistence effects. */
+ handle(envelope: AgentEventEnvelope): void {
+ const event = envelope.event;
+ if (event.type === "tool_start") {
+ this.activeToolCalls.set(toolKey(envelope.sessionId, event.toolCallId), {
+ sessionId: envelope.sessionId,
+ toolCallId: event.toolCallId,
+ toolName: event.toolName,
+ args: event.args,
+ createdAt: new Date(envelope.ts).toISOString(),
+ startedAtMs: envelope.ts,
+ turnId: envelope.turnId ?? this.options.ownership.activeTurnId(envelope.sessionId),
+ ...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),
+ ...(envelope.agentName ? { agentName: envelope.agentName } : {}),
+ });
+ }
+ // A terminal event for a turn that no longer owns its session must not
+ // clear the current turn's state. Persistence is a separate pass, so the
+ // event is still archived as history.
+ if (!this.options.ownership.isStaleTerminalEvent(envelope)) this.options.emit(envelope);
+ const persisted = this.persist(envelope);
+ if (persisted) {
+ // Replay the completed tool row through the message_end contract, so a
+ // subscriber that missed the original tool_start still gets the row.
+ this.options.emit({ ...envelope, event: { type: "message_end", message: persisted } });
+ }
+ }
+
+ private persist(envelope: AgentEventEnvelope): UiMessage | undefined {
+ const event = envelope.event;
+ const sessionId = envelope.sessionId;
+ const turnId = this.options.ownership.activeTurnId(sessionId);
+ const finish = (status: "completed" | "aborted" | "error", errorCode: string | undefined) =>
+ this.options.ownership
+ .finishTurn(sessionId, status, errorCode, { turnId: envelope.turnId ?? "" })
+ .catch((error: unknown) => {
+ this.options.log("warn", "turn finalization failed", { sessionId, error: String(error) });
+ });
+ switch (event.type) {
+ case "message_start":
+ if (event.message.role === "assistant" && !envelope.parentToolCallId) {
+ this.inflightSnapshots.set(sessionId, event.message);
+ }
+ return;
+ case "message_update":
+ if (event.message.role === "assistant" && !envelope.parentToolCallId) {
+ const message = applyMessageUpdate(this.inflightSnapshots.get(sessionId), event);
+ this.inflightSnapshots.set(sessionId, message);
+ this.checkpointer.observe({ sessionId, turnId: envelope.turnId ?? turnId, message });
+ }
+ return;
+ case "error":
+ this.options.log("error", "agent turn failed", {
+ sessionId,
+ code: event.error.code,
+ message: event.error.message,
+ retriable: event.error.retriable,
+ });
+ if (this.options.ownership.isStaleTerminalEvent(envelope)) return;
+ void finish(event.error.code === "TURN_ABORTED" ? "aborted" : "error", event.error.code);
+ return;
+ case "agent_end":
+ if (this.options.ownership.isStaleTerminalEvent(envelope)) return;
+ void finish("completed", undefined);
+ return;
+ case "turn_end":
+ if (!envelope.parentToolCallId) this.addTurnUsage(sessionId, event.subagentUsage);
+ return;
+ case "message_end":
+ return this.persistMessageEnd(envelope, event.message, event.precedingAssistant, turnId);
+ case "tool_end": {
+ const key = toolKey(sessionId, event.toolCallId);
+ const started = this.activeToolCalls.get(key);
+ this.activeToolCalls.delete(key);
+ this.options.log(
+ event.isError ? "error" : "info",
+ event.isError ? "tool execution failed" : "tool execution completed",
+ {
+ sessionId,
+ turnId: envelope.turnId ?? started?.turnId,
+ toolCallId: event.toolCallId,
+ toolName: started?.toolName ?? "unknown",
+ durationMs: started ? Math.max(0, envelope.ts - started.startedAtMs) : undefined,
+ },
+ );
+ const message: UiMessage = {
+ id: event.toolCallId,
+ role: "tool",
+ content: typeof event.result === "string" ? event.result : JSON.stringify(event.result),
+ createdAt: started?.createdAt ?? new Date(envelope.ts).toISOString(),
+ toolCallId: event.toolCallId,
+ toolName: started?.toolName,
+ toolArgs: started?.args,
+ toolStatus: event.isError ? "error" : "success",
+ toolResult: event.result,
+ ...(event.toolUsage ? { toolUsage: event.toolUsage } : {}),
+ toolCompletedAt: new Date(envelope.ts).toISOString(),
+ toolDurationMs: started ? Math.max(0, envelope.ts - Date.parse(started.createdAt)) : undefined,
+ isError: event.isError,
+ status: "complete",
+ ...(started?.parentToolCallId ? { parentToolCallId: started.parentToolCallId } : {}),
+ ...(started?.agentName ? { agentName: started.agentName } : {}),
+ };
+ void this.persistence.append({
+ sessionId,
+ message,
+ // A late tool_end belongs to the turn that started the tool, even if
+ // another prompt has already opened a newer turn for this session.
+ turnId: started?.turnId ?? envelope.turnId ?? turnId,
+ });
+ return message;
+ }
+ default:
+ return;
+ }
+ }
+
+ private persistMessageEnd(
+ envelope: AgentEventEnvelope,
+ message: UiMessage,
+ precedingAssistant: UiMessage | undefined,
+ turnId: string | undefined,
+ ): undefined {
+ const sessionId = envelope.sessionId;
+ if (message.role === "user" && !envelope.parentToolCallId) {
+ // Steering input accepted during a stream: reserve the current reply
+ // before persisting it, then the user row.
+ const preceding = precedingAssistant?.role === "assistant" ? precedingAssistant : undefined;
+ if (preceding) this.steeringReplies.add(preceding.id);
+ for (const row of [preceding, message]) {
+ if (!row) continue;
+ void this.persistence.append({ sessionId, message: row, turnId: envelope.turnId ?? turnId });
+ }
+ return;
+ }
+ if (message.role === "assistant") {
+ if (!envelope.parentToolCallId) {
+ if (message.usage) this.addTurnUsage(sessionId, message.usage);
+ this.inflightSnapshots.delete(sessionId);
+ const finalId = message.id;
+ this.checkpointer.observe({ sessionId, turnId: envelope.turnId ?? turnId, message });
+ void this.checkpointer.flush(sessionId).finally(() => this.checkpointer.settleIf(sessionId, finalId));
+ }
+ // Empty aborted bubbles are not useful transcript rows. Structured
+ // provider failures remain durable so their details survive a reload.
+ const failed = message.status === "error" || message.status === "aborted";
+ const empty = !(message.content || "").trim() && !(message.thinking || "").trim();
+ const reservedForSteering = this.steeringReplies.delete(message.id);
+ if (failed && empty && !message.error && !reservedForSteering) return;
+ void this.persistence.append({ sessionId, message: subagentTagged(message, envelope), turnId });
+ return;
+ }
+ if (message.role === "tool") {
+ void this.persistence.append({
+ sessionId,
+ message: subagentTagged(message, envelope),
+ turnId: envelope.turnId ?? turnId,
+ });
+ }
+ return;
+ }
+
+ private addTurnUsage(sessionId: string, usage: MessageUsage | undefined): void {
+ if (!usage) return;
+ const next = addUsage(this.activeTurnUsages.get(sessionId), usage);
+ if (next) this.activeTurnUsages.set(sessionId, next);
+ }
+}
+
+function toolKey(sessionId: string, toolCallId: string): string {
+ return `${sessionId}:${toolCallId}`;
+}
+
+function subagentTagged(message: UiMessage, envelope: AgentEventEnvelope): UiMessage {
+ if (!envelope.parentToolCallId) return message;
+ return {
+ ...message,
+ parentToolCallId: envelope.parentToolCallId,
+ ...(envelope.agentName ? { agentName: envelope.agentName } : {}),
+ };
+}
diff --git a/packages/host-runtime/src/turn-persistence.test.ts b/packages/host-runtime/src/turn-persistence.test.ts
new file mode 100644
index 000000000..64634bc9a
--- /dev/null
+++ b/packages/host-runtime/src/turn-persistence.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import type { UiMessage } from "@pi-desktop/shared";
+
+import { TurnPersistence } from "./turn-persistence.js";
+
+function row(id: string): UiMessage {
+ return { id, role: "assistant", content: id, createdAt: "2026-09-18T00:00:00.000Z", status: "complete" };
+}
+
+describe("TurnPersistence", () => {
+ it("writes a session's rows in order and reports nothing pending afterwards", async () => {
+ const written: string[] = [];
+ const persistence = new TurnPersistence({
+ getHost: () => ({
+ async call(_method: string, params: { message: UiMessage }) {
+ written.push(params.message.id);
+ },
+ }),
+ log: () => undefined,
+ });
+ const first = persistence.append({ sessionId: "s", message: row("a") });
+ const second = persistence.append({ sessionId: "s", message: row("b") });
+ expect(persistence.size()).toBe(2);
+ await Promise.all([first, second]);
+ expect(written).toEqual(["a", "b"]);
+ expect(persistence.size()).toBe(0);
+ });
+
+ it("retries while host-core is unavailable and lands the row once it is back", async () => {
+ let attempts = 0;
+ let available = false;
+ const sleeps: number[] = [];
+ const persistence = new TurnPersistence({
+ getHost: () => ({
+ isAvailable: () => available,
+ async call() {
+ attempts += 1;
+ },
+ }),
+ log: () => undefined,
+ sleep: async (ms) => {
+ sleeps.push(ms);
+ if (sleeps.length === 3) available = true;
+ },
+ });
+ await persistence.append({ sessionId: "s", message: row("a") });
+ expect(attempts).toBe(1);
+ expect(sleeps).toEqual([100, 250, 500]);
+ });
+
+ it("treats a duplicate message id as already written and logs other failures", async () => {
+ const logs: string[] = [];
+ let calls = 0;
+ const persistence = new TurnPersistence({
+ getHost: () => ({
+ async call() {
+ calls += 1;
+ if (calls === 1) throw new Error("UNIQUE constraint failed: messages.id");
+ throw Object.assign(new Error("bad row"), { errorCode: "INVALID_ARGUMENT" });
+ },
+ }),
+ log: (_level, message) => logs.push(message),
+ });
+ await persistence.append({ sessionId: "s", message: row("dup") });
+ await persistence.append({ sessionId: "s", message: row("bad") });
+ expect(calls).toBe(2);
+ expect(logs).toEqual(["transcript append failed"]);
+ });
+});
diff --git a/packages/host-runtime/src/turn-persistence.ts b/packages/host-runtime/src/turn-persistence.ts
new file mode 100644
index 000000000..0ebb039e8
--- /dev/null
+++ b/packages/host-runtime/src/turn-persistence.ts
@@ -0,0 +1,119 @@
+import { ErrorCodes, type UiMessage } from "@pi-desktop/shared";
+
+import type { HostRpc } from "./host-ports.js";
+
+export type TurnPersistenceLogger = (
+ level: "warn" | "error",
+ message: string,
+ data?: Record<string, unknown>,
+) => void;
+
+export type MessageAppend = {
+ sessionId: string;
+ message: UiMessage;
+ turnId?: string;
+};
+
+type HostAvailability = HostRpc & { isAvailable?(): boolean };
+
+/** Bounded wait between retries while host-core is restarting. */
+const RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000, 4_000, 8_000] as const;
+
+function isHostUnavailable(error: unknown): boolean {
+ return (error as { errorCode?: string } | null)?.errorCode === ErrorCodes.HOST_UNAVAILABLE;
+}
+
+function isDuplicateMessageIdError(error: unknown): boolean {
+ return /UNIQUE constraint failed: messages\.id/i.test(String(error));
+}
+
+/**
+ * Transcript appends for the headless Host. Rows of one session are written
+ * in order, a write that only failed because host-core was restarting is
+ * retried with a bounded backoff, and a duplicate message id counts as
+ * written (the host already has the row). The queue is process memory: the
+ * desktop keeps a file-backed outbox because a window can close mid-turn,
+ * whereas a `pi-host` process ends only with its supervisor.
+ */
+export class TurnPersistence {
+ private readonly chains = new Map<string, Promise<void>>();
+ private pendingCount = 0;
+ private disposed = false;
+
+ constructor(
+ private readonly deps: {
+ getHost: () => HostAvailability | null;
+ log: TurnPersistenceLogger;
+ sleep?: (ms: number) => Promise<void>;
+ },
+ ) {}
+
+ /** Number of appends not yet acknowledged by host-core. */
+ size(): number {
+ return this.pendingCount;
+ }
+
+ /** Queue one append behind the session's earlier ones; resolves once it landed or was given up. */
+ append(entry: MessageAppend): Promise<void> {
+ if (this.disposed) return Promise.resolve();
+ this.pendingCount += 1;
+ const previous = this.chains.get(entry.sessionId) ?? Promise.resolve();
+ const run = previous
+ .then(() => this.write(entry))
+ .finally(() => {
+ this.pendingCount -= 1;
+ if (this.chains.get(entry.sessionId) === run) this.chains.delete(entry.sessionId);
+ });
+ this.chains.set(entry.sessionId, run);
+ return run;
+ }
+
+ /** Wait until every queued append has been attempted. */
+ async flush(): Promise<void> {
+ await Promise.allSettled([...this.chains.values()]);
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ }
+
+ private async write(entry: MessageAppend): Promise<void> {
+ for (let attempt = 0; ; attempt += 1) {
+ if (this.disposed) return;
+ const host = this.deps.getHost();
+ if (host && (host.isAvailable?.() ?? true)) {
+ try {
+ await host.call("session.appendMessage", {
+ sessionId: entry.sessionId,
+ message: entry.message,
+ ...(entry.turnId ? { turnId: entry.turnId } : {}),
+ });
+ return;
+ } catch (error) {
+ if (isDuplicateMessageIdError(error)) return;
+ if (!isHostUnavailable(error)) {
+ this.deps.log("warn", "transcript append failed", {
+ sessionId: entry.sessionId,
+ messageId: entry.message.id,
+ error: String(error),
+ });
+ return;
+ }
+ }
+ }
+ const delay = RETRY_DELAYS_MS[Math.min(attempt, RETRY_DELAYS_MS.length - 1)];
+ if (attempt >= RETRY_DELAYS_MS.length * 2) {
+ this.deps.log("error", "transcript append abandoned: host unavailable", {
+ sessionId: entry.sessionId,
+ messageId: entry.message.id,
+ });
+ return;
+ }
+ await (this.deps.sleep ?? defaultSleep)(delay);
+ }
+ }
+}
+
+function defaultSleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
diff --git a/packages/host-runtime/tsconfig.json b/packages/host-runtime/tsconfig.json
new file mode 100644
index 000000000..60d923f0b
--- /dev/null
+++ b/packages/host-runtime/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "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" },
+ { "path": "../agent-runtime" }
+ ]
+}
diff --git a/packages/host-runtime/vitest.config.ts b/packages/host-runtime/vitest.config.ts
new file mode 100644
index 000000000..ae847ff6d
--- /dev/null
+++ b/packages/host-runtime/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.yaml
index 00dc0bfef..b80c354f6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -43,6 +43,9 @@ importers:
'@pi-desktop/agent-runtime':
specifier: workspace:*
version: link:../../packages/agent-runtime
+ '@pi-desktop/host-runtime':
+ specifier: workspace:*
+ version: link:../../packages/host-runtime
'@pi-desktop/i18n':
specifier: workspace:*
version: link:../../packages/i18n
@@ -205,6 +208,28 @@ importers:
specifier: ^4.1.10
+ packages/host-runtime:
+ dependencies:
+ '@pi-desktop/agent-host':
+ specifier: workspace:*
+ version: link:../agent-host
+ '@pi-desktop/agent-runtime':
+ specifier: workspace:*
+ version: link:../agent-runtime
+ '@pi-desktop/shared':
+ specifier: workspace:*
+ version: link:../shared
+ devDependencies:
+ '@types/node':
+ specifier: ^24.13.3
+ version: 24.13.3
+ typescript:
+ specifier: ^5.9.3
+ version: 5.9.3
+ vitest:
+ specifier: ^4.1.10
+
packages/i18n:
devDependencies:
typescript: