Skip to content

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

27.8 KB
Raw Blame
import { parseMcpServerIds, parseMcpToolNames } from "./mcp-tool-selection.js";
/**
 * Node pi agent sidecar.
 * Protocol: NDJSON JSON-RPC on stdio with Electron main.
 * Host access is proxied through main (single host-core process).
 */
import { randomUUID } from "node:crypto";
import type { ModelAuth } from "@earendil-works/pi-ai";
import { ParentHostProxy } from "./parent-host-proxy.js";
import { visionFromModelConfig } from "./model-capabilities.js";
import { hydrateAttachmentHistory } from "./attachment-history.js";
import { classifyAgentError } from "./agent-errors.js";
import { readLocalRequestErrorDetails } from "./local-request-errors.js";
import {
  DesktopAgentRuntime,
  type PluginToolDef,
  type RuntimePrompt,
  type RuntimePromptAttachment,
  type RuntimeProviderConfig,
} from "./runtime.js";
import type { PluginSkillDef } from "./plugin-skills-prompt.js";
import type { SessionMessageOrigin, TrustedExtensionSpec } from "@pi-desktop/shared";
import type { ProjectInstructions } from "./project-instructions.js";
import type { CustomSystemPrompt } from "./custom-system-prompt.js";
import {
  normalizeSupportedThinkingLevels,
  normalizeThinkingLevel,
} from "./sidecar-config.js";
import { matchesExpectedTurnId } from "./turn-target.js";
import { applyNodeNetworkProxy } from "./node-proxy.js";
import { applyAdditiveDefaultCaCertificates } from "./system-ca.js";
import { NATIVE_PI_SESSION_PREFIX } from "./native-pi-session-id.js";
import {
  parseModeLaunchParams,
  parseModePromptTurn,
  parseModeTurnNotice,
} from "./modes/mode-params.js";
import {
  isCommandShellOption,
  normalizeNetworkProxy,
  OAUTH_AUTH_KIND,
  readNdjsonLines,
} from "@pi-desktop/shared";
import type {
  AgentEventEnvelope,
  AskToolResolution,
  SubagentDefinition,
  ContextCompactionRecord,
  ContextCompactionSettings,
  CommandShellOption,
  ModeTurnContext,
  PlanExecution,
  SessionThinkingLevel,
  UiMessage,
} from "@pi-desktop/shared";

type RuntimeMap = Map<string, DesktopAgentRuntime>;

type NativePiServiceFactory = typeof import("./native-pi-session.js")["nativePiService"];
let nativePiServiceFactory: NativePiServiceFactory | undefined;

async function getNativePiService() {
  if (!nativePiServiceFactory) {
    nativePiServiceFactory = (await import("./native-pi-session.js")).nativePiService;
  }
  return nativePiServiceFactory();
}

function nativeProjectPaths(params: { projectPaths?: unknown } | undefined): string[] {
  const value = params?.projectPaths;
  return Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
}

const runtimes: RuntimeMap = new Map();
const hostProxy = new ParentHostProxy();
const testRuntimeIds = new WeakMap<DesktopAgentRuntime, string>();
function testRuntimeIdentity(sessionId: string) {
  if (process.env.PI_DESKTOP_PLAN_UI_PROBE !== "1") {
    throw Object.assign(new Error("test runtime identity RPC is unavailable"), {
      rpcCode: -32601,
    });
  }
  const runtime = runtimes.get(sessionId);
  if (!runtime) {
    throw Object.assign(new Error("runtime not found for session"), {
      rpcCode: -32000,
      errorCode: "RUNTIME_NOT_FOUND",
    });
  }
  let runtimeId = testRuntimeIds.get(runtime);
  if (!runtimeId) {
    runtimeId = randomUUID();
    testRuntimeIds.set(runtime, runtimeId);
  }
  const status = runtime.getStatus();
  return {
    runtimeId,
    sessionId: runtime.sessionId,
    mode: runtime.getMode(),
    modelId: status.modelId,
    status: {
      isRunning: status.isRunning,
      currentTurnId: status.currentTurnId,
      planningState: status.planningState,
      pendingToolConfirmations: status.pendingToolConfirmations,
      ...(status.pendingPlanId ? { pendingPlanId: status.pendingPlanId } : {}),
    },
  };
}

