Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { randomUUID } from "node:crypto";
import { COMPUTER_CALL_TIMEOUT_MS, DEFAULT_RPC_TIMEOUT_MS, IMAGE_BATCH_TIMEOUT_MS, imageGenerationPrompts, readNdjsonLines, rpcTimeoutMs, rpcErrorFromWire, rpcErrorToWire } 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;
signal: AbortSignal;
}) => 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",
"backgroundJobs.capabilities",
"backgroundJobs.list",
"backgroundJobs.wait",
"backgroundJobs.stop",
"tools.fileBatchCapabilities",
"tools.fileBatchRegister",
"tools.fileBatchSeal",
"tools.fileBatchAbandon",
"tools.fileBatchClose",
"tools.abort",
"tools.list",
"session.get",
"session.appendMessage",
"session.appendCompaction",
"session.replaceMessages",
"workspace.get",
"plans.enter",
"plans.submit",
"plans.pending",
"plans.abort",
// Host validates the live session/run/turn claim; user controls stay private.
"modes.completeStage",
"modes.gateResult",
"project.instructions.resolve",
"provider.resolveAuth",
"provider.resolveSubagentModel",
"delegation.validateRole",
"app.health",
"plugins.modelContext.read",
// 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 localToolControllers = new Map<string, AbortController>();
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;
private pluginModelContextReader?: (params: Record<string, unknown>) => Promise<unknown>;
setPluginModelContextReader(reader: (params: Record<string, unknown>) => Promise<unknown>): void {
this.pluginModelContextReader = reader;
}
// 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();
for (const controller of this.localToolControllers.values()) controller.abort();
this.localToolControllers.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: Omit<Parameters<LocalToolHandler>[0], "signal">,
params: Record<string, unknown>,
): Promise<LocalToolResult> {
const key = `${input.sessionId}:${input.toolCallId}`;
if (this.localToolControllers.has(key)) throw new Error("duplicate local tool call");
const controller = new AbortController();
this.localToolControllers.set(key, controller);
const imageGeneration = params.toolName === "GenerateImages";
const computerUse = params.toolName === "Computer";
// High-risk local tools must be authorised by host-core before the local
// handler runs. Running first and asking later would let a local tool
// bypass the permission broker, which is the whole point of the gate.
const hostAuthorised = imageGeneration || computerUse;
const budget = imageGeneration
? IMAGE_BATCH_TIMEOUT_MS + 130_000
: computerUse
? COMPUTER_CALL_TIMEOUT_MS + 30_000
: DEFAULT_RPC_TIMEOUT_MS;
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
(async () => {
if (hostAuthorised) {
if (imageGeneration) imageGenerationPrompts(input.args);
if (!this.host) throw new Error("host unavailable");
const gate = await this.host.call<LocalToolResult>("tools.execute", params);
if (!gate.ok) return gate;
controller.signal.throwIfAborted();
}
return handler({ ...input, signal: controller.signal });
})(),
new Promise<LocalToolResult>((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error("host-local tool timeout"));
}, budget);
this.localToolTimers.add(timer);
}),
]);
} finally {
controller.abort();
this.localToolControllers.delete(key);
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;
if (this.host && this.host !== host) {
for (const controller of this.localToolControllers.values()) controller.abort();
}
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(() => {
for (const controller of this.localToolControllers.values()) controller.abort();
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 roleValidator?: (sessionId: string, mode: string, role: unknown) => Promise<boolean>;
setRoleValidator(validate: (sessionId: string, mode: string, role: unknown) => Promise<boolean>): void {
this.roleValidator = validate;
}
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 === "tools.abort") {
this.localToolControllers.get(`${params.sessionId}:${params.toolCallId}`)?.abort();
}
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 === "delegation.validateRole") {
const allowed = await this.roleValidator?.(String(params.sessionId), String(params.mode), params.role);
this.writeToChild(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { allowed: allowed === true } }) + "\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 === "plugins.modelContext.read") {
const result = await this.pluginModelContextReader?.(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,
}, params);
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: unknown) {
this.writeToChild(
JSON.stringify({
jsonrpc: "2.0",
id: msg.id,
error: rpcErrorToWire(e),
}) + "\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) {
pending.reject(rpcErrorFromWire(msg.error));
} 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;