type RuntimeParams = {
  sessionId: string;
  /** Any valid mode id; validated by `parseModeLaunchParams`. */
  mode?: unknown;
  /** Definition of `mode` resolved by Electron main (ADR mode-definitions). */
  modeDefinition?: unknown;
  /** Durable host turn ID for the prompt currently being executed. */
  turnId?: string;
  pluginModelContextEnabled?: boolean;
  thinkingLevel?: SessionThinkingLevel;
  infiniteProviderRetry?: boolean;
  backgroundJobContinuationEnabled?: boolean;
  backgroundCompletion?: UiMessage;
  /** Session `/fast` switch AND the model's opt-in, resolved by main (ADR 0334). */
  fastMode?: boolean;
  /** Opt-in TypeSafe classifier credential resolved by Electron main. */
  jevApiKey?: string;
  /** Set by main only for Agent sessions with computer use switched on. */
  computerUseEnabled?: boolean;
  /** Set by main only for Agent sessions with codemode switched on. */
  codemodeEnabled?: boolean;
  provider: RuntimeProviderConfig;
  commandShell: CommandShellOption;
  pluginTools?: PluginToolDef[];
  pluginSkills?: PluginSkillDef[];
  /** Trusted extensions enabled for this session (D387). */
  trustedExtensions?: TrustedExtensionSpec[];
  /** Delegates this session may spawn through `Task` (ADR 0062). */
  subagents?: SubagentDefinition[];
  /** Provider bindings for pinned models, keyed by `subagentModelKey`. */
  subagentProviders?: Record<string, RuntimeProviderConfig>;
  /** Opted-in override keys, separate from definition-only pinned bindings. */
  subagentModelKeys?: string[];
  scratchDir?: string;
  /** Per-session visualization directory; omitted for remote sessions. */
  visualizationsDir?: string;
  /** Session-bound workspace root supplied by Electron main. */
  projectPath?: string;
  remoteWorkspace?: { hostKey: string; path: string };
  /** An isolated session's worktree root, supplied by Electron main (ADR 0329). */
  workspaceRoot?: string;
  customSystemPrompt?: CustomSystemPrompt;
  projectInstructions?: ProjectInstructions;
  projectMemory?: string;
  compactionSettings?: ContextCompactionSettings;
  attachmentsDir?: string;
  userMessageId?: string;
  sessionMessage?: SessionMessageOrigin;
  attachments?: RuntimePromptAttachment[];
};

function write(msg: unknown) {
  process.stdout.write(JSON.stringify(msg) + "\n");
}

/**
 * Attach the vendor-account auth resolver to a provider binding.
 *
 * The launch payload for an OAuth row carries no credential at all — main
 * strips it — so the sidecar hands pi-ai a callback that asks main for request
 * auth instead. Main answers only for a provider it bound to this session, and
 * only with a short-lived `ModelAuth`; the refresh token stays on its side.
 */
function withVendorAuth<T extends RuntimeProviderConfig>(
  sessionId: string,
  provider: T,
): T {
  if (provider?.authKind !== OAUTH_AUTH_KIND) return provider;
  return {
    ...provider,
    resolveAuth: () =>
      hostProxy.call<ModelAuth>("provider.resolveAuth", {
        sessionId,
        providerId: provider.id,
      }),
  };
}

function notify(method: string, params: unknown) {
  write({ jsonrpc: "2.0", method, params });
}

function respond(id: string | number, result?: unknown, error?: unknown) {
  if (error) write({ jsonrpc: "2.0", id, error });
  else write({ jsonrpc: "2.0", id, result });
}

async function runtimeFor(
  params: RuntimeParams,
  currentPrompt?: string,
  modeTurn?: ModeTurnContext,
): Promise<DesktopAgentRuntime> {
  const sessionId = String(params.sessionId);
  const { mode, modeDefinition } = parseModeLaunchParams(params);
  if (!isCommandShellOption(params.commandShell) || !params.commandShell.available) {
    throw Object.assign(new Error("active command shell is invalid or unavailable"), {
      rpcCode: -32000,
      errorCode: "COMMAND_SHELL_INVALID",
    });
  }
  const providerInput = params.provider;
  const provider = withVendorAuth(sessionId, {
    ...providerInput,
    supportsReasoning: providerInput?.supportsReasoning === true,
    supportedThinkingLevels: normalizeSupportedThinkingLevels(
      providerInput?.supportedThinkingLevels,
      providerInput?.supportsReasoning === true,
    ),
  });
  const thinkingLevel = normalizeThinkingLevel(params.thinkingLevel);
  const pluginTools = params.pluginTools ?? [];
  const pluginSkills = params.pluginSkills ?? [];
  const trustedExtensions = params.trustedExtensions ?? [];
  const subagents = params.subagents ?? [];
  const subagentModelKeys = params.subagentModelKeys ?? [];
  const subagentProviders = Object.fromEntries(
    Object.entries(params.subagentProviders ?? {}).map(([key, pinned]) => [
      key,
      withVendorAuth(sessionId, pinned),
    ]),
  );
  if (
    !provider?.modelId ||
    (!provider.apiKey &&
      provider.authKind !== "none" &&
      provider.authKind !== OAUTH_AUTH_KIND)
  ) {
    throw Object.assign(new Error("model/provider not configured"), {
      rpcCode: -32000,
      errorCode: "MODEL_NOT_CONFIGURED",
    });
  }

  const existing = runtimes.get(sessionId);
  if (existing?.getStatus().isRunning) {
    throw Object.assign(new Error("session already has an active turn"), {
      rpcCode: -32000,
      errorCode: "AGENT_BUSY",
    });
  }
  const config = {
    mode,
    provider,
    thinkingLevel,
    pluginTools,
    pluginSkills,
    trustedExtensions,
    subagents,
    subagentProviders,
    subagentModelKeys,
    jevApiKey: params.jevApiKey,
    computerUseEnabled: params.computerUseEnabled === true,
    codemodeEnabled: params.codemodeEnabled === true,
    projectInstructions: params.projectInstructions,
    customSystemPrompt: params.customSystemPrompt,
    projectMemory: params.projectMemory,
    projectPath: params.projectPath,
    remoteWorkspace: params.remoteWorkspace,
    workspaceRoot: params.workspaceRoot,
    commandShell: params.commandShell,
  };
  // Name the first field that disagrees so a cache-invalidating rebuild can be
  // attributed to its cause (#1948) instead of surfacing only as a reset.
  const mismatch = existing?.firstMismatch(config) ?? null;
  const reusable = existing && mismatch === null ? existing : undefined;
  if (existing && !reusable) {
    console.error(
      `[runtime] rebuilding ${sessionId}: runtime config mismatch (${mismatch ?? "unknown"})`,
    );
    await existing.dispose();
    runtimes.delete(sessionId);
  }
  if (reusable) {
    reusable.setPluginSkills(pluginSkills);
    reusable.setCompactionSettings(params.compactionSettings);
    reusable.setInfiniteProviderRetry(params.infiniteProviderRetry === true);
    reusable.setBackgroundJobContinuationEnabled(params.backgroundJobContinuationEnabled === true);
    reusable.setFastMode(params.fastMode === true);
    reusable.setMode(mode, modeDefinition);
    return reusable;
  }

  const detail = await hostProxy.call<{
    session?: {
      messages?: UiMessage[];
      compaction?: ContextCompactionRecord;
    } | null;
  }>("session.get", { id: sessionId });
  if (!detail?.session) {
    throw Object.assign(new Error("session not found while restoring history"), {
      errorCode: "SESSION_NOT_FOUND",
    });
  }
  let restoredMessages = detail.session.messages ?? [];
  if (params.backgroundCompletion) restoredMessages = restoredMessages.filter(message => message.id !== params.backgroundCompletion!.id);
  // The current prompt is sent separately below. Exclude its persisted row
  // before attachment hydration so it cannot consume the history byte budget.
  if (currentPrompt !== undefined && params.userMessageId) {
    restoredMessages = restoredMessages.filter((message) =>
      message.role !== "user" || message.id !== params.userMessageId,
    );
  }
  const supportsVision = visionFromModelConfig(params.provider.modelConfig);
  let history = await hydrateAttachmentHistory(restoredMessages, {
    scratchDir: params.scratchDir,
    projectPath: params.remoteWorkspace ? undefined : params.projectPath,
    attachmentsDir: params.attachmentsDir,
    supportsVision,
  });
  const compaction = detail.session.compaction;
  // Older callers without a stable message id retain the previous content match.
  // A Host-started mode turn has no user row at all (its content is a fixed
  // continuation notice), so nothing in the history is its prompt.
  const hostStartedTurn = Boolean(params.backgroundCompletion) || (modeTurn !== undefined && modeTurn.origin !== "user");
  if (currentPrompt !== undefined && !params.userMessageId && !hostStartedTurn) {
    const last = history.at(-1);
    if (last?.role === "user" && last.content === currentPrompt) {
      history = history.slice(0, -1);
    }
  }
  const runtime = new DesktopAgentRuntime({
    host: hostProxy,
    ...(params.pluginModelContextEnabled === true ? {
      readPluginModelContext: (input, signal) => signal?.aborted
        ? Promise.resolve(undefined)
        : hostProxy.call("plugins.modelContext.read", input, 600),
    } : {}),
    sessionId,
    mode,
    modeDefinition,
    turnId: params.turnId,
    provider,
    commandShell: params.commandShell,
    thinkingLevel,
    infiniteProviderRetry: params.infiniteProviderRetry === true,
    backgroundJobContinuationEnabled: params.backgroundJobContinuationEnabled === true,
    fastMode: params.fastMode === true,
    jevApiKey: params.jevApiKey,
    computerUseEnabled: config.computerUseEnabled,
    codemodeEnabled: config.codemodeEnabled,
    history,
    compaction,
    compactionSettings: params.compactionSettings,
    pluginTools,
    pluginSkills,
    trustedExtensions,
    subagents,
    subagentProviders,
    subagentModelKeys,
    projectPath: params.projectPath,
    remoteWorkspace: params.remoteWorkspace,
    workspaceRoot: params.workspaceRoot,
    customSystemPrompt: params.customSystemPrompt,
    projectInstructions: params.projectInstructions,
    projectMemory: params.projectMemory,
    scratchDir:
      typeof params.scratchDir === "string" && params.scratchDir
        ? params.scratchDir
        : undefined,
    visualizationsDir:
      typeof params.visualizationsDir === "string" && params.visualizationsDir
        ? params.visualizationsDir
        : undefined,
    onEvent: (envelope: AgentEventEnvelope) => notify("agent.event", envelope),
    onDiagnostic: (diagnostic) => notify("agent.diagnostic", diagnostic),
  });
  runtimes.set(sessionId, runtime);
  // Load failures are diagnostics, never a failed prompt (spec 16 §4.4).
  await runtime.loadTrustedExtensions().catch(() => undefined);
  if (provider.extensionAgentKey) {
    const activated = await runtime.activateTrustedExtensionAgent(
      provider.extensionAgentKey,
      provider.modelId,
    );
    if (!activated) {
      throw Object.assign(new Error("plugin agent is not available"), {
        rpcCode: -32000,
        errorCode: "MODEL_NOT_CONFIGURED",
      });
    }
  }
  return runtime;
}

function classifiedRuntimeError(err: unknown) {
  const candidate = err as {
    code?: unknown;
    message?: unknown;
    retriable?: unknown;
    details?: unknown;
    errorCode?: unknown;
  };
  if (
    typeof candidate?.code === "string" &&
    typeof candidate.message === "string" &&
    typeof candidate.retriable === "boolean"
  ) {
    return {
      code: candidate.code,
      message: candidate.message,
      retriable: candidate.retriable,
      ...(candidate.details !== undefined ? { details: candidate.details } : {}),
    };
  }
  const errorCode = candidate?.errorCode;
  if (typeof errorCode === "string") {
    return {
      code: errorCode,
      message: err instanceof Error ? err.message : String(err),
      retriable: false,
    };
  }
  return classifyAgentError(err);
}

// Host notifications (permissions.request never reaches us — main forwards
// it to the renderer directly; re-emitting it here would duplicate the
// permission dialog delivery).

async function handle(method: string, params: any): Promise<unknown> {
  switch (method) {
    case "sidecar.configure": {
      // Main owns host-core; sidecar only keeps config metadata.
      if (params && typeof params === "object" && "networkProxy" in params) {
        applyNodeNetworkProxy(
          normalizeNetworkProxy(params.networkProxy),
          process.env,
          typeof params.systemProxyRelayUrl === "string"
            ? params.systemProxyRelayUrl
            : undefined,
        );
      }
      return { ok: true, mode: "host-proxy" };
    }
    case "sidecar.health":
      return { ok: true, runtimes: runtimes.size };
    case "native.session.list": {
      const service = await getNativePiService();
      return { sessions: await service.list({ projectPaths: nativeProjectPaths(params) }) };
    }
    case "native.session.search": {
      const service = await getNativePiService();
      return service.search(String(params?.query ?? ""), {
        projectPaths: nativeProjectPaths(params),
      });
    }
    case "native.session.get": {
      const service = await getNativePiService();
      return {
        session: service.detail(String(params.id ?? ""), {
          messageBefore: params.messageBefore,
          messageLimit: params.messageLimit,
          messageAround: params.messageAround,
          contentLimit: params.contentLimit,
        }),
      };
    }
    case "native.session.fork": {
      const service = await getNativePiService();
      return {
        session: service.fork({
          id: String(params.id ?? ""),
          title: typeof params.title === "string" ? params.title : undefined,
          throughMessageId:
            typeof params.throughMessageId === "string" ? params.throughMessageId : undefined,
        }),
      };
    }
    case "agent.testRuntimeIdentity": {
      return testRuntimeIdentity(String(params.sessionId ?? ""));
    }
    case "agent.prompt": {
      const sessionId = String(params.sessionId);
      const content = String(params.content ?? "");
      if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
        const service = await getNativePiService();
        return service.prompt(sessionId, content, (envelope) =>
          notify("native.agent.event", envelope),
          typeof params.userMessageId === "string" ? params.userMessageId : undefined,
        );
      }
      const turnId =
        typeof params.turnId === "string" && params.turnId.trim()
          ? params.turnId
          : randomUUID();
      const attachments = Array.isArray(params.attachments)
        ? (params.attachments as RuntimePromptAttachment[])
        : undefined;
      // Trusted run context from Electron main; a malformed one rejects the
      // prompt before any runtime is touched (ADR mode-definitions).
      const modeTurn = parseModePromptTurn(params.modeTurn, parseModeLaunchParams(params));
      const runtime = await runtimeFor(params, content, modeTurn);
      const userMessageId =
        typeof params.userMessageId === "string" && params.userMessageId
          ? params.userMessageId
          : undefined;
      // The per-turn permission ceiling (spec §7.3) is recorded on the
      // durable turn by host-core and enforced on every `tools.execute`; the
      // runtime carries no copy of it.
      const prompt: RuntimePrompt = {
        text: content,
        ...(params.backgroundCompletion ? { backgroundCompletion: params.backgroundCompletion } : {}),
        mcpServerIds: parseMcpServerIds(params.mcpServerIds),
        mcpToolNames: parseMcpToolNames(params.mcpToolNames),
        attachments,
        ...(params.sessionMessage ? { sessionMessage: params.sessionMessage as SessionMessageOrigin } : {}),
        ...(modeTurn ? { modeTurn } : {}),
      };
      void runtime.prompt(prompt, userMessageId, turnId).catch((err) => {
        // Rejected-prompt path (pre-flight/transport failures). Streamed
        // provider errors surface via stopReason "error" and are classified
        // and emitted by the runtime itself.
        notify("agent.event", {
          sessionId,
          turnId,
          ts: Date.now(),
          event: {
            type: "error",
            error: classifiedRuntimeError(err),
          },
        });
      });
      return { accepted: true, turnId };
    }
    case "agent.steeringContext":
    case "agent.steer": {
      const runtime = runtimes.get(String(params.sessionId ?? ""));
      if (!runtime) {
        throw Object.assign(new Error("No active turn to steer"), { errorCode: "TURN_NOT_FOUND" });
      }
      const expectedTurnId = String(params.expectedTurnId ?? "");
      if (method === "agent.steeringContext") return runtime.steeringContext(expectedTurnId);
      const prompt: RuntimePrompt = {
        text: String(params.content ?? ""),
        attachments: Array.isArray(params.attachments) ? params.attachments : undefined,
        mcpServerIds: parseMcpServerIds(params.mcpServerIds),
        mcpToolNames: parseMcpToolNames(params.mcpToolNames),
      };
      if (prompt.attachments?.some(attachment => attachment.lineRange !== undefined)) {
        runtime.steeringContext(expectedTurnId);
        return runtime.steer(await runtime.resolveFileLineReferences(prompt), expectedTurnId, params.message);
      }
      return runtime.steer(
        prompt,
        expectedTurnId,
        params.message,
      );
    }
    case "agent.executeApprovedPlan": {
      const sessionId = String(params.sessionId ?? "");
      const turnId = String(params.turnId ?? "").trim();
      const execution = params.execution as PlanExecution | undefined;
      if (!sessionId || !turnId || !execution) {
        throw Object.assign(new Error("approved plan execution parameters required"), {
          errorCode: "PLAN_EXECUTION_NOT_FOUND",
        });
      }
      const runtime = await runtimeFor({
        ...params,
        sessionId,
        mode: "agent",
        // Approved plans always execute as the builtin Agent.
        modeDefinition: undefined,
        turnId,
      });
      void runtime.executeApprovedPlan(execution, turnId).catch((err) => {
        notify("agent.event", {
          sessionId,
          turnId,
          ts: Date.now(),
          event: {
            type: "error",
            error: classifiedRuntimeError(err),
          },
        });
      });
      return { accepted: true, turnId };
    }
    case "agent.compact": {
      const runtime = await runtimeFor(params);
      await runtime.compactManually();
      return { accepted: true };
    }
    case "agent.abort": {
      const sessionId = String(params.sessionId);
      const turnId = typeof params.turnId === "string" ? params.turnId : undefined;
      if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
        return (await getNativePiService()).abort(sessionId, turnId);
      }
      const runtime = runtimes.get(sessionId);
      if (!matchesExpectedTurnId(runtime?.getStatus().currentTurnId, turnId)) return { ok: false, aborted: false };
      await hostProxy.call("plans.abort", { sessionId, ...(turnId ? { turnId } : {}) }).catch(() => undefined);
      if (runtime && runtimes.get(sessionId) === runtime && matchesExpectedTurnId(runtime.getStatus().currentTurnId, turnId)) {
        await runtime.abort();
      }
      return { ok: true };
    }
    case "agent.stopSubagents": {
      const runtime = runtimes.get(String(params.sessionId));
      if (!runtime) throw new Error("No active runtime for this session");
      const ids = params.delegationIds;
      if (ids !== undefined && (!Array.isArray(ids) || ids.length === 0 || ids.length > 100 || ids.some(id => typeof id !== "string" || !id.trim()))) {
        throw new Error("Invalid delegation IDs");
      }
      const result = await runtime.stopSubagents(ids as string[] | undefined);
      return { pending: result.details.stopPending?.flatMap(record => typeof record.delegationId === "string" ? [record.delegationId] : []) ?? [] };
    }
    case "agent.stop": {
      const sessionId = String(params.sessionId);
      const turnId = typeof params.turnId === "string" ? params.turnId : undefined;
      if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
        return (await getNativePiService()).abort(sessionId, turnId);
      }
      const runtime = runtimes.get(sessionId);
      if (!matchesExpectedTurnId(runtime?.getStatus().currentTurnId, turnId)) {
        return { requested: false };
      }
      return runtime?.requestGracefulStop() ?? { requested: false };
    }
    case "asktool.resolve": {
      const sessionId = String(params.sessionId ?? "");
      const runtime = runtimes.get(sessionId);
      if (!runtime) {
        throw Object.assign(new Error("runtime not found for asktool request"), {
          errorCode: "ASKTOOL_NOT_FOUND",
        });
      }
      return runtime.resolveAskTool(params as AskToolResolution);
    }
    case "extensions.command.run": {
      const sessionId = String(params.sessionId ?? "");
      const runtime = runtimes.get(sessionId);
      if (!runtime) {
        throw Object.assign(new Error("runtime not found for session"), {
          rpcCode: -32000,
          errorCode: "RUNTIME_NOT_FOUND",
        });
      }
      return runtime.runTrustedExtensionCommand(
        String(params.name ?? ""),
        String(params.args ?? ""),
      );
    }
    case "agent.modeTurnNotice": {
      const runtime = runtimes.get(String(params.sessionId ?? ""));
      return runtime?.modeTurnNotice(parseModeTurnNotice(params)) ?? { applied: false };
    }
    case "agent.getStatus": {
      const sessionId = String(params.sessionId);
      if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
        return (await getNativePiService()).status(sessionId);
      }
      const runtime = runtimes.get(sessionId);
      return {
        status: runtime?.getStatus() ?? {
          sessionId,
          isRunning: false,
          pendingToolConfirmations: 0,
        },
      };
    }
    case "agent.disposeSession": {
      const sessionId = String(params.sessionId);
      if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
        (await getNativePiService()).dispose(sessionId);
        return { ok: true };
      }
      const runtime = runtimes.get(sessionId);
      if (runtime) {
        await runtime.dispose();
        runtimes.delete(sessionId);
      }
      return { ok: true };
    }
    default:
      throw Object.assign(new Error(`method not found: ${method}`), {
        rpcCode: -32601,
      });
  }
}

readNdjsonLines(process.stdin, async (line) => {
  if (!line.trim()) return;
  let msg: any;
  try {
    msg = JSON.parse(line);
  } catch {
    process.stderr.write(
      `[agent-sidecar] Invalid NDJSON frame (${Buffer.byteLength(line, "utf8")} bytes)\n`,
    );
    return;
  }
  // Responses to host.proxy requests from parent
  if (hostProxy.handleParentMessage(msg)) return;

  if (!msg.method || msg.id === undefined) return;
  try {
    const result = await handle(msg.method, msg.params ?? {});
    respond(msg.id, result);
  } catch (err: any) {
    // Restore validation can fail before a runtime/stream exists. Preserve its
    // safe provenance in the existing RPC error data instead of flattening it.
    const local = readLocalRequestErrorDetails(err) ? classifyAgentError(err) : undefined;
    respond(msg.id, undefined, {
      code: err.rpcCode ?? -32000,
      message: local?.message ?? (err instanceof Error ? err.message : String(err)),
      data: local
        ? { errorCode: local.code, retriable: local.retriable, details: local.details }
        : { errorCode: err.errorCode ?? "INTERNAL" },
    });
  }
});

// A rejected promise nobody awaits (a stray async event handler, a background
// host call) must not take every session's runtime down with it: Node's
// default for `unhandledRejection` is to exit the process. Log and carry on;
// the affected session surfaces its own error through the normal event path.
process.on("exit", () => {
  nativePiServiceFactory?.().disposeAll();
});

process.on("unhandledRejection", (reason) => {
  const detail =
    reason instanceof Error
      ? `${reason.name}: ${reason.message}${reason.stack ? `\n${reason.stack}` : ""}`
      : String(reason);
  process.stderr.write(`[agent-sidecar] unhandled promise rejection: ${detail}\n`);
});

const bootProxy = process.env.PI_DESKTOP_PROXY_JSON;
if (bootProxy) {
  try {
    applyNodeNetworkProxy(normalizeNetworkProxy(JSON.parse(bootProxy)));
  } catch {
    // Invalid boot payload is ignored; sidecar.configure will replace it.
  }
}
// The default TLS context is configured before any provider request can be
// issued, so the merged CA set covers every transport this sidecar builds.
applyAdditiveDefaultCaCertificates();
process.stderr.write("[agent-sidecar] ready (host-proxy mode)\n